]> git.plutz.net Git - cgilite/blob - cgilite.sh
ddad1d4811c7635c8032c08620666fec9a9b2232
[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     QUERY_STRING="${REQUEST_URI#*\?}"
81     cgilite_headers=''; while read -r hl; do
82       hl="${hl%${CR}}"; [ "$hl" ] || break
83       case $hl in
84         'Content-Length: '*) CONTENT_LENGTH="${hl#*: }";;
85           'Content-Type: '*)   CONTENT_TYPE="${hl#*: }";;
86       esac
87       cgilite_headers="${cgilite_headers}${hl}${BR}"
88     done
89
90     export REMOTE_ADDR SERVER_NAME SERVER_PORT REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL \
91            PATH_INFO QUERY_STRING CONTENT_TYPE CONTENT_LENGTH
92
93     # Try to serve multiple requests, provided that script serves a
94     # Content-Length header.
95     # Without Content-Length header, connection will terminate after
96     # script.
97
98     cgilite_status='200 OK'; cgilite_response=''; cgilite_cl="Connection: close${CR}";
99     . "$0" | while read -r l; do case $l in
100       Status:*) cgilite_status="${l#Status: }";;
101       Content-Length:*) cgilite_cl="${l}";;
102       $CR) printf '%s %s\r\n%s%s\n\r\n' \
103              'HTTP/1.1' "${cgilite_status%${CR}}" \
104              "${cgilite_response}${cgilite_response:+${BR}}" "${cgilite_cl}"
105            cat || kill $$
106            [ "${cgilite_cl#Connection}" = "${cgilite_cl}" ]; exit;;
107       *) cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
108     esac; done || exit 0;
109     (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
110   done
111   kill $cgilite_watchdog
112   exit 0
113 fi
114
115 if [ "${REQUEST_METHOD}" = POST -a "${CONTENT_LENGTH:-0}" -gt 0 -a \
116      "${CONTENT_TYPE}" = "application/x-www-form-urlencoded" ]; then
117   cgilite_post="$(head -c "$CONTENT_LENGTH")"
118 fi
119
120 [ "${DEBUG+x}" ] && env >&2
121
122 cgilite_count(){
123   printf %s "&$1" \
124   | grep -oE '&'"$2"'=[^&]*' \
125   | wc -l
126 }
127
128 cgilite_value(){
129   local str="&$1" name="$2" cnt="${3:-1}"
130   while [ $cnt -gt 0 ]; do
131     [ "${str}" = "${str#*&${name}=}" ] && return 1
132     str="${str#*&${name}=}"
133     cnt=$((cnt - 1))
134   done
135   printf -- "$(printf %s "${str%%&*}" |sed -E 's;\+; ;g;'"$HEX_DECODE")"
136 }
137
138 cgilite_keys(){
139   local str="&$1"
140   while [ "${str#*&}" != "${str}" ]; do
141     str="${str#*&}"
142     printf '%s\n' "${str%%=*}"
143   done \
144   | sort -u
145 }
146
147 GET(){ cgilite_value "${QUERY_STRING}" $@; }
148 GET_COUNT(){ cgilite_count "${QUERY_STRING}" $1; }
149 GET_KEYS(){ cgilite_keys "${QUERY_STRING}"; }
150
151 POST(){ cgilite_value "${cgilite_post}" $@; }
152 POST_COUNT(){ cgilite_count "${cgilite_post}" $1; }
153 POST_KEYS(){ cgilite_keys "${cgilite_post}"; }
154
155 REF(){ cgilite_value "${HTTP_REFERER#*\?}" $@; }
156 REF_COUNT(){ cgilite_count "${HTTP_REFERER#*\?}" $1; }
157 REF_KEYS(){ cgilite_keys "${HTTP_REFERER#*\?}"; }
158
159 HEADER(){
160   # Read value of header line. Use this instead of
161   # referencing HTTP_* environment variables.
162   if [ -n "${cgilite_headers+x}" ]; then
163     local str="${BR}${cgilite_headers}"
164     [ "${str}" = "${str#*${BR}${1}: }" ] && return 1
165     str="${str#*${BR}${1}: }"
166     printf %s "${str%%${BR}*}"
167   else
168     local var="HTTP_$(printf %s "$1" |tr a-z- A-Z-)"
169     eval "[ \"\$$var\" ] && printf %s \"\$$var\" || return 1"
170     # eval "printf %s \"\$HTTP_$(printf %s "${1}" |tr a-z A-Z |tr -c A-Z _)\""
171   fi
172 }
173
174 COOKIE(){
175   HEX_DECODE "$(
176     HEADER Cookie \
177     | grep -oE '(^|; ?)'"$1"'=[^;]*' \
178     | sed -En "${2:-1}"'{s;^[^=]+=;;; s;\+; ;g; p;}'
179   )"
180 }
181
182 HTML(){
183   # HTML Entity Coding
184   # Prints UTF-8 string as decimal Unicode Code Points
185   # Useful for escaping user input for use in HTML text and attributes
186   { [ $# -eq 0 ] && cat || printf %s "$*"; } \
187   | hexdump -ve '/1 "%03o\n"' \
188   | while read n; do
189     case $n in
190       # bitbanging octal UTF-8 chains into singular 7 digit octal numbers
191       [01]??) printf '0000%s' $n;; # 7 bit ASCII character, nothing to do
192       2??)    printf '%s' ${n#2};; # tail fragment, append 6 bit
193       3[0123]?) printf '000%s' ${n#3};; # 2 octet (11 bit) chain start
194       34?) printf '00%s' ${n#34};; # 3 octet (16 bit) chain start
195       35?) printf '01%s' ${n#35};; # 3 octet chain start, high
196       36?) printf '%s' ${n#36};;   # 4 octet (21 bit) chain start
197     esac
198   done \
199   | sed -E 's;.{7};&\n;g;' \
200   | while read n; do
201     printf '&#%d;' $((0$n))
202   done
203 }
204
205 URL(){
206   # Code every character in URL escape hex format
207   # except alphanumeric ascii
208
209   { [ $# -eq 0 ] && cat || printf %s "$*"; } \
210   | hexdump -v -e '/1 ",%02X"' \
211   | sed 's;,;%;g; s;%2F;/;g;'
212 }
213
214 SET_COOKIE(){
215   # Param: session | +seconds | [date]
216   # Param: name=value
217   # Param: Path= | Domain= | Secure
218   local expire cookie
219   case "$1" in
220     ''|0|session) expire='';;
221     [+-][0-9]*)   expire="$(date -R -d @$(($(date +%s) + $1)))";;
222     *)            expire="$(date -R -d "$1")";;
223   esac
224   cookie="$2"
225
226   printf 'Set-Cookie: %s; HttpOnly; SameSite=Lax' "$cookie"
227   [ -n "$expire" ] && printf '; Expires=%s' "${expire%+????}${expire:+GMT}"
228   [ $# -ge 3 ] && shift 2 && printf '; %s' "$@"
229   printf '\r\n'
230 }
231
232 REDIRECT(){
233   printf '%s: %s\r\n' \
234     Status "303 See Other" \
235     Content-Length 0 \
236     Location "$*"
237   printf '\r\n'
238   exit 0
239 }