6 *) echo >&2 "usage: $0 {start|stop|restart|status} HOST"; exit 1 ;;
12 echo "$*" >"$file.new"
13 mv "$file.new" "$file"
16 runssh () { ssh -T -oControlPath="./$host.ctrl" "$@"; }
20 ## Shut down an existing connection if there is one.
21 if [ -S "$host.ctrl" ]; then
22 runssh -Oexit "$host" >/dev/null 2>/dev/null || :
25 ## If there's still a socket, then work out what to do.
26 if [ -e "$host.ctrl" ]; then
28 ## If the connection's still running then we have a problem.
29 if runssh -Ocheck "$host" >/dev/null 2>/dev/null; then
30 echo >&2 "$0: failed to kill existing connection to $host"
34 ## Remove the stale socket.
41 ## Initial shutdown protocol.
42 writefile "$host.state" stopping
43 if [ -f "$host.pid" ]; then kill $(cat "$host.pid") 2>/dev/null || :; fi
46 ## Clobber the existing connection, if there is one.
50 rm -f "$host.state" "$host.pid"
55 ## There doesn't seem to be a better way of getting this. :-(
56 read pid <"$host.daemonpipe"
57 rm -f "$host.daemonpipe"
60 trap 'rm -f "$host.pid"; stopit' EXIT INT TERM
61 writefile "$host.pid" "$pid"
66 ## Keep the connection up for as long as we can.
67 while [ -f "$host.pid" ]; do
69 ## Maybe back off before trying another connection.
75 writefile "$host.state" \
76 "wait until $(date -d+${delay}sec +"%Y-%m-%d %H:%M:%S %z")"
79 if [ $delay -gt 120 ]; then delay=120; fi
83 ## Start a new connection.
84 writefile "$host.state" starting
85 if ! runssh -MNnf "$host" >/dev/null; then continue; fi
86 if ! runssh -Ocheck "$host" >/dev/null 2>&1; then
87 echo "connection to $host apparently stillborn"
90 writefile "$host.state" connected
93 ## Wait until it gets torn down. The chicanery with a pipe is because
94 ## the ssh process will continue until either it gets disconnected from
95 ## the server or stdin closes -- so we have to arrange that stdin doesn't
96 ## close. Thanks to Richard Kettlewell for the suggestion.
97 rm -f "$host.pipe"; mkfifo -m400 "$host.pipe"
98 runssh -N "$host" >/dev/null <"$host.pipe" || :
100 writefile "$host.state" disconnected
106 ## If there's already a connection then we have nothing to do.
107 if runssh -Ocheck "$host" >/dev/null 2>/dev/null; then
108 echo >&2 "$0: already connected to $host"
112 ## Start a daemon which makes connections for us. This is remarkably
114 rm -f "$host.daemonpipe"; mkfifo -m600 "$host.daemonpipe"
115 { daemon& echo $! >"$host.daemonpipe"; } 2>&1 | logger -pdaemon.notice&
122 restart) stopit; startit ;;
124 if [ -f "$host.state" ]
125 then cat "$host.state"
130 echo >&2 "usage: $0 {start|stop|restart|status} HOST"