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