2010-02-03 15:34:52 +00:00
|
|
|
use strict;
|
|
|
|
use File::Temp qw(tempdir);
|
|
|
|
|
|
|
|
our @sshOpts = split ' ', ($ENV{"NIX_SSHOPTS"} or "");
|
|
|
|
|
2010-12-15 14:25:54 +00:00
|
|
|
push @sshOpts, "-x";
|
|
|
|
|
2010-02-03 15:34:52 +00:00
|
|
|
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;
|
2010-02-03 20:35:37 +00:00
|
|
|
return 1 if system("ssh $sshHost @sshOpts -O check 2> /dev/null") == 0;
|
2010-02-03 15:34:52 +00:00
|
|
|
|
|
|
|
my $tmpDir = tempdir("nix-ssh.XXXXXX", CLEANUP => 1, TMPDIR => 1)
|
|
|
|
or die "cannot create a temporary directory";
|
|
|
|
|
|
|
|
push @sshOpts, "-S", "$tmpDir/control";
|
2010-02-04 02:38:40 +00:00
|
|
|
|
|
|
|
# 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.
|
2010-12-07 12:33:42 +00:00
|
|
|
open SSHPIPE, "ssh $sshHost @sshOpts -M -N -o LocalCommand='echo started' -o PermitLocalCommand=yes |" or die;
|
2010-08-24 14:27:07 +00:00
|
|
|
|
2010-12-07 12:33:42 +00:00
|
|
|
while (<SSHPIPE>) {
|
2010-02-04 02:38:40 +00:00
|
|
|
chomp;
|
2010-08-24 14:27:07 +00:00
|
|
|
if ($_ eq "started") {
|
|
|
|
$sshStarted = 1;
|
|
|
|
return 1;
|
|
|
|
}
|
2010-02-04 02:38:40 +00:00
|
|
|
}
|
2010-08-24 14:27:07 +00:00
|
|
|
|
|
|
|
return 0;
|
2010-02-03 15:34:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
# 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: $?";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2010-02-04 02:05:22 +00:00
|
|
|
END { my $saved = $?; closeSSHConnection; $? = $saved; }
|
2010-02-03 15:34:52 +00:00
|
|
|
|
|
|
|
return 1;
|