| 1 | #!/bin/bash |
| 2 | |
| 3 | # Note: bash is required, sh will fail to output anything to the client |
| 4 | # Probably related to interactions beteween & and output redirections |
| 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) |
| 9 | |
| 10 | # $0 [prog] ([port]) |
| 11 | # You can use the evironment variable $QUERY_STRING for the query |
| 12 | |
| 13 | [ "$ADDR" = "" ] && ADDR=127.0.0.1 |
| 14 | [ "$LOG" = "" ] && LOG=/tmp/gopher.service.err |
| 15 | [ "$PIDF" = "" ] && PIDF="`mktemp`" |
| 16 | [ "$TIMEOUT" = "" ] && TIMEOUT=10 |
| 17 | [ "$MAXCON" = "" ] && MAXCON=1024 |
| 18 | |
| 19 | prog="$1" |
| 20 | port="$2" |
| 21 | defn="$3" |
| 22 | [ "$port" = "" ] && port=70 |
| 23 | |
| 24 | if [ "$prog" = "" ]; then |
| 25 | rm "$PIDF" |
| 26 | echo "Syntax: $0 [prog] ([port]) (default non-7)" >&2 |
| 27 | echo ' You can use the evironment variable $QUERY_STRING for the query' >&2 |
| 28 | echo ' The default port is 70' >&2 |
| 29 | echo ' A default message for non-service (7) request can be given' >&2 |
| 30 | echo ' A filename will be displayed, you can delete it to stop the service' >&2 |
| 31 | echo ' (you still have to make a last connection on $port)' >&2 |
| 32 | exit 1 |
| 33 | fi |
| 34 | |
| 35 | tmpd=`mktemp -t -d .gopher-service.XXXXXX` |
| 36 | if [ ! -d "$tmpd" ]; then |
| 37 | rm "$PIDF" |
| 38 | echo "Cannot create temporary directory, aborting..." >&2 |
| 39 | exit 2 |
| 40 | fi |
| 41 | |
| 42 | echo "#!/bin/sh |
| 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: |
| 47 | rm \"$PIDF\" |
| 48 | nc -q0 $ADDR $port 2>/dev/null </dev/null |
| 49 | " > "$PIDF" |
| 50 | |
| 51 | chmod u+rx "$PIDF" |
| 52 | |
| 53 | echo "$PIDF" |
| 54 | |
| 55 | i=0 |
| 56 | while [ -e "$PIDF" ]; do |
| 57 | i=`expr $i + 1` |
| 58 | [ $i -gt "$MAXCON" ] && i=1 |
| 59 | fifo="$tmpd/fifo.$i" |
| 60 | rm -f "$fifo" 2>/dev/null |
| 61 | mkfifo "$fifo" |
| 62 | < "$fifo" nc -l -q0 -w"$TIMEOUT" "$ADDR" -p "$port" | ( |
| 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 |
| 77 | ) > "$fifo" |
| 78 | done |
| 79 | rm -rf "$tmpd" 2>/dev/null |
| 80 | |