]> git.plutz.net Git - cgilite/blob - cgilite.sh
mime types for streaming formats
[cgilite] / cgilite.sh
1 #!/bin/sh
2
3 # Copyright 2017 - 2020 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 # ksh and zsh workaround
22 # set -o posix # ksh, not portable
23 setopt -o OCTAL_ZEROES 2>&-
24
25 CR="\r"
26 BR='
27 '
28 cgilite_timeout=2
29
30 debug(){ [ $# -gt 0 ] && printf '%s\n' "$@" >&2 || tee -a /dev/stderr; }
31
32 PATH(){ 
33   local str seg out
34   [ $# -eq 0 ] && str="$(cat)" || str="$*"
35   while [ "$str" ]; do
36     seg=${str%%/*}; str="${str#*/}"
37     case $seg in
38       ..) out="${out%/}"; out="${out%/*}/";;
39     .|'') out="${out%/}/";;
40        *) out="${out%/}/${seg}";;
41     esac;
42     [ "$seg" = "$str" ] && break
43   done
44   [ "${str}" -a "${out}" ] && printf %s "$out" || printf %s/ "${out%/}"
45 }
46
47 HEX_DECODE='
48   s;\\;\\\\;g; :HEXDECODE_X; s;%([^0-9A-F]);\\045\1;g; tHEXDECODE_X;
49   # Hexadecimal { %00 - %FF } will be transformed to octal { \000 - \377 } for posix printf
50   s;%[0123].;&\\0;g; s;%[4567].;&\\1;g; s;%[89AB].;&\\2;g; s;%[CDEF].;&\\3;g;
51   s;%[048C][0-7]\\.;&0;g; s;%[048C][89A-F]\\.;&1;g; s;%[159D][0-7]\\.;&2;g; s;%[159D][89A-F]\\.;&3;g;
52   s;%[26AE][0-7]\\.;&4;g; s;%[26AE][89A-F]\\.;&5;g; s;%[37BF][0-7]\\.;&6;g; s;%[37BF][89A-F]\\.;&7;g;
53   s;%.[08](\\..);\10;g; s;%.[19](\\..);\11;g; s;%.[2A](\\..);\12;g; s;%.[3B](\\..);\13;g;
54   s;%.[4C](\\..);\14;g; s;%.[5D](\\..);\15;g; s;%.[6E](\\..);\16;g; s;%.[7F](\\..);\17;g;
55 '
56
57 HEX_DECODE(){
58   printf -- "$(printf %s "$1" |sed -E "$HEX_DECODE")"
59 }
60
61 if [ -z "$REQUEST_METHOD" ]; then
62   # no webserver variables means we are running via inetd / ncat
63   # so use builtin web server
64
65   # Use env from inetd as webserver variables
66   REMOTE_ADDR="${TCPREMOTEIP}"
67   SERVER_NAME="${TCPLOCALIP}"
68   SERVER_PORT="${TCPLOCALPORT}"
69
70   # Wait 2 seconds for request or kill connection through watchdog.
71   # Once Request is received the watchdog will be suspended (killed).
72   # At the end of the loop the watchdog will be restarted to enable
73   # timeout for the subsequent request.
74
75   (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
76   while read REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL; do
77     [ "${SERVER_PROTOCOL#HTTP/1.[01]${CR}}" ] && break
78     kill $cgilite_watchdog
79
80     SERVER_PROTOCOL="${SERVER_PROTOCOL%${CR}}"
81     PATH_INFO="$(HEX_DECODE "${REQUEST_URI%\?*}" |PATH)"
82     [ "${REQUEST_URI}" = "${REQUEST_URI#*\?}" ] \
83     && QUERY_STRING='' \
84     || QUERY_STRING="${REQUEST_URI#*\?}"
85     cgilite_headers=''; while read -r hl; do
86       hl="${hl%${CR}}"; [ "$hl" ] || break
87       case $hl in
88         'Content-Length: '*) CONTENT_LENGTH="${hl#*: }";;
89           'Content-Type: '*)   CONTENT_TYPE="${hl#*: }";;
90       esac
91       cgilite_headers="${cgilite_headers}${hl}${BR}"
92     done
93
94     export REMOTE_ADDR SERVER_NAME SERVER_PORT REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL \
95            PATH_INFO QUERY_STRING CONTENT_TYPE CONTENT_LENGTH
96
97     # Try to serve multiple requests, provided that script serves a
98     # Content-Length header.
99     # Without Content-Length header, connection will terminate after
100     # script.
101
102     cgilite_status='200 OK'; cgilite_response=''; cgilite_cl="Connection: close${CR}${BR}";
103     . "$0" | while read -r l; do case $l in
104       Status:*)
105         cgilite_status="${l#Status: }";;
106       Content-Length:*)
107         cgilite_cl=""
108         cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
109       Connection:*)
110         cgilite_cl="${l}${BR}";;
111       $CR) printf '%s %s\r\n%s%s\r\n' \
112              'HTTP/1.1' "${cgilite_status%${CR}}" \
113              "${cgilite_response}${cgilite_response:+${BR}}" "${cgilite_cl}"
114            cat || kill $$
115            [ "${cgilite_cl#Connection}" = "${cgilite_cl}" ]; exit;;
116       *) cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
117     esac; done || exit 0;
118     (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
119   done
120   kill $cgilite_watchdog
121   exit 0
122 fi
123
124 if [ "${REQUEST_METHOD}" = POST -a "${CONTENT_LENGTH:-0}" -gt 0 -a \
125      "${CONTENT_TYPE}" = "application/x-www-form-urlencoded" ]; then
126   cgilite_post="$(head -c "$CONTENT_LENGTH")"
127 fi
128
129 [ "${DEBUG+x}" ] && env >&2
130
131 cgilite_count(){
132   printf %s "&$1" \
133   | grep -oE '&'"$2"'=[^&]*' \
134   | wc -l
135 }
136
137 cgilite_value(){
138   local str="&$1" name="$2" cnt="${3:-1}"
139   while [ $cnt -gt 0 ]; do
140     [ "${str}" = "${str#*&${name}=}" ] && return 1
141     str="${str#*&${name}=}"
142     cnt=$((cnt - 1))
143   done
144   printf -- "$(printf %s "${str%%&*}" |sed -E 's;\+; ;g;'"$HEX_DECODE")"
145 }
146
147 cgilite_keys(){
148   local str="&$1"
149   while [ "${str#*&}" != "${str}" ]; do
150     str="${str#*&}"
151     printf '%s\n' "${str%%=*}"
152   done \
153   | sort -u
154 }
155
156 GET(){ cgilite_value "${QUERY_STRING}" $@; }
157 GET_COUNT(){ cgilite_count "${QUERY_STRING}" $1; }
158 GET_KEYS(){ cgilite_keys "${QUERY_STRING}"; }
159
160 POST(){ cgilite_value "${cgilite_post}" $@; }
161 POST_COUNT(){ cgilite_count "${cgilite_post}" $1; }
162 POST_KEYS(){ cgilite_keys "${cgilite_post}"; }
163
164 REF(){ cgilite_value "${HTTP_REFERER#*\?}" $@; }
165 REF_COUNT(){ cgilite_count "${HTTP_REFERER#*\?}" $1; }
166 REF_KEYS(){ cgilite_keys "${HTTP_REFERER#*\?}"; }
167
168 HEADER(){
169   # Read value of header line. Use this instead of
170   # referencing HTTP_* environment variables.
171   if [ -n "${cgilite_headers+x}" ]; then
172     local str="${BR}${cgilite_headers}"
173     [ "${str}" = "${str#*${BR}${1}: }" ] && return 1
174     str="${str#*${BR}${1}: }"
175     printf %s "${str%%${BR}*}"
176   else
177     local var="HTTP_$(printf %s "$1" |tr a-z- A-Z-)"
178     eval "[ \"\$$var\" ] && printf %s \"\$$var\" || return 1"
179     # eval "printf %s \"\$HTTP_$(printf %s "${1}" |tr a-z A-Z |tr -c A-Z _)\""
180   fi
181 }
182
183 COOKIE(){
184   HEX_DECODE "$(
185     HEADER Cookie \
186     | grep -oE '(^|; ?)'"$1"'=[^;]*' \
187     | sed -En "${2:-1}"'{s;^[^=]+=;;; s;\+; ;g; p;}'
188   )"
189 }
190
191 HTML(){
192   # Escape HTML cahracters
193   # Also escape [, ], and \n for use in html-sh
194   local str out
195   [ $# -eq 0 ] && str="$(cat)" || str="$*"
196   while [ "$str" ]; do
197     case $str in
198       \&*) out="${out}&amp;";;
199       \<*) out="${out}&lt;";;
200       \>*) out="${out}&gt;";;
201       \"*) out="${out}&quot;";;
202       \'*) out="${out}&#x27;";;
203       \[*) out="${out}&#x5B;";;
204       \]*) out="${out}&#x5D;";;
205       "${CR}"*) out="${out}&#x0D;";;
206       "${BR}"*) out="${out}&#x0A;";;
207       *) out="${out}${str%"${str#?}"}";;
208     esac
209     str="${str#?}"
210   done
211   printf %s "$out"
212 }
213
214 URL(){
215   # Escape pathes, so they can be used in link tags and HTTP Headers
216   local str out
217   [ $# -eq 0 ] && str="$(cat)" || str="$*"
218   while [ "$str" ]; do
219     case $str in
220       \&*) out="${out}%26";;
221       \"*) out="${out}%22";;
222       \'*) out="${out}%27";;
223       \?*) out="${out}%3F";;
224       \#*) out="${out}%23";;
225       \[*) out="${out}%5B";;
226       \]*) out="${out}%5D";;
227       \ *) out="${out}%20";;
228       " "*) out="${out}%09";;
229       "${CR}"*) out="${out}%0D";;
230       "${BR}"*) out="${out}%0A";;
231       %*) out="${out}%25";;
232       *) out="${out}${str%"${str#?}"}";;
233     esac
234     str="${str#?}"
235   done
236   printf %s "$out"
237 }
238
239 SET_COOKIE(){
240   # Param: session | +seconds | [date]
241   # Param: name=value
242   # Param: Path= | Domain= | Secure
243   local expire cookie
244   case "$1" in
245     ''|0|session) expire='';;
246     [+-][0-9]*)   expire="$(date -R -d @$(($(date +%s) + $1)))";;
247     *)            expire="$(date -R -d "$1")";;
248   esac
249   cookie="$2"
250
251   printf 'Set-Cookie: %s; HttpOnly; SameSite=Lax' "$cookie"
252   [ -n "$expire" ] && printf '; Expires=%s' "${expire%+????}${expire:+GMT}"
253   [ $# -ge 3 ] && shift 2 && printf '; %s' "$@"
254   printf '\r\n'
255 }
256
257 REDIRECT(){
258   printf '%s: %s\r\n' \
259     Status "303 See Other" \
260     Content-Length 0 \
261     Location "$*"
262   printf '\r\n'
263   exit 0
264 }