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