about summary refs log tree commit diff
path: root/scripts/SSH.pm
diff options
context:
space:
mode:
authorEelco Dolstra <e.dolstra@tudelft.nl>2011-02-09T12·41+0000
committerEelco Dolstra <e.dolstra@tudelft.nl>2011-02-09T12·41+0000
commitd0eda1f3e9b2030e373038fd8997f033f2d7aedd (patch)
tree9db733f87fceaba36ddcba54b794b8be06c1d136 /scripts/SSH.pm
parent3854fc9b42d16b810f62b64194b699033b03aaf1 (diff)
parent543988572e2abc85767da315b2acc1f971c5d07f (diff)
* Merged the SQLite branch.
Diffstat (limited to 'scripts/SSH.pm')
-rw-r--r--scripts/SSH.pm52
1 files changed, 52 insertions, 0 deletions
diff --git a/scripts/SSH.pm b/scripts/SSH.pm
new file mode 100644
index 000000000000..68f4a628b072
--- /dev/null
+++ b/scripts/SSH.pm
@@ -0,0 +1,52 @@
+use strict;
+use File::Temp qw(tempdir);
+
+our @sshOpts = split ' ', ($ENV{"NIX_SSHOPTS"} or "");
+
+push @sshOpts, "-x";
+
+my $sshStarted = 0;
+my $sshHost;
+
+# Open a master SSH connection to `host', unless there already is a
+# running master connection (as determined by `-O check').
+sub openSSHConnection {
+    my ($host) = @_;
+    die if $sshStarted;
+    $sshHost = $host;
+    return 1 if system("ssh $sshHost @sshOpts -O check 2> /dev/null") == 0;
+
+    my $tmpDir = tempdir("nix-ssh.XXXXXX", CLEANUP => 1, TMPDIR => 1)
+        or die "cannot create a temporary directory";
+    
+    push @sshOpts, "-S", "$tmpDir/control";
+
+    # Start the master.  We can't use the `-f' flag (fork into
+    # background after establishing the connection) because then the
+    # child continues to run if we are killed.  So instead make SSH
+    # print "started" when it has established the connection, and wait
+    # until we see that.
+    open SSHPIPE, "ssh $sshHost @sshOpts -M -N -o LocalCommand='echo started' -o PermitLocalCommand=yes |" or die;
+
+    while (<SSHPIPE>) {
+        chomp;
+        if ($_ eq "started") {
+            $sshStarted = 1;
+            return 1;
+        }
+    }
+
+    return 0;
+}
+
+# Tell the master SSH client to exit.
+sub closeSSHConnection {
+    if ($sshStarted) {
+        system("ssh $sshHost @sshOpts -O exit 2> /dev/null") == 0
+            or warn "unable to stop SSH master: $?";
+    }
+}
+
+END { my $saved = $?; closeSSHConnection; $? = $saved; }
+
+return 1;