]> git.plutz.net Git - cgilite/blob - cgilite.sh
bugfix/typo: correct transformation of header fields into web server variable names
[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     unset PATH_INFO QUERY_STRING cgilite_headers CONTENT_LENGTH CONTENT_TYPE
148
149     [ "${SERVER_PROTOCOL#HTTP/1.[01]${CR}}" ] && break
150     kill $cgilite_watchdog
151
152     SERVER_PROTOCOL="${SERVER_PROTOCOL%${CR}}"
153     PATH_INFO="$(HEX_DECODE % "${REQUEST_URI%\?*}" |PATH)"
154     [ "${REQUEST_URI}" = "${REQUEST_URI#*\?}" ] \
155     && QUERY_STRING='' \
156     || QUERY_STRING="${REQUEST_URI#*\?}"
157     while read -r hl; do
158       hl="${hl%${CR}}"; [ "$hl" ] || break
159       case $hl in
160         'Content-Length: '*) CONTENT_LENGTH="${hl#*: }";;
161           'Content-Type: '*)   CONTENT_TYPE="${hl#*: }";;
162       esac
163       cgilite_headers="${cgilite_headers}${hl}${BR}"
164     done
165
166     export REMOTE_ADDR SERVER_NAME SERVER_PORT REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL \
167            PATH_INFO QUERY_STRING CONTENT_TYPE CONTENT_LENGTH cgilite_headers
168
169     # Try to serve multiple requests, provided that script serves a
170     # Content-Length header.
171     # Without Content-Length header, connection will terminate after
172     # script.
173
174     cgilite_status='200 OK'; cgilite_response=''; cgilite_cl="Connection: close${CR}${BR}";
175     . "$0" | while read -r l; do case $l in
176       Status:*)
177         cgilite_status="${l#Status: }";;
178       Content-Length:*)
179         cgilite_cl=""
180         cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
181       Connection:*)
182         cgilite_cl="${l}${BR}";;
183       $CR) printf '%s %s\r\n%s%s\r\n' \
184              'HTTP/1.1' "${cgilite_status%${CR}}" \
185              "${cgilite_response}${cgilite_response:+${BR}}" "${cgilite_cl}"
186            cat || kill $$
187            [ "${cgilite_cl#Connection}" = "${cgilite_cl}" ]; exit;;
188       *) cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
189     esac; done || exit 0;
190     (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
191   done
192   kill $cgilite_watchdog
193   exit 0
194 fi
195
196 include_cgilite="$0"
197
198 if [ "${REQUEST_METHOD}" = POST -a "${CONTENT_LENGTH:-0}" -gt 0 -a \
199      "${CONTENT_TYPE}" = "application/x-www-form-urlencoded" ]; then
200   cgilite_post="$(head -c "$CONTENT_LENGTH")"
201 fi
202
203 PATH_INFO="$(PATH "/${PATH_INFO#${_BASE}}")"
204
205 debug(){ [ $# -gt 0 ] && printf '%s\n' "$@" >&2 || tee -a /dev/stderr; }
206 [ "${DEBUG+x}" ] && env >&2
207
208 # general helper functions, see GET, POST, and REF below
209
210 cgilite_count(){
211   printf %s "&$1" \
212   | grep -oE '&'"$2"'=[^&]*' \
213   | wc -l
214 }
215
216 cgilite_value(){
217   local str="&$1" name="$2" cnt="${3:-1}"
218   while [ $cnt -gt 0 ]; do
219     [ "${str}" = "${str#*&${name}=}" ] && return 1
220     str="${str#*&${name}=}"
221     cnt=$((cnt - 1))
222   done
223   HEX_DECODE % "$(printf %s "${str%%&*}" |tr + \  )"
224 }
225
226 cgilite_keys(){
227   local str="&$1"
228   while [ "${str#*&}" != "${str}" ]; do
229     str="${str#*&}"
230     printf '%s\n' "${str%%=*}"
231   done \
232   | sort -u
233 }
234
235 # Read arguments from GET, POST, or the query string of the referrer (REF).
236 # Example:
237 # GET varname n
238 #
239 # where n is number for the Nth occurence of a variable and defaults to 1
240 #
241 # *_COUNT varname
242 # -> returns number of ocurences
243 # *_KEYS
244 # -> returns list of available varnames
245
246 GET(){ cgilite_value "${QUERY_STRING}" "$@"; }
247 GET_COUNT(){ cgilite_count "${QUERY_STRING}" $1; }
248 GET_KEYS(){ cgilite_keys "${QUERY_STRING}"; }
249
250 POST(){ cgilite_value "${cgilite_post}" "$@"; }
251 POST_COUNT(){ cgilite_count "${cgilite_post}" $1; }
252 POST_KEYS(){ cgilite_keys "${cgilite_post}"; }
253
254 REF(){ cgilite_value "${HTTP_REFERER#*\?}" "$@"; }
255 REF_COUNT(){ cgilite_count "${HTTP_REFERER#*\?}" $1; }
256 REF_KEYS(){ cgilite_keys "${HTTP_REFERER#*\?}"; }
257
258 HEADER(){
259   # Read value of header line. Use this instead of
260   # referencing HTTP_* environment variables.
261   if [ -n "${cgilite_headers+x}" ]; then
262     local str="${BR}${cgilite_headers}"
263     [ "${str}" = "${str#*${BR}${1}: }" ] && return 1
264     str="${str#*${BR}${1}: }"
265     printf %s "${str%%${BR}*}"
266   else
267     local var="HTTP_$(printf %s "$1" |tr a-z- A-Z_)"
268     eval "[ \"\$$var\" ] && printf %s \"\$$var\" || return 1"
269     # eval "printf %s \"\$HTTP_$(printf %s "${1}" |tr a-z A-Z |tr -c A-Z _)\""
270   fi
271 }
272
273 COOKIE(){
274   # Read value of cookie
275   HEX_DECODE % "$(
276     HEADER Cookie \
277     | grep -oE '(^|; ?)'"$1"'=[^;]*' \
278     | sed -En "${2:-1}"'{s;^[^=]+=;;; s;\+; ;g; p;}'
279   )"
280 }
281
282 HTML(){
283   # Escape HTML cahracters
284   # Also escape [, ], and \n for use in html-sh
285   local str out
286   [ $# -eq 0 ] && str="$(cat)" || str="$*"
287   while [ "$str" ]; do case $str in
288     \&*) out="${out}&amp;";       str="${str#?}";;
289     \<*) out="${out}&lt;";        str="${str#?}";;
290     \>*) out="${out}&gt;";        str="${str#?}";;
291     \"*) out="${out}&quot;";      str="${str#?}";;
292     \'*) out="${out}&#x27;";      str="${str#?}";;
293     \[*) out="${out}&#x5B;";      str="${str#?}";;
294     \]*) out="${out}&#x5D;";      str="${str#?}";;
295     "${CR}"*) out="${out}&#x0D;"; str="${str#?}";;
296     "${BR}"*) out="${out}&#x0A;"; str="${str#?}";;
297     *) out="${out}${str%%[]&<>\"\'${CR}${BR}[]*}"; str="${str#"${str%%[]&<>\"\'${CR}${BR}[]*}"}";;
298   esac; 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 case $str in
307     \&*) out="${out}%26"; str="${str#?}";;
308     \"*) out="${out}%22"; str="${str#?}";;
309     \'*) out="${out}%27"; str="${str#?}";;
310     \?*) out="${out}%3F"; str="${str#?}";;
311     \#*) out="${out}%23"; str="${str#?}";;
312     \[*) out="${out}%5B"; str="${str#?}";;
313     \]*) out="${out}%5D"; str="${str#?}";;
314     \ *) out="${out}%20"; str="${str#?}";;
315     "   "*) out="${out}%09"; str="${str#?}";;
316     "${CR}"*) out="${out}%0D"; str="${str#?}";;
317     "${BR}"*) out="${out}%0A"; str="${str#?}";;
318     %*) out="${out}%25"; str="${str#?}";;
319     *) out="${out}${str%%[]&\"\'\?#     ${CR}${BR}%[]*}"; str="${str#"${str%%[]&\"\'\?#         ${CR}${BR}%[]*}"}";;
320   esac; 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 }