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