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 ## Not waiting on a pipe yet.
69 ## Keep the connection up for as long as we can.
70 while [ -f "$host.pid" ]; do
72 ## Maybe back off before trying another connection.
78 writefile "$host.state" \
79 "wait until $(date -d+${delay}sec +"%Y-%m-%d %H:%M:%S %z")"
82 if [ $delay -gt 120 ]; then delay=120; fi
86 ## Prepare a pipe so that we can wait for SSH to finish. This is a
90 *) kill $kidcat >/dev/null 2>&1 || :; kidcat=nil ;;
92 rm -f "$host.pipe"; mkfifo -m600 "$host.pipe"
93 cat $host.pipe >/dev/null& kidcat=$!
95 ## Start a new connection.
96 writefile "$host.state" starting
97 if ! runssh -MNnf "$host" >"$host.pipe"; then continue; fi
98 if ! runssh -Ocheck "$host" >/dev/null 2>&1; then
99 echo "connection to $host apparently stillborn"
102 writefile "$host.state" connected
105 ## Wait until it gets torn down.
106 wait $kidcat >/dev/null 2>&1 || :
109 writefile "$host.state" disconnected
115 ## If there's already a connection then we have nothing to do.
116 if runssh -Ocheck "$host" >/dev/null 2>/dev/null; then
117 echo >&2 "$0: already connected to $host"
121 ## Start a daemon which makes connections for us. This is remarkably
123 rm -f "$host.daemonpipe"; mkfifo -m600 "$host.daemonpipe"
124 { daemon& echo $! >"$host.daemonpipe"; } 2>&1 | logger -pdaemon.notice&
131 restart) stopit; startit ;;
133 if [ -f "$host.state" ]
134 then cat "$host.state"
139 echo >&2 "usage: $0 {start|stop|restart|status} HOST"