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