blob: 42fd49a9de5057e860a777749685c14f6da2556b (
plain)
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
|
#!/bin/sh
##
## === gosher ===
##
## gosher is a simple gopher server in a POSIX shell script:
##
## $ ./gosher [<PORT> [<GOPHERDIR>]
##
## If PORT is not specified, the default is 70. If GOPHERDIR is not
## specified, "./" is assumed
##
##
## (c) 2018 Vincenzo 'KatolaZ' Nicosia <katolaz@freaknet.org>
##
##
######################
##
## If the script is called with basename "gosher", launch the netcat
## server...
##
NETCAT=netcat
OPREFIX=/tmp/outf_
IPREFIX=/tmp/inf_
##DEBUG=
DEBUG=yes
## function
cleanup(){
[ -p "${OPREFIX}$$" ] && rm -f ${OPREFIX}$$
[ -p "${IPREFIX}$$" ] && rm -f ${IPREFIX}$$
exit 1
}
MYNAME=$(basename $0)
if [ -z "${MYNAME#gosher}" ]; then
## we are called as gosher -- launch the server
PORT=${1:-70}
GOPHERDIR=${2:-"./"}
trap cleanup 0 HUP INT TRAP TERM QUIT
OUTF=${OPREFIX}$$
INF=${IPREFIX}$$
mkfifo -m 600 $OUTF $INF
while [ 1 -eq 1 ]; do
./gosher_serve ${GOPHERDIR} <$INF >$OUTF &
${NETCAT} -vv -l -p ${PORT} >$INF <$OUTF
ret=$?
done
exit 0
fi
######################
##
## ...otherwise, serve a request
##
## function
invalid_selector(){
sel="$1"
echo "3Error: Invalid selector: \"$sel\""
echo "."
exit 1
}
## function
serve_selector(){
sel="$1"
cat "${sel}"
exit 0
}
### transform a .gph file into a gophermap
## function
serve_index(){
IDX=$1
IFS='
'
while read line; do
rline=$(echo $line | sed -r -e 's/\r//g')
case $rline in
'['*)
echo $rline | sed -r -e 's/\[//g;s/\]//g;s/\|/\t/g;s/\t//;s/$/\r/g'
;;
t*)
echo $rline | cut -c 2-
;;
*)
echo $line
esac
done < $IDX
printf ".\r\n"
exit 0
}
GOPHERDIR=${1:-"./"}
read selector
selector=$(echo $selector | sed -r 's:\$.*::g;s:\r::g' )
[ -n "$DEBUG" ] && {
echo "iGOPHERDIR: ${GOPHERDIR}"
echo "iselector: \"${selector}\""
}
case $selector in
/?*|"")
RP1=$(realpath "${GOPHERDIR}"/"${selector}" || "")
[ $? -eq 0 ] || invalid_selector "$selector"
RP2=$(realpath "${GOPHERDIR}")"${selector}"
[ $? -eq 0 ] || invalid_selector "$selector"
[ -n "$DEBUG" ] && {
echo "iRP1: ${RP1}"
echo "iRP2: ${RP2}"
}
if [ "${RP1}" = "${RP2}" ]; then
if [ -f "${RP1}" ]; then
serve_selector "${RP1}"
elif [ -d "${RP1}" ]; then
[ -f "${RP1}/gophermap" ] && serve_selector "${RP1}/gophermap"
[ -f "${RP1}/index.gph" ] && serve_index "${RP1}/index.gph"
fi
fi
invalid_selector "$selector"
;;
*)
[ -f "${GOPHERDIR}/gophermap" ] && serve_selector "${GOPHERDIR}/gophermap"
[ -f "${GOPHERDIR}/index.gph" ] && serve_index "${GOPHERDIR}/index.gph"
invalid_selector "/"
;;
esac
|