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