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