generated is better than vendor in this case
[gofetch.git] / gopherd.sh
CommitLineData
4a19c3b8 1#!/bin/bash
c8b05198 2
4a19c3b8
NR
3# Note: bash is required, sh will fail to output anything to the client
4# Probably related to interactions beteween & and output redirections
82e110d3
NR
5#
6# It seems the timeout on netcat does not work when listening...
7# So you will have to either kill the process or make a last connection
8# (which will not be processed)
4a19c3b8
NR
9
10# $0 [prog] ([port])
11# You can use the evironment variable $QUERY_STRING for the query
c8b05198
NR
12
13[ "$ADDR" = "" ] && ADDR=127.0.0.1
4a19c3b8 14[ "$LOG" = "" ] && LOG=/tmp/gopher.service.err
c8b05198
NR
15[ "$PIDF" = "" ] && PIDF="`mktemp`"
16[ "$TIMEOUT" = "" ] && TIMEOUT=10
17[ "$MAXCON" = "" ] && MAXCON=1024
4a19c3b8 18
c8b05198
NR
19prog="$1"
20port="$2"
82e110d3 21defn="$3"
c8b05198
NR
22[ "$port" = "" ] && port=70
23
24if [ "$prog" = "" ]; then
25 rm "$PIDF"
82e110d3 26 echo "Syntax: $0 [prog] ([port]) (default non-7)" >&2
4a19c3b8
NR
27 echo ' You can use the evironment variable $QUERY_STRING for the query' >&2
28 echo ' The default port is 70' >&2
82e110d3 29 echo ' A default message for non-service (7) request can be given' >&2
4a19c3b8 30 echo ' A filename will be displayed, you can delete it to stop the service' >&2
82e110d3 31 echo ' (you still have to make a last connection on $port)' >&2
c8b05198
NR
32 exit 1
33fi
34
35tmpd=`mktemp -t -d .gopher-service.XXXXXX`
36if [ ! -d "$tmpd" ]; then
37 rm "$PIDF"
38 echo "Cannot create temporary directory, aborting..." >&2
39 exit 2
40fi
41
d6613663 42echo "#!/bin/sh
82e110d3
NR
43# PID: $$
44# PID File (this file): $PIDF
45# You can stop the service by deleting this file then making a last
46# connection (which will not be processed) to the service:
47rm \"$PIDF\"
48nc -q0 $ADDR $port 2>/dev/null </dev/null
49" > "$PIDF"
50
51chmod u+rx "$PIDF"
52
c8b05198
NR
53echo "$PIDF"
54
55i=0
56while [ -e "$PIDF" ]; do
57 i=`expr $i + 1`
58 [ $i -gt "$MAXCON" ] && i=1
59 fifo="$tmpd/fifo.$i"
4a19c3b8 60 rm -f "$fifo" 2>/dev/null
c8b05198
NR
61 mkfifo "$fifo"
62 < "$fifo" nc -l -q0 -w"$TIMEOUT" "$ADDR" -p "$port" | (
82e110d3
NR
63 if [ -e "$PIDF" ]; then
64 read -r query
65 selector="`echo "$query" | cut -f1 -d' ' | sed 's:[\r\n]::g'`"
66 query="`echo "$query" | cut -f2 -d' ' | sed 's:[\r\n]::g'`"
67 if [ "$query" = "" ]; then
68 if [ "$defn" = "" ]; then
69 echo "7Search $selector $ADDR $port"
70 else
71 echo "$defn"
72 fi
73 else
74 QUERY_STRING="$query" "$prog" 2>> "$LOG" &
75 fi
76 fi
c8b05198
NR
77 ) > "$fifo"
78done
4a19c3b8 79rm -rf "$tmpd" 2>/dev/null
d6613663 80