forked from ColasNahaboo/cgibashopts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbash.cgi
284 lines (251 loc) · 8.34 KB
/
bash.cgi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#!/bin/bash
# Author: (c) Colas Nahaboo http://colas.nahaboo.net with a MIT License.
# See https://github.com/ColasNahaboo/cgibashopts
# Author: (c) Domain https://github.com/Domain with a MIT License.
# See https://github.com/Domain/bash.cgi
# Uses the CGI env variables REQUEST_METHOD CONTENT_TYPE QUERY_STRING
declare -x BASHCGI_RELEASE=5.1.0
declare -x BASHCGI_VERSION="${BASHCGI_RELEASE%%.*}"
declare cr=$'\r'
declare nl=$'\n'
declare response_content_type=''
declare -A FORMS
declare -A COOKIES
declare -A SET_COOKIES
export FORMFILES=
export FORMQUERY=
export BASHCGI_DIR="${BASHCGI_ROOT:-${TMPDIR:-/tmp}}/bash.cgi.dir"
export BASHCGI_UPLOAD="$BASHCGI_DIR/upload"
BASHCGI_TMP="$BASHCGI_DIR/tmp"
BASHCGI_SESSION="$BASHCGI_DIR/session"
bashcgi_clean() {
[ -f "$BASHCGI_TMP" ] && rm -rf "$BASHCGI_TMP"
}
overtrap() {
local handler="$1"
shift
local signals=$@
for sig in "${signals[@]}"; do
local cur="$(trap -p $sig | sed -nr "s/trap -- '(.*)' $sig\$/\1/p")"
if test ${cur:+x}; then
trap "{ $cur; }; { $handler; }" $sig
else
trap "$handler" $sig
fi
done
}
overtrap bashcgi_clean EXIT
trace() {
[ -n "$BASHCGI_DEBUG" ] && mkdir -p "$(dirname "$BASHCGI_DEBUG")" > /dev/null 2>&1 && echo "$@" >> "${BASHCGI_DEBUG}"
}
# decodes the %XX url encoding in $1, same as urlencode -d but faster
# removes carriage returns to force unix newlines, converts + into space
urldecode() {
local v="${1//+/ }" d r=''
while [ -n "$v" ]; do
if [[ $v =~ ^([^%]*)%([0-9a-fA-F][0-9a-fA-F])(.*)$ ]]; then
eval d="\$'\x${BASH_REMATCH[2]}'"
[ "$d" = "$cr" ] && d=
r="$r${BASH_REMATCH[1]}$d"
v="${BASH_REMATCH[3]}"
else
r="$r$v"
break
fi
done
echo "$r"
}
# the reverse of urldecode above
urlencode() {
local length="${#1}" i c
for ((i = 0; i < length; i++)); do
c="${1:i:1}"
case $c in
[a-zA-Z0-9.~_-]) echo -n "$c" ;;
*) printf '%%%02X' "'$c" ;;
esac
done
}
handle_upload() {
if [[ ${CONTENT_TYPE:-} =~ ^multipart/form-data\;[[:space:]]*boundary=([^\;]+) ]]; then
local sep="--${BASH_REMATCH[1]}"
local OIFS="$IFS"
IFS=$'\r'
while read -r line; do
if [[ $line =~ ^Content-Disposition:\ *form-data\;\ *name=\"([^\"]+)\"(\;\ *filename=\"([^\"]+)\")? ]]; then
local var="${BASH_REMATCH[1]}"
local val="${BASH_REMATCH[3]}"
[[ $val =~ [%+] ]] && val=$(urldecode "$val")
local type=
read -r line
while [ -n "$line" ]; do
if [[ $line =~ ^Content-Type:\ *text/plain ]]; then
type=txt
elif [[ $line =~ ^Content-Type: ]]; then # any other type
type=bin
fi
read -r line
done
trace "Found form file ${var}:${val}, type ${type}"
if [ "$type" = bin ]; then # binary file upload
# binary-read stdin till next step
sed -n -e "{:loop p; n;/^$sep/q; b loop}" >$BASHCGI_TMP
[ $BASHCGI_TMP != /dev/null ] &&
truncate -s -2 $BASHCGI_TMP # remove last \r\n
elif [ "$type" = txt ]; then # text file upload
local lp=
while read -r line; do
[[ $line =~ ^"$sep" ]] && break
echo -n "$lp$line"
lp="$nl"
done >$BASHCGI_TMP
else # string, possibly multi-line
val=
while read -r line; do
[[ $line =~ ^"$sep" ]] && break
val="$val${val:+$nl}${line}"
done
fi
if [ -n "$type" ]; then
if [ $BASHCGI_TMP != /dev/null ]; then
if [ -n "$val" ]; then
trace "Moving file $BASHCGI_TMP to $BASHCGI_UPLOAD/$var"
# a file was uploaded, even empty
[ -n "$FORMFILES" ] || mkdir -p "$BASHCGI_UPLOAD"
FORMFILES="$FORMFILES${FORMFILES:+ }$var"
declare -x "FORMFILE_$var=$BASHCGI_UPLOAD/${var}"
mv $BASHCGI_TMP "$BASHCGI_UPLOAD/${var}"
else
rm -f $BASHCGI_TMP
fi
fi
fi
FORMS["$var"]="$val"
fi
done
IFS="$OIFS"
return 0
fi
return 1
}
extract() {
declare -n aa="$1"
shift
local s="$@"
trace "Extracting $s ..."
while [[ $s =~ ^([^=]*)=([^\&\;]*)[\;\&]*(.*)$ ]]; do
local var="$(echo "${BASH_REMATCH[1]}" | xargs)"
local val="$(echo "${BASH_REMATCH[2]}" | xargs)"
s="${BASH_REMATCH[3]}"
[[ $var =~ [%+] ]] && var="$(urldecode "$var")"
[[ $val =~ [%+] ]] && val="$(urldecode "$val")"
aa["$var"]="$val"
trace "Found key '$var', value '$val'"
done
}
parse_request() {
local s=""
if [ "${REQUEST_METHOD:-}" = POST ]; then
trace "Found POST"
handle_upload && s="${QUERY_STRING:-}" || s="$(cat)&${QUERY_STRING:-}"
else
trace "POST not found"
s="${QUERY_STRING:-}"
fi
# regular (no file uploads) arguments processing
if [[ $s =~ = ]]; then # modern & (or ;) separated list of key=value
extract FORMS "$s"
else # legacy indexed search
FORMQUERY=$(urldecode "$s")
fi
}
parse_cookies() {
trace "Parsing cookies ... '${HTTP_COOKIE:-}'"
extract COOKIES "${HTTP_COOKIE:-}"
}
set_cookie() {
local key=$(urlencode "$1")
local value=$(urlencode "$2")
local opts=''
[ $# -gt 2 ] && { shift 2; opts=";$*"; }
SET_COOKIES["$key"]="$value$opts"
}
content_type()
{
[ $# -eq 1 ] || return 1
[ -z "${response_content_type}" ] || return 2
response_content_type=$1
for k in "${!SET_COOKIES[@]}"; do
echo "Set-Cookie: $k=${SET_COOKIES[$k]}"
done
echo "Content-Type: $1; charset=utf-8"
echo "Cache-Control: no-cache"
echo "Content-range: bytes */*" # this prevent mod_deflate buffering
echo
}
date2stamp () {
date --date "$1" +%s
}
stamp2date (){
date --date @$1 "+%Y-%m-%d %T"
}
dateDiff (){
declare -i sec=86400
case $1 in
-s) sec=1; shift;;
-m) sec=60; shift;;
-h) sec=3600; shift;;
-d) sec=86400; shift;;
*) sec=86400;;
esac
local date1=$(date2stamp "$1")
local date2=$(date2stamp "$2")
local diffSec=$((date2-date1))
echo $((diffSec/sec))
}
new_session() {
local sid=$(cat /proc/sys/kernel/random/uuid)
local sfile="$BASHCGI_SESSION/$sid"
mkdir -p "$BASHCGI_SESSION"
touch "$sfile"
trace "new session $sid in $BASHCGI_SESSION"
declare -i sec=${1:-3600*24*30}
local expired=$(date -d "now +$sec seconds" "+%Y-%m-%d %T")
echo "declare -x bashcgi_expired=\"$expired\"" >> "$sfile"
echo "$sid"
}
check_session() {
local sid="$1"
local sfile="$BASHCGI_SESSION/$sid"
trace "checking session file $sfile ..."
[ -f "$sfile" ] && source "$sfile" || { trace "fail to load $sfile"; return -1; }
trace "checking expired date $bashcgi_expired ..."
[ -n "$bashcgi_expired" ] && [ $(dateDiff -s "now" "$bashcgi_expired") -gt 0 ] ||
{ rm -rf "$sfile"; trace "session expired at $bashcgi_expired"; return -2; }
shift
local keys="$@"
declare -i i=1
for k in "$@"; do
[ -n "${!k}" ] && trace "key $k=${!k} confirmed" || { trace "missing key $k"; return i; }
((i++))
done
trace "session $sid is ok"
}
save_session() {
trace "saving session $#: '$@'"
check_session $1 && trace "check passed" || { trace "fail to save session"; return 1; }
local sid="$1"
local sfile="$BASHCGI_SESSION/$sid"
shift
for v in "$@"; do
grep "$v" "$sfile" > /dev/null 2>&1 || echo "$v" >> "$sfile"
done
}
delete_session() {
local sid="$1"
local sfile="$BASHCGI_SESSION/$sid"
rm -rf "$sfile"
}
mkdir -p "$BASHCGI_DIR" > /dev/null 2>&1 || trace "Fail to mkdir $BASHCGI_DIR"
parse_request
parse_cookies