/
quickserve
executable file
·67 lines (58 loc) · 2.14 KB
/
quickserve
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
#!/bin/bash
# quickserve - easy and convenient HTTP server that serves directory listings and files.
port=8080
fifo=`mktemp /tmp/XXXXXX`
output_buffer=`mktemp /tmp/XXXXXX`
rm -f "$fifo"
mkfifo "$fifo"
echo "Listening on $port" >&2
trap 'echo -e "\rGoodbye."; rm -f "$fifo"; rm -f "$output_buffer"; exit' 2
netcat_help=$(nc -h 2>&1)
while true; do
if [[ "$netcat_help" =~ 'GNU' ]]; then
nc -l -p "$port"
else
nc -l "localhost" "$port"
fi < "$fifo" |
head -n 1 |
cut -d' ' -f2 | (
read uri
echo "[$(date)] $uri" >&2
if [ -d "$uri" ]; then
escuri="$(echo "$uri" | sed -e "s/'/\'/" | sed -e 's/>/\>/' | sed -e 's/</\</')"
echo "<h2>Directory listing for $escuri</h2>" > $output_buffer
echo "<ul>" >> $output_buffer
if [[ "$escuri" != */ ]]; then
escuri="$escuri/"
fi
ls -a "$uri" |
tail -n +2 |
sed -e "s/'/\'/" |
sed -e 's/>/\>/' |
sed -e 's/</\</' |
sed -e "s!\(.*\)!<li><a href='$escuri\1'>\1</a></li>!" >> $output_buffer
echo "</ul>" >> $output_buffer
echo "HTTP/1.1 200 OK"
echo "Connection: close"
echo "Content-Type: text/html"
echo "Content-Length: $(stat $output_buffer | cut -d' ' -f8)"
echo
cat $output_buffer
elif [ -f "$uri" ]; then
mime="$(file --mime-type "$uri" | sed -e 's/^.*: \(.*\)/\1/')"
echo "HTTP/1.1 200 OK"
echo "Connection: close"
echo "Content-Type: $mime"
echo "Content-Length: $(stat "$uri" | cut -d' ' -f8)"
echo
cat "$uri"
else
echo "HTTP/1.1 404 NotFound"
echo "Connection: close"
echo "Content-Type: text/html"
echo "Content-Length: 19"
echo
echo "<h2>Not Found</h2>"
fi
) > "$fifo"
done