More.pm

filter: Statementstmt 45.7% 195 / 426 Branchbran 27.8% 58 / 208 Conditioncond 31.4% 27 / 86 MC/DCmcdc 13.4% 7 / 52 Subroutinesub 57.1% 28 / 49 Podpod 100% 12 / 12 totaltotal 39.2% 327 / 833 CC 142 SCAR 37.6
CC
142
Cov
39%
write
110.0
__ANON__
84.8
eval_full
72.0
CRAP 43.1
↑ Summary More/Linux.pm »
1 package Net::OpenSSH::More;
2 9 $Net::OpenSSH::More::VERSION = '1.06';
3 #ABSTRACT: Net::OpenSSH submodule with many useful features
4  
5 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 9 ▶use parent 'Net::OpenSSH';
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 9 ▶use Data::UUID ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 9 ▶use Expect ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 9 ▶use File::HomeDir ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 9 ▶use File::Temp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 9 ▶use Fcntl ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 9 ▶use IO::Pty ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 9 ▶use IO::Socket::INET ();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 9 ▶use IO::Socket::INET6 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 9 ▶use IO::Stty ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 9 ▶use List::Util qw{first};
Subroutine BEGIN: called CC=1 SCAR=0.0
20 9 ▶use Net::DNS::Resolver ();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 9 ▶use Net::IP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
22 9 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 9 ▶use Term::ANSIColor ();
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25  
26 my %defaults = (
27 9 ▶ 'user' => $ENV{'USER'} || getpwuid($>),
Condition33%1/3
$ENV{'USER'} || getpwuid $>
l!l&&r!l&&!r
090
MC/DC0%0/2
$ENV{'USER'} || getpwuid $>
$ENV{'USER'} getpwuid $>
Truth table33%1/3
A || B
A= $ENV{'USER'}B= getpwuid $>
ABresult
1X1
011
000
28 'port' => 22,
29 'use_persistent_shell' => 0,
30 'output_prefix' => '',
31 'home' => File::HomeDir->my_home,
32 'retry_interval' => 6,
33 'retry_max' => 10,
34 'retry_on_auth_failure' => 0,
35 );
36  
37 9 our %cache;
38 9 our $disable_destructor = 0;
39  
40 ###################
41 # PRIVATE METHODS #
42 ###################
43  
44 3 ▶my $die_no_trace = sub {
Subroutine __ANON__: called CC=3 SCAR=11.4
45 3 my ( $full_msg, $summary ) = @_;
46 3 ▶ $summary ||= 'FATAL';
Condition50%1/2
$summary ||= "FATAL"
l!l
03
MC/DC0%0/1
$summary ||= "FATAL"
$summary
Truth table50%1/2
A
A= $summary
Aresult
11
00
47 3 ▶ my $carp = $INC{'Carp/Always.pm'} ? '' : ' - Use Carp::Always for full trace.';
Branch: 1 branch
BranchTrueFalseTotal
$INC{'Carp/Always.pm'} ? : 0 3 3
48 3 die "[$summary] ${full_msg}${carp}";
49 9 };
50  
51 0 ▶my $check_local_perms = sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
52 0 my ( $path, $expected_mode, $is_dir ) = @_;
53 0 ▶ $is_dir //= 0;
Condition0%0/2
$is_dir //= 0
l!l
00
MC/DC0%0/1
$is_dir //= 0
$is_dir
Truth table0%0/2
A
A= $is_dir
Aresult
11
00
54 0 my @stat = stat($path);
55 ## no critic(BitwiseOperator)
56 0 ▶ $die_no_trace->(qq{"$path" must be a directory that exists}) unless !$is_dir ^ -d _;
Branch: 1 branch
BranchTrueFalseTotal
unless !$is_dir ^ -d _ 0 0 0
57 ## no critic(BitwiseOperator)
58 0 ▶ $die_no_trace->(qq{"$path" must be a file that exists}) unless $is_dir ^ -f _;
Branch: 1 branch
BranchTrueFalseTotal
unless $is_dir ^ -f _ 0 0 0
59 0 ▶ $die_no_trace->(qq{"$path" could not be read}) unless -r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -r _ 0 0 0
60  
61 ## no critic(BitwiseOperator)
62 0 my $actual_mode = $stat[2] & 07777;
63 0 ▶ $die_no_trace->( sprintf( qq{Permissions on "$path" are not correct: got=0%o, expected=0%o}, $actual_mode, $expected_mode ) ) unless $expected_mode eq $actual_mode;
Branch: 1 branch
BranchTrueFalseTotal
unless $expected_mode eq $actual_mode 0 0 0
64 0 return 1;
65 9 };
66  
67 10 ▶my $resolve_login_method = sub {
Subroutine __ANON__: called CC=9 SCAR=35.3
68 10 my ($opts) = @_;
69  
70 10 ▶ my $chosen = first { $opts->{$_} } qw{key_path password};
Subroutine __ANON__: called CC=1 SCAR=0.0
71 10 ▶ $chosen //= '';
Condition50%1/2
$chosen //= ""
l!l
100
MC/DC0%0/1
$chosen //= ""
$chosen
Truth table50%1/2
A
A= $chosen
Aresult
11
00
72 10 ▶ undef $chosen if $chosen eq 'key_path' && !$check_local_perms->( $opts->{'key_path'}, 0600 );
Branch: 1 branch
BranchTrueFalseTotal
if $chosen eq "key_path" and not &$check_local_perms($opts->{"key_path"}, 384) 0 10 10
Condition33%1/3
$chosen eq "key_path" and not &$check_local_perms($opts->{"key_path"}, 384)
!ll&&!rl&&r
1000
MC/DC0%0/2
$chosen eq "key_path" and not &$check_local_perms($opts->{"key_path"}, 384)
$chosen eq "key_path" not &$check_local_perms($opts->{"key_path"}, 384)
Truth table33%1/3
A and not(B)
A= $chosen eq "key_path"B= not &$check_local_perms($opts->{"key_path"}, 384)
ABresult
0X0
100
111
73 10 ▶ return $chosen if $chosen;
Branch: 1 branch
BranchTrueFalseTotal
if $chosen 10 0 10
74 0 ▶ return 'SSH_AUTH_SOCK' if $ENV{'SSH_AUTH_SOCK'};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"SSH_AUTH_SOCK"} 0 0 0
75 0 my $fallback_path = "$opts->{'home'}/.ssh/id";
76 0 ▶ my $key_type = first { -s "${fallback_path}_$_" } qw{ed25519 ecdsa rsa dsa};
Subroutine __ANON__: not called CC=1 SCAR=6.9
77 0 ▶ $opts->{'key_path'} = "${fallback_path}_${key_type}" if defined $key_type;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key_type 0 0 0
78  
79 0 ▶ $die_no_trace->('No key_path or password specified and no active SSH agent; cannot connect') if !$opts->{'key_path'};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"key_path"} 0 0 0
80 0 ▶ $check_local_perms->( $opts->{'key_path'}, 0600 ) if $opts->{'key_path'};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"key_path"} 0 0 0
81  
82 0 return $opts->{'key_path'};
83 9 };
84  
85 0 ▶my $get_dns_record_from_hostname = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
86 0 my ( $hostname, $record_type ) = @_;
87 0 ▶ $record_type ||= 'A';
Condition0%0/2
$record_type ||= "A"
l!l
00
MC/DC0%0/1
$record_type ||= "A"
$record_type
Truth table0%0/2
A
A= $record_type
Aresult
11
00
88  
89 0 my $reply = Net::DNS::Resolver->new()->search( $hostname, $record_type );
90 0 ▶ return unless $reply;
Branch: 1 branch
BranchTrueFalseTotal
unless $reply 0 0 0
91 0 return { map { $_->type() => $_->address() } grep { $_->type eq $record_type } ( $reply->answer() ) };
92 9 };
93  
94 # Knock on the server till it responds, or doesn't. Try both ipv4 and ipv6.
95 17 ▶my $ping = sub {
Subroutine __ANON__: called CC=10 SCAR=35.9
96 17 my ($opts) = @_;
97  
98 17 my $timeout = 30;
99 17 my ( $host_info, $ip, $r_type );
100 17 ▶ if ( my $ip_obj = Net::IP->new( $opts->{'host'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ip_obj = 'Net::IP'->new($opts->{'host'})) { } 17 0 17
101 17 ▶ $r_type = $ip_obj->ip_is_ipv4 ? 'A' : 'AAAA';
Branch: 1 branch
BranchTrueFalseTotal
$ip_obj->ip_is_ipv4 ? : 17 0 17
102 17 $ip = $opts->{'host'};
103 }
104 else {
105 0 my $host_info = {};
106 0 foreach my $type (qw{A AAAA}) {
107 0 $host_info = $get_dns_record_from_hostname->( $opts->{'host'}, $type );
108 0 ▶ last if $host_info;
Branch: 1 branch
BranchTrueFalseTotal
if $host_info 0 0 0
109 }
110 0 ▶ $host_info //= {};
Condition0%0/2
$host_info //= {}
l!l
00
MC/DC0%0/1
$host_info //= {}
$host_info
Truth table0%0/2
A
A= $host_info
Aresult
11
00
111 0 ($r_type) = keys(%$host_info);
112 0 ▶ if ( !$host_info->{$r_type} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($host_info->{$r_type}) 0 0 0
113 0 require Data::Dumper;
114 0 die "Can't determine IP type. " . Data::Dumper::Dumper($host_info);
115 }
116 0 $ip = $host_info->{$r_type};
117 }
118 17 my %family_map = ( 'A' => 'INET', 'AAAA' => 'INET6' );
119 17 my $start = time;
120  
121 17 ▶ while ( ( time - $start ) <= $timeout ) {
Branch: 1 branch
BranchTrueFalseTotal
if (time - $start <= $timeout) 17 0 17
122 return 1 if "IO::Socket::$family_map{$r_type}"->new(
123 'PeerAddr' => $ip,
124 17 ▶ 'PeerPort' => $opts->{'port'},
Branch: 1 branch
BranchTrueFalseTotal
if ("IO::Socket::$family_map{$r_type}")->new("PeerAddr", $ip, "PeerPort", $opts->{"port"}, "Proto", "tcp", "Timeout", $timeout) 17 0 17
125 'Proto' => 'tcp',
126 'Timeout' => $timeout,
127 );
128 0 ▶ diag( { '_opts' => $opts }, "[DEBUG] Waiting for response on $ip:$opts->{'port'} ($r_type)..." ) if $opts->{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"debug"} 0 0 0
129 0 select undef, undef, undef, 0.5; # there's no need to try more than 2 times per second
130 }
131 0 return 0;
132 9 };
133  
134 # Whether the machine on the other end is still there, which check_master alone
135 # cannot answer: it asks the local master process, and that stays up and happy
136 # when the far end has been rebuilt, rebooted or destroyed underneath it. The
137 # only thing that settles it is asking the far end to do something.
138 #
139 # Costs a round trip, so it belongs where a connection is being adopted rather
140 # than on the path of every command.
141 2 ▶my $far_end_answers = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
142 2 my ($self) = @_;
143  
144 2 ▶ return 0 if !$self->check_master;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->check_master 0 2 2
145  
146 2 local $@;
147 2 my $answered = eval { $self->test('true') };
148 2 ▶ return $answered ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$answered ? : 1 1 2
149 9 };
150  
151 # Declared before it is assigned because it calls itself: a connection adopted
152 # from the environment is only found to be stale once there is an object to ask,
153 # and the way back from that is to start over without it.
154 9 my $init_ssh;
155 10 ▶$init_ssh = sub {
Subroutine __ANON__: called CC=41 SCAR=44.4
156 10 my ( $class, $opts ) = @_;
157  
158 # Always clear the cache if possible when we get here.
159 10 ▶ if ( $opts->{'_cache_index'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"_cache_index"}) 10 0 10
160 10 local $disable_destructor = 1;
161 10 undef $cache{ $opts->{'_cache_index'} };
162 }
163  
164 # Try not to have disallowed ENV chars. For now just transliterate . into _
165 # XXX TODO This will be bad with some usernames/domains.
166 # Maybe need to run host through punycode decoder, etc.?
167 10 ▶ if ( !$opts->{'_host_sock_key'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts->{"_host_sock_key"}) 10 0 10
168 10 $opts->{'_host_sock_key'} = "NET_OPENSSH_MASTER_$opts->{'host'}_$opts->{'user'}";
169 10 $opts->{'_host_sock_key'} =~ tr/./_/;
170 }
171  
172 # Make temp dir go out of scope with this object for ctl paths, etc.
173 # Leave no trace!
174 10 ▶ $opts->{'_tmp_obj'} = File::Temp->newdir() if !$opts->{'_tmp_obj'};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"_tmp_obj"} 10 0 10
175 10 my $tmp_dir = $opts->{'_tmp_obj'}->dirname();
176 10 ▶ diag( { '_opts' => $opts }, "Temp dir: $tmp_dir" ) if $opts->{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"debug"} 0 10 10
177 10 my $temp_fh;
178  
179 # Use an existing connection if possible, otherwise make one
180 10 ▶ if ( $ENV{ $opts->{'_host_sock_key'} } && -e $ENV{ $opts->{'_host_sock_key'} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{$opts->{'_host_sock_key'}} and -e $ENV{$opts->{'_host_sock_key'}}) { } 0 10 10
Condition33%1/3
$ENV{$opts->{"_host_sock_key"}} and -e $ENV{$opts->{"_host_sock_key"}}
!ll&&!rl&&r
1000
MC/DC0%0/2
$ENV{$opts->{"_host_sock_key"}} and -e $ENV{$opts->{"_host_sock_key"}}
$ENV{$opts->{"_host_sock_key"}} -e $ENV{$opts->{"_host_sock_key"}}
Truth table33%1/3
A and B
A= $ENV{$opts->{"_host_sock_key"}}B= -e $ENV{$opts->{"_host_sock_key"}}
ABresult
0X0
100
111
181 0 $opts->{'external_master'} = 1;
182 0 $opts->{'ctl_path'} = $ENV{ $opts->{'_host_sock_key'} };
183 }
184 else {
185 10 ▶ if ( !$opts->{'debug'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts->{"debug"}) 10 0 10
186  
187 # +> rather than >, because the retry loop reads this back to find
188 # out what ssh said. A write-only handle answers readline with a
189 # warning and undef, so the read was never going to work whatever
190 # else was fixed around it.
191 10 ▶ open( $temp_fh, "+>", "$tmp_dir/STDERR" ) or $die_no_trace->("Can't open $tmp_dir/STDERR for reading and writing: $!");
Branch: 1 branch
BranchTrueFalseTotal
open $temp_fh, "+>", "$tmp_dir/STDERR" or &$die_no_trace("Can't open $tmp_dir/STDERR for reading and writing: $!") 10 0 10
192 10 $opts->{'master_stderr_fh'} = $temp_fh;
193 }
194 10 $opts->{'strict_mode'} = 0;
195  
196 10 $opts->{'master_opts'} = [
197 '-o' => 'StrictHostKeyChecking=no',
198 '-o' => 'GSSAPIAuthentication=no',
199 '-o' => 'UserKnownHostsFile=/dev/null',
200 '-o' => 'ConnectTimeout=180',
201 '-o' => 'TCPKeepAlive=no',
202 ];
203 0 ▶ push @{ $opts->{'master_opts'} }, '-v' if $opts->{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"debug"} 0 10 10
204 10 ▶ if ( $opts->{'key_path'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"key_path"}) 0 10 10
205 0 push @{ $opts->{'master_opts'} }, '-o', 'IdentityAgent=none';
206 }
207  
208 # Attempt to use the SSH agent if possible. This won't hurt if you use -k or -P.
209 # Even if your sock doesn't work to get you in, you may want it to do something on the remote host.
210 # Of course, you may want to disable this with no_agent if your system is stupidly configured
211 # with lockout after 3 tries and you have 4 keys in agent.
212  
213 # Anyways, don't just kill the sock for your bash session, restore it in DESTROY
214 10 ▶ $opts->{'_restore_auth_sock'} = delete $ENV{SSH_AUTH_SOCK} if $opts->{'no_agent'};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"no_agent"} 0 10 10
215 10 ▶ $opts->{'forward_agent'} = 1 if $ENV{'SSH_AUTH_SOCK'};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"SSH_AUTH_SOCK"} 0 10 10
216 }
217  
218 10 my $status = 0;
219 10 my $self;
220  
221 # What the last failed attempt said. Each attempt fails for a reason, and
222 # the reason is what tells a key that is refused from a host that is not
223 # there yet, so it is said when it changes, and again when this gives up.
224 10 my $last_said = q{};
225 9 ▶ my $said = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
226 9 my ( $why, $attempt ) = @_;
227 9 $why =~ s/\s+/ /g;
228 9 $why =~ s/\A | \z//g;
229 9 ▶ diag( { '_opts' => $opts }, "Attempt $attempt of $opts->{'retry_max'} to reach $opts->{'host'} failed: $why" ) if $why ne $last_said;
Branch: 1 branch
BranchTrueFalseTotal
if $why ne $last_said 5 4 9
230 9 $last_said = $why;
231 9 return;
232 10 };
233 10 foreach my $attempt ( 1 .. $opts->{'retry_max'} ) {
234  
235 # Have to wait here: the `next` statements further down short-circuit
236 # past the foot of the loop.
237 17 ▶ sleep $opts->{'retry_interval'} if $attempt > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $attempt > 1 7 10 17
238  
239 17 local $@;
240 17 my $up = $ping->($opts);
241 17 ▶ if ( !$up ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($up) 0 17 17
242 0 ▶ $die_no_trace->("$opts->{'host'} is down!") if $opts->{die_on_drop};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"die_on_drop"} 0 0 0
243 0 ▶ $last_said = "nothing answered on port " . ( $opts->{'port'} // 22 );
Condition0%0/2
$opts->{"port"} // 22
l!l
00
MC/DC0%0/1
$opts->{"port"} // 22
$opts->{"port"}
Truth table0%0/2
A
A= $opts->{"port"}
Aresult
11
00
244 0 diag( { '_opts' => $opts }, "Waiting for host to bring up sshd, attempt $attempt..." );
245 0 next;
246 }
247  
248 # A short name for each attempt, because a socket path holds 108 bytes.
249 17 ▶ $opts->{'ctl_path'} = "$tmp_dir/$attempt" if !$opts->{'external_master'};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"external_master"} 17 0 17
250  
251 # Now, per the POD of Net::OpenSSH, new will NEVER DIE, so just trust it.
252 17 my @base_module_opts =
253 qw{host user port password passphrase key_path gateway proxy_command batch_mode ctl_dir ctl_path ssh_cmd scp_cmd rsync_cmd remote_shell timeout kill_ssh_on_timeout strict_mode async connect master_opts default_ssh_opts forward_agent forward_X11 default_stdin_fh default_stdout_fh default_stderr_fh default_stdin_file default_stdout_file default_stderr_file master_stdout_fh master_stderr_fh master_stdout_discard master_stderr_discard expand_vars vars external_master default_encoding default_stream_encoding default_argument_encoding password_prompt login_handler master_setpgrp master_pty_force};
254 17 my $class4super = "Net::OpenSSH::More";
255  
256 # Throw away what the last attempt's master wrote, so the checks below
257 # judge this attempt rather than the one before it.
258 17 ▶ if ($temp_fh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($temp_fh) 17 0 17
259 17 truncate( $temp_fh, 0 );
260 17 seek( $temp_fh, 0, Fcntl::SEEK_SET );
261 }
262  
263 # Subclassing here is a bit tricky, especially *after* you have gone down more than one layer.
264 # Ultimately we only ever want the constructor for Net::OpenSSH, so start there and then
265 # Re-bless into subclass if that's relevant.
266 # Defined, not true: a 0, such as strict_mode above, is a choice.
267 17 $self = $class4super->SUPER::new( map { $_ => $opts->{$_} } grep { defined $opts->{$_} } @base_module_opts );
268 17 my $ssh_error = $self->error;
269 17 my $error = $ssh_error;
270  
271 # What ssh said has to be in hand before anything decides to retry.
272 # Net::OpenSSH sets error whenever the master will not come up, which is
273 # exactly what a refused credential looks like, so reading this only
274 # afterwards meant the checks below never saw a word of it.
275 17 ▶ if ( $temp_fh && -s $temp_fh ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($temp_fh and -s $temp_fh) 4 13 17
Condition66%2/3
$temp_fh and -s $temp_fh
!ll&&!rl&&r
0134
MC/DC50%1/2
$temp_fh and -s $temp_fh
$temp_fh -s $temp_fh
Truth table66%2/3
A and B
A= $temp_fhB= -s $temp_fh
ABresult
0X0
100
111
276 4 seek( $temp_fh, 0, Fcntl::SEEK_SET );
277 4 local $/;
278 4 ▶ $error .= " " . ( readline($temp_fh) // q{} );
Condition50%1/2
readline $temp_fh // ""
l!l
40
MC/DC0%0/1
readline $temp_fh // ""
readline $temp_fh
Truth table50%1/2
A
A= readline $temp_fh
Aresult
11
00
279 }
280  
281 # Only these checks read the combined text. A connection that works
282 # writes to the same file -- the host key warning, at least -- so
283 # deciding whether to retry on it would retry every connection ever
284 # made. That is what $ssh_error is kept separate for.
285 17 ▶ if ( $error && !$opts->{'retry_on_auth_failure'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error and not $opts->{"retry_on_auth_failure"}) 4 13 17
Condition100%3/3
$error and not $opts->{"retry_on_auth_failure"}
!ll&&!rl&&r
764
MC/DC100%2/2
$error and not $opts->{"retry_on_auth_failure"}
$error not $opts->{"retry_on_auth_failure"}
Truth table100%3/3
A and not(B)
A= $errorB= not $opts->{"retry_on_auth_failure"}
ABresult
0X0
100
111
286 4 ▶ $die_no_trace->("Bad password passed, will not retry SSH connection: $error.") if ( $error =~ m{bad password} && $opts->{'password'} );
Branch: 1 branch
BranchTrueFalseTotal
if $error =~ /bad password/ and $opts->{"password"} 0 4 4
Condition33%1/3
$error =~ /bad password/ and $opts->{"password"}
!ll&&!rl&&r
400
MC/DC0%0/2
$error =~ /bad password/ and $opts->{"password"}
$error =~ /bad password/ $opts->{"password"}
Truth table33%1/3
A and B
A= $error =~ /bad password/B= $opts->{"password"}
ABresult
0X0
100
111
287 4 ▶ $die_no_trace->("Bad key, will not retry SSH connection: $error.") if ( $error =~ m{master process exited unexpectedly} && $opts->{'key_path'} );
Branch: 1 branch
BranchTrueFalseTotal
if $error =~ /master process exited unexpectedly/ and $opts->{"key_path"} 0 4 4
Condition33%1/3
$error =~ /master process exited unexpectedly/ and $opts->{"key_path"}
!ll&&!rl&&r
400
MC/DC0%0/2
$error =~ /master process exited unexpectedly/ and $opts->{"key_path"}
$error =~ /master process exited unexpectedly/ $opts->{"key_path"}
Truth table33%1/3
A and B
A= $error =~ /master process exited unexpectedly/B= $opts->{"key_path"}
ABresult
0X0
100
111
288 4 ▶ $die_no_trace->("Bad credentials, will not retry SSH connection: $error.") if ( $error =~ m{Permission denied} );
Branch: 1 branch
BranchTrueFalseTotal
if $error =~ /Permission denied/ 1 3 4
289 }
290  
291 16 ▶ if ( ref $self ne 'Net::OpenSSH::More' || $ssh_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self ne "Net::OpenSSH::More" or $ssh_error) 9 7 16
Condition66%2/3
ref $self ne "Net::OpenSSH::More" or $ssh_error
l!l&&r!l&&!r
097
MC/DC50%1/2
ref $self ne "Net::OpenSSH::More" or $ssh_error
ref $self ne "Net::OpenSSH::More" $ssh_error
Truth table66%2/3
A or B
A= ref $self ne "Net::OpenSSH::More"B= $ssh_error
ABresult
1X1
011
000
292 9 ▶ $said->( $error || 'the master connection would not start', $attempt );
Condition50%1/2
$error || 'the master connection would not start'
l!l
90
MC/DC0%0/1
$error || 'the master connection would not start'
$error
Truth table50%1/2
A
A= $error
Aresult
11
00
293 9 next;
294 }
295 7 ▶ bless $self, $class if ref $self ne $class;
Branch: 1 branch
BranchTrueFalseTotal
if ref $self ne $class 0 7 7
296  
297 7 ▶ if ( $status = $self->check_master() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status = $self->check_master) 7 0 7
298 7 ▶ diag( { '_opts' => $opts }, "Successfully established connection to $opts->{'host'} on attempt #$attempt." ) if $attempt gt 1;
Branch: 1 branch
BranchTrueFalseTotal
if $attempt gt 1 2 5 7
299 7 last;
300 }
301 0 $said->( 'the master connection did not answer a check', $attempt );
302 }
303 9 ▶ $die_no_trace->("Failed to establish SSH connection after $opts->{'retry_max'} attempts. The last attempt said: $last_said. Stopping here.") if ( !$status );
Branch: 1 branch
BranchTrueFalseTotal
unless $status 2 7 9
304  
305 # An adopted master is somebody else's, and all we knew when we took it was
306 # that a socket file existed at that path. That says nothing about the
307 # machine at the far end, which may have gone away since whoever published
308 # it last spoke to it. Drop the stale entry and build our own instead.
309 # Deleting it first is what stops this going round again: the block that
310 # adopts one cannot fire with the variable gone.
311 7 ▶ if ( $opts->{'external_master'} && !$far_end_answers->($self) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"external_master"} and not &$far_end_answers($self)) 0 7 7
Condition33%1/3
$opts->{"external_master"} and not &$far_end_answers($self)
!ll&&!rl&&r
700
MC/DC0%0/2
$opts->{"external_master"} and not &$far_end_answers($self)
$opts->{"external_master"} not &$far_end_answers($self)
Truth table33%1/3
A and not(B)
A= $opts->{"external_master"}B= not &$far_end_answers($self)
ABresult
0X0
100
111
312 0 delete $ENV{ $opts->{'_host_sock_key'} };
313 0 delete $opts->{'external_master'};
314 0 delete $opts->{'ctl_path'};
315  
316 0 local $disable_destructor = 1;
317 0 return $init_ssh->( $class, $opts );
318 }
319  
320 # Publish this master's socket if nobody has yet. _host_sock_key is given a
321 # value a few lines above unconditionally, so testing it here -- rather than
322 # what it names in the environment -- meant this never ran once, and it
323 # would have used an empty string as the variable name if it had.
324 #
325 # disown_master hands the master process over: Net::OpenSSH stops counting
326 # it as ours, so it is not torn down with this object and outlives the
327 # program that made it. That is what makes the socket worth publishing, and
328 # it is also why this only happens when caching was asked for.
329 7 ▶ if ( !$opts->{'no_cache'} && !$ENV{ $opts->{'_host_sock_key'} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts->{"no_cache"} or $ENV{$opts->{"_host_sock_key"}}) 3 4 7
Condition66%2/3
$opts->{"no_cache"} or $ENV{$opts->{"_host_sock_key"}}
l!l&&r!l&&!r
403
MC/DC50%1/2
$opts->{"no_cache"} or $ENV{$opts->{"_host_sock_key"}}
$opts->{"no_cache"} $ENV{$opts->{"_host_sock_key"}}
Truth table66%2/3
A or B
A= $opts->{"no_cache"}B= $ENV{$opts->{"_host_sock_key"}}
ABresult
1X1
011
000
330 3 $self->{'master_pid'} = $self->disown_master();
331 3 $ENV{ $opts->{'_host_sock_key'} } = $self->get_ctl_path();
332 }
333  
334 #Allow the user to unlink the host sock if we need to pop the cache for some reason
335 7 $self->{'host_sock'} = $ENV{ $opts->{'_host_sock_key'} };
336  
337 7 return $self;
338 9 };
339  
340 0 ▶my $connection_check = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
341 0 my ($self) = @_;
342 0 ▶ return 1 if $self->check_master;
Branch: 1 branch
BranchTrueFalseTotal
if $self->check_master 0 0 0
343 0 local $@;
344 0 local $disable_destructor = 1;
345 0 eval { $self = $init_ssh->( __PACKAGE__, $self->{'_opts'} ) };
346 0 ▶ return $@ ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 0 0 0
347 9 };
348  
349 # Try calling the function.
350 # If it fails, then call $connection_check to reconnect if needed.
351 #
352 # The goal is to avoid calling $connection_check
353 # unless something goes wrong since it adds about
354 # 450ms to each ssh command.
355 #
356 # If the control socket has gone away, call
357 # $connection_check ahead of time to reconnect it.
358 0 ▶my $call_ssh_reinit_if_check_fails = sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
359 0 my ( $self, $func, @args ) = @_;
360  
361 0 ▶ $connection_check->($self) if !-S $self->{'_ctl_path'};
Branch: 1 branch
BranchTrueFalseTotal
unless -S $self->{"_ctl_path"} 0 0 0
362  
363 0 local $@;
364 0 my @ret = eval { $self->$func(@args) };
365 0 ▶ my $ssh_error = $@ || $self->error;
Condition0%0/3
$@ || $self->error
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ || $self->error
$@ $self->error
Truth table0%0/3
A || B
A= $@B= $self->error
ABresult
1X1
011
000
366 0 ▶ warn "[WARN] $ssh_error" if $ssh_error;
Branch: 1 branch
BranchTrueFalseTotal
if $ssh_error 0 0 0
367 0 ▶ return @ret if !$ssh_error;
Branch: 1 branch
BranchTrueFalseTotal
unless $ssh_error 0 0 0
368  
369 0 $connection_check->($self);
370 0 return ( $self->$func(@args) );
371 9 };
372  
373 7 ▶my $post_connect = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
374 7 my ( $self, $opts ) = @_;
375  
376 7 ▶ $self->{'persistent_shell'}->close() if $self->{'persistent_shell'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"persistent_shell"} 0 7 7
377 7 undef $self->{'persistent_shell'};
378  
379 7 return;
380 9 };
381  
382 0 ▶my $trim = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
383 0 my ($string) = @_;
384 0 ▶ return '' unless length $string;
Branch: 1 branch
BranchTrueFalseTotal
unless length $string 0 0 0
385 0 $string =~ s/^\s+//;
386 0 $string =~ s/\s+$//;
387 0 return $string;
388 9 };
389  
390 0 ▶my $send = sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
391 0 my ( $self, $line_reader, @command ) = @_;
392  
393 0 ▶ $self->diag( "[DEBUG][$self->{'_opts'}{'host'}] EXEC " . join( " ", @command ) ) if $self->{'_opts'}{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_opts"}{"debug"} 0 0 0
394  
395 0 my ( $pty, $err, $pid ) = $call_ssh_reinit_if_check_fails->( $self, 'open3pty', @command );
396 0 ▶ $die_no_trace->("Net::OpenSSH::open3pty failed: $err") if ( !defined $pid || $self->error() );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $pid or $self->error 0 0 0
Condition0%0/3
not defined $pid or $self->error
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $pid or $self->error
not defined $pid $self->error
Truth table0%0/3
not(A) or B
A= not defined $pidB= $self->error
ABresult
1X1
011
000
397  
398 0 $self->{'_out'} = "";
399 0 ▶ $line_reader = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
400 0 my ( $self, $out, $stash_param ) = @_;
401 0 $out =~ s/[\r\n]{1,2}$//;
402 0 $self->{$stash_param} .= "$out\n";
403 0 return;
404 }
405 0 ▶ if ref $line_reader ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $line_reader ne "CODE" 0 0 0
406  
407 # TODO make this async so you can stream STDERR *in order*
408 # with STDOUT as well
409 # That said, most only care about error if command fails, so...
410 0 my $out;
411 0 ▶ $line_reader->( $self, $out, '_out' ) while $out = $pty->getline;
Branch: 1 branch
BranchTrueFalseTotal
$out = $pty->getline and do { &$line_reader($self, $out, "_out") } 0 0 0
412 0 $pty->close;
413  
414 # only populate error if there's an error #
415 0 $self->{'_err'} = '';
416 0 ▶ $line_reader->( $self, $out, '_err' ) while $out = $err->getline;
Branch: 1 branch
BranchTrueFalseTotal
$out = $err->getline and do { &$line_reader($self, $out, "_err") } 0 0 0
417 0 $err->close;
418  
419 0 waitpid( $pid, 0 );
420 0 return $? >> 8;
421 9 };
422  
423 9 my $TERMINATOR = "\r\n";
424 0 ▶my $send_persistent_cmd = sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
425 0 my ( $self, $command, $uuid ) = @_;
426  
427 0 ▶ $uuid //= Data::UUID->new()->create_str();
Condition0%0/3
$uuid //= "Data::UUID"->new->create_str
l!l&&r!l&&!r
000
MC/DC0%0/2
$uuid //= "Data::UUID"->new->create_str
$uuid "Data::UUID"->new->create_str
Truth table0%0/3
A //= B
A= $uuidB= "Data::UUID"->new->create_str
ABresult
1X1
011
000
428 0 $command = join( ' ', @$command );
429 0 my $actual_cmd = "UUID='$uuid'; echo \"BEGIN \$UUID\"; $command; echo \"___\$?___\"; echo; echo \"EOF \$UUID\"";
430 0 ▶ $self->diag("[DEBUG][$self->{'_opts'}{'host'}] EXEC $actual_cmd") if $self->{'_opts'}{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_opts"}{"debug"} 0 0 0
431  
432 #Use command on bash to ignore stuff like aliases so that we have a minimum level of PEBKAC errors due to aliasing cp to cp -i, etc.
433 0 $self->{'expect'}->print("${actual_cmd}${TERMINATOR}");
434  
435 # Rather than take the approach of cPanel, which commands then polls async,
436 # it is more straightforward to echo unique strings before and after the command.
437 # This made getting the return code somewhat more complicated, as you can see below.
438 # That said, it also makes you not have to worry about doing things asynchronously.
439 0 $self->{'expect'}->expect( $self->{'_opts'}{'expect_timeout'}, '-re', qr/BEGIN $uuid/m );
440 0 $self->{'expect'}->expect( $self->{'_opts'}{'expect_timeout'}, '-re', qr/EOF $uuid/m ); # If nothing is printed in timeout, give up
441  
442 # Get the actual output, remove terminal grunk
443 0 my $message = $trim->( $self->{'expect'}->before() );
444 0 $message =~ s/[\r\n]{1,2}$//; # Remove 'secret newline' control chars
445 0 $message =~ s/\x{d}//g; # More control chars
446 0 $message = Term::ANSIColor::colorstrip($message); # Strip colors
447  
448 # Find the exit code
449 0 my ($code) = $message =~ m/___(\d*)___$/;
450 0 ▶ unless ( defined $code ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $code) 0 0 0
451  
452 # Tell the user if they've made a boo-boo
453 0 my $possible_err = $trim->( $self->{'expect'}->before() );
454 0 $possible_err =~ s/\s//g;
455 0 ▶ $die_no_trace->("Runaway multi-line string detected. Please adjust the command passed.") if $possible_err =~ m/\>/;
Branch: 1 branch
BranchTrueFalseTotal
if $possible_err =~ /\>/ 0 0 0
456  
457 0 $die_no_trace->(
458 "Could not determine exit code!
459 It timed out (went $self->{'_opts'}{'expect_timeout'}s without printing anything).
460 Run command outside of the persistent terminal please."
461 );
462 }
463 0 $message =~ s/___(\d*)___$//g;
464  
465 0 return ( $message, $code );
466 9 };
467  
468 0 ▶my $do_persistent_command = sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
469 0 my ( $self, $command, $no_stderr ) = @_;
470  
471 0 ▶ if ( !$self->{'persistent_shell'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"persistent_shell"}) 0 0 0
472 0 my ( $pty, $pid ) = $call_ssh_reinit_if_check_fails->( $self, 'open2pty', $self->{'_remote_shell'} );
473 0 ▶ die "Got no pty back from open2pty: " . $self->error if !$pty;
Branch: 1 branch
BranchTrueFalseTotal
unless $pty 0 0 0
474  
475 # You might think that the below settings are important.
476 # In most cases, they are not.
477 0 $pty->set_raw();
478 0 $pty->stty( 'raw', 'icrnl', '-echo' );
479 0 $pty->slave->stty( 'raw', 'icrnl', '-echo' );
480  
481 #Hook in expect
482 0 ▶ $self->diag("[DEBUG][$self->{'_opts'}{'host'}] INIT expect on for PTY with pid $pid") if $self->{'_opts'}{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_opts"}{"debug"} 0 0 0
483 0 $self->{'expect'} = Expect->init($pty);
484 0 $self->{'expect'}->restart_timeout_upon_receive(1); #Logabandon by default
485  
486 # XXX WARNING bashisms. That said, I'm not sure how to better do this yet portably.
487 0 my $expect_env_cmd = "export PS1=''; export TERM='dumb'; unset HISTFILE; export FOE='configured'; stty raw icrnl -echo; unalias -a; echo \"EOF=\$FOE\"";
488 0 ▶ $self->diag("[DEBUG][$self->{'_opts'}{'host'}] EXEC $expect_env_cmd") if $self->{'_opts'}{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_opts"}{"debug"} 0 0 0
489 0 $self->{'expect'}->print("${expect_env_cmd}${TERMINATOR}");
490 0 $self->{'expect'}->expect( $self->{'_opts'}{'expect_timeout'}, '-re', qr/EOF=configured/ );
491 0 $self->{'expect'}->clear_accum();
492  
493 #cache
494 0 $self->{'persistent_shell'} = $pty;
495 0 $self->{'persistent_pid'} = $pid;
496 }
497  
498 #execute the command
499 0 my $uuid = Data::UUID->new()->create_str();
500 0 ▶ push @$command, '2>', "/tmp/stderr_$uuid.out" unless $no_stderr;
Branch: 1 branch
BranchTrueFalseTotal
unless $no_stderr 0 0 0
501 0 my ( $oot, $code ) = $send_persistent_cmd->( $self, $command, $uuid );
502 0 $self->{'_out'} = $oot;
503  
504 0 ▶ unless ($no_stderr) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($no_stderr) 0 0 0
505  
506 #Grab stderr
507 0 ( $self->{'_err'} ) = $send_persistent_cmd->( $self, [ '/usr/bin/cat', "/tmp/stderr_$uuid.out" ] );
508  
509 #Clean up
510 0 $send_persistent_cmd->( $self, [ '/usr/bin/rm', '-f', "/tmp/stderr_$uuid.out" ] );
511 }
512  
513 0 return int($code);
514 9 };
515  
516 #######################
517 # END PRIVATE METHODS #
518 #######################
519  
520  
521 11 ▶sub new {
Subroutine new: called CC=11 SCAR=24.5
Pod documented
522 11 my ( $class, %opts ) = @_;
523 11 ▶ $opts{'host'} = '127.0.0.1' if !$opts{'host'} || $opts{'host'} eq 'localhost';
Branch: 1 branch
BranchTrueFalseTotal
if not $opts{"host"} or $opts{"host"} eq "localhost" 0 11 11
Condition33%1/3
not $opts{"host"} or $opts{"host"} eq "localhost"
l!l&&r!l&&!r
0011
MC/DC0%0/2
not $opts{"host"} or $opts{"host"} eq "localhost"
not $opts{"host"} $opts{"host"} eq "localhost"
Truth table33%1/3
not(A) or B
A= not $opts{"host"}B= $opts{"host"} eq "localhost"
ABresult
1X1
011
000
524 11 ▶ $opts{'remote_shell'} ||= 'bash'; # prevent stupid defaults
Condition50%1/2
$opts{"remote_shell"} ||= "bash"
l!l
011
MC/DC0%0/1
$opts{"remote_shell"} ||= "bash"
$opts{"remote_shell"}
Truth table50%1/2
A
A= $opts{"remote_shell"}
Aresult
11
00
525 11 ▶ $opts{'expect_timeout'} //= 30; # If your program goes over 30s without printing...
Condition50%1/2
$opts{"expect_timeout"} //= 30
l!l
011
MC/DC0%0/1
$opts{"expect_timeout"} //= 30
$opts{"expect_timeout"}
Truth table50%1/2
A
A= $opts{"expect_timeout"}
Aresult
11
00
526  
527 # Set defaults, check if we can return early
528 11 %opts = ( %defaults, %opts );
529 11 $opts{'_cache_index'} = "$opts{'user'}_$opts{'host'}_$opts{'port'}";
530  
531 # A cached object is only worth having if it still reaches the machine it
532 # was built for. Rebuild a host at the same address -- which is an ordinary
533 # thing to do to a VM -- and the cached object here is pointed at something
534 # that no longer exists, while its local master sits there looking healthy.
535 # Handing that back means the caller's first command dies on a broken pipe
536 # rather than the login failing, which is a long way from the cause.
537 11 ▶ if ( !$opts{'no_cache'} && $cache{ $opts{'_cache_index'} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $opts{"no_cache"} and $Net::OpenSSH::More::cache{$opts{"_cache_index"}}) 2 9 11
Condition100%3/3
not $opts{"no_cache"} and $Net::OpenSSH::More::cache{$opts{"_cache_index"}}
!ll&&!rl&&r
722
MC/DC100%2/2
not $opts{"no_cache"} and $Net::OpenSSH::More::cache{$opts{"_cache_index"}}
not $opts{"no_cache"} $Net::OpenSSH::More::cache{$opts{"_cache_index"}}
Truth table100%3/3
not(A) and B
A= not $opts{"no_cache"}B= $Net::OpenSSH::More::cache{$opts{"_cache_index"}}
ABresult
0X0
100
111
538 2 my $cached = $cache{ $opts{'_cache_index'} };
539 2 ▶ return $cached if $far_end_answers->($cached);
Branch: 1 branch
BranchTrueFalseTotal
if &$far_end_answers($cached) 1 1 2
540  
541 1 local $disable_destructor = 1;
542 1 delete $cache{ $opts{'_cache_index'} };
543 }
544  
545 # Figure out how we're gonna login
546 10 $opts{'_login_method'} = $resolve_login_method->( \%opts );
547  
548 # check permissions on base files if we got here
549 10 ▶ $check_local_perms->( "$opts{'home'}/.ssh", 0700, 1 ) if -e "$opts{'home'}/.ssh";
Branch: 1 branch
BranchTrueFalseTotal
if -e qq[$opts{"home"}/.ssh] 0 10 10
550 10 ▶ $check_local_perms->( "$opts{'home'}/.ssh/config", 0600 ) if -e "$opts{'home'}/.ssh/config";
Branch: 1 branch
BranchTrueFalseTotal
if -e qq[$opts{"home"}/.ssh/config] 0 10 10
551  
552 # Make the connection
553 10 my $self = $init_ssh->( $class, \%opts );
554 7 ▶ $cache{ $opts{'_cache_index'} } = $self unless $opts{'no_cache'};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"no_cache"} 3 4 7
555  
556 # Stash opts for later
557 7 $self->{'_opts'} = \%opts;
558  
559 # Establish persistent shell, etc.
560 7 $post_connect->( $self, \%opts );
561  
562 7 return $self;
563 }
564  
565  
566 0 ▶sub use_persistent_shell {
Subroutine use_persistent_shell: not called CC=2 SCAR=17.9
Pod documented
567 0 my ( $self, $use_shell ) = @_;
568 0 ▶ return $self->{'_opts'}{'use_persistent_shell'} if !defined($use_shell);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $use_shell 0 0 0
569 0 return $self->{'_opts'}{'use_persistent_shell'} = $use_shell;
570 }
571  
572  
573 0 ▶sub copy {
Subroutine copy: not called CC=1 SCAR=6.9
Pod documented
574 0 die "Unimplemented, use a subclass of this perhaps?";
575 }
576  
577  
578 0 ▶sub backup_files {
Subroutine backup_files: not called CC=4 SCAR=30.0
Pod documented
579 0 my ( $self, @files ) = @_;
580  
581 # For each file passed in
582 0 foreach my $file (@files) {
583  
584 # If the file hasn't already been backed up
585 0 ▶ if ( !defined $self->{'file_backups'}{$file} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"file_backups"}{$file}) 0 0 0
586  
587 # and the file exists
588 0 ▶ if ( $self->sftp->test_e($file) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->sftp->test_e($file)) { } 0 0 0
589  
590 # then back it up
591 0 $self->{'file_backups'}{$file} = time;
592 0 my $bkup = $file . '.' . $self->{'file_backups'}{$file};
593 0 $self->diag("[INFO] Backing up '$file' to '$bkup'");
594 0 $self->copy( $file, $bkup ); # XXX Probably not that portable, maybe move to Linux.pm somehow?
595  
596 # otherwise if the file to be backed up doesn't exist
597 }
598 else {
599 # then just note that a file may need to be deleted later
600 0 $self->{'file_backups'}{$file} = '';
601 }
602 }
603 }
604 0 return;
605 }
606  
607  
608 0 ▶sub restore_files {
Subroutine restore_files: not called CC=6 SCAR=37.4
Pod documented
609 0 my ( $self, @files ) = @_;
610  
611 # If no files were passed in then grab all files that have been backed up
612 0 ▶ @files = keys( %{ $self->{'file_backups'} } ) if !@files;
Branch: 1 branch
BranchTrueFalseTotal
unless @files 0 0 0
613  
614 # foreach file
615 0 foreach my $file (@files) {
616  
617 # that has been marked as modified
618 0 ▶ if ( defined $self->{'file_backups'}{$file} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"file_backups"}{$file}) 0 0 0
619  
620 # if a backup exists
621 0 ▶ if ( $self->{'file_backups'}{$file} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'file_backups'}{$file}) { } 0 0 0
622  
623 # then restore the backup
624 0 my $bkup = $file . '.' . $self->{'file_backups'}{$file};
625 0 ▶ if ( $self->sftp->test_e($bkup) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->sftp->test_e($bkup)) 0 0 0
626 0 $self->diag("[INFO] Restoring backup '$file' from '$bkup'");
627 0 $self->sftp->rename( $bkup, $file, 'overwrite' => 1 );
628 }
629  
630 # otherwise no backup exists we just need to delete the modified file
631 }
632 else {
633 0 $self->diag("[INFO] Deleting '$file' to restore system state (beforehand the file didn't exist)");
634 0 $self->sftp->remove($file);
635 }
636 }
637 0 delete $self->{'file_backups'}{$file};
638 }
639 0 return;
640 }
641  
642  
643 19 ▶sub DESTROY {
Subroutine DESTROY: called CC=6 SCAR=29.7
644 19 my ($self) = @_;
645 19 ▶ return if !$self->{'_perl_pid'} || $$ != $self->{'_perl_pid'} || $disable_destructor;
Branch: 1 branch
BranchTrueFalseTotal
if not $self->{"_perl_pid"} or $$ != $self->{"_perl_pid"} or $Net::OpenSSH::More::disable_destructor 19 0 19
Condition33%2/6
not $self->{"_perl_pid"} or $$ != $self->{"_perl_pid"} or $Net::OpenSSH::More::disable_destructor
l!l&&r!l&&!r
1900
not $self->{"_perl_pid"} or $$ != $self->{"_perl_pid"}
l!l&&r!l&&!r
1900
MC/DC0%0/3
not $self->{"_perl_pid"} or $$ != $self->{"_perl_pid"} or $Net::OpenSSH::More::disable_destructor
not $self->{"_perl_pid"} $$ != $self->{"_perl_pid"} $Net::OpenSSH::More::disable_destructor
Truth table25%1/4
not(A) or B or C
A= not $self->{"_perl_pid"}B= $$ != $self->{"_perl_pid"}C= $Net::OpenSSH::More::disable_destructor
ABCresult
1XX1
01X1
0011
0000
646 0 $self->restore_files();
647 0 ▶ $ENV{SSH_AUTH_SOCK} = $self->{'_opts'}{'_restore_auth_sock'} if $self->{'_opts'}{'_restore_auth_sock'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_opts"}{"_restore_auth_sock"} 0 0 0
648 0 ▶ $self->{'persistent_shell'}->close() if $self->{'persistent_shell'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"persistent_shell"} 0 0 0
649  
650 0 return $self->SUPER::DESTROY();
651 }
652  
653  
654 8 ▶sub diag {
Subroutine diag: called CC=2 SCAR=6.9
Pod documented
655 8 my ( $self, @msgs ) = @_;
656 8 print STDOUT "$self->{'_opts'}{'output_prefix'}$_\n" for @msgs;
657 8 return;
658 }
659  
660  
661 0 ▶sub cmd {
Subroutine cmd: not called CC=6 SCAR=37.4
Pod documented
662 0 my ($self) = shift;
663 0 ▶ my $opts = ref $_[0] eq 'HASH' ? shift : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 0 0 0
664 0 my @command = @_;
665  
666 0 ▶ $die_no_trace->( 'No command specified', 'PEBCAK' ) if !@command;
Branch: 1 branch
BranchTrueFalseTotal
unless @command 0 0 0
667  
668 0 my $ret;
669 0 ▶ $opts->{'use_persistent_shell'} = $self->{'_opts'}{'use_persistent_shell'} if !exists $opts->{'use_persistent_shell'};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts->{"use_persistent_shell"} 0 0 0
670 0 ▶ if ( $opts->{'use_persistent_shell'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{'use_persistent_shell'}) { } 0 0 0
671 0 $ret = $do_persistent_command->( $self, \@command, $opts->{'no_stderr'} );
672 }
673 else {
674 0 $ret = $send->( $self, undef, @command );
675 }
676 0 chomp( my $out = $self->{'_out'} );
677 0 ▶ my $err = $self->error || '';
Condition0%0/2
$self->error || ''
l!l
00
MC/DC0%0/1
$self->error || ''
$self->error
Truth table0%0/2
A
A= $self->error
Aresult
11
00
678  
679 0 $self->{'last_exit_code'} = $ret;
680 0 return ( $out, $err, $ret );
681 }
682  
683  
684 0 ▶sub cmd_exit_code {
Subroutine cmd_exit_code: not called CC=1 SCAR=6.9
Pod documented
685 0 my ( $self, @args ) = @_;
686 0 return ( $self->cmd(@args) )[2];
687 }
688  
689 0 ▶sub sftp {
Subroutine sftp: not called CC=3 SCAR=24.8
Pod documented
690 0 my ($self) = @_;
691  
692 0 ▶ unless ( defined $self->{'_sftp'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"_sftp"}) 0 0 0
693 0 $self->{'_sftp'} = $self->SUPER::sftp();
694 0 ▶ die 'Unable to establish SFTP connection to remote host: ' . $self->error() unless defined $self->{'_sftp'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"_sftp"} 0 0 0
695 }
696 0 return $self->{'_sftp'};
697 }
698  
699  
700 0 ▶sub write {
Subroutine write: not called CC=10 SCAR=47.0
Pod documented
701 0 my ( $self, $file, $content, $mode, $owner, $group ) = @_;
702  
703 0 ▶ die '[PARAMETER] No file specified' if !defined $file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file 0 0 0
704 0 ▶ die '[PARAMETER] File content not specified' if !defined $content;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 0 0 0
705  
706 0 my %opts;
707 0 ▶ $opts{'perm'} = $mode if $mode;
Branch: 1 branch
BranchTrueFalseTotal
if $mode 0 0 0
708 0 my $ret = $self->sftp()->put_content( $content, $file, %opts );
709 0 ▶ warn "[WARN] Write failed: " . $self->sftp()->error() if !$ret;
Branch: 1 branch
BranchTrueFalseTotal
unless $ret 0 0 0
710  
711 0 ▶ if ( defined $owner || defined $group ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $owner or defined $group) 0 0 0
Condition0%0/3
defined $owner or defined $group
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $owner or defined $group
defined $owner defined $group
Truth table0%0/3
A or B
A= defined $ownerB= defined $group
ABresult
1X1
011
000
712 0 ▶ $owner //= $self->{'_opts'}{'user'};
Condition0%0/3
$owner //= $self->{"_opts"}{"user"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$owner //= $self->{"_opts"}{"user"}
$owner $self->{"_opts"}{"user"}
Truth table0%0/3
A //= B
A= $ownerB= $self->{"_opts"}{"user"}
ABresult
1X1
011
000
713 0 ▶ $group //= $owner;
Condition0%0/3
$group //= $owner
l!l&&r!l&&!r
000
MC/DC0%0/2
$group //= $owner
$group $owner
Truth table0%0/3
A //= B
A= $groupB= $owner
ABresult
1X1
011
000
714 0 $ret = $self->sftp()->chown( $file, $owner, $group );
715 0 ▶ warn "[WARN] Couldn't chown $file" if $ret;
Branch: 1 branch
BranchTrueFalseTotal
if $ret 0 0 0
716 }
717  
718 0 return $ret;
719 }
720  
721  
722 0 ▶sub eval_full {
Subroutine eval_full: not called CC=8 SCAR=42.8
Pod documented
723 0 my ( $self, %options ) = @_;
724 0 my $code = $options{code};
725 0 ▶ my $args = $options{args} // [];
Condition0%0/2
$options{"args"} // []
l!l
00
MC/DC0%0/1
$options{"args"} // []
$options{"args"}
Truth table0%0/2
A
A= $options{"args"}
Aresult
11
00
726 0 ▶ my $exe = $options{exe} || '/usr/bin/perl';
Condition0%0/2
$options{'exe'} || '/usr/bin/perl'
l!l
00
MC/DC0%0/1
$options{'exe'} || '/usr/bin/perl'
$options{'exe'}
Truth table0%0/2
A
A= $options{'exe'}
Aresult
11
00
727  
728 0 require Storable;
729 0 local $Storable::Deparse = 1;
730  
731 0 my ( $in_fh, $out_fh, undef, $pid ) = $call_ssh_reinit_if_check_fails->(
732 $self,
733 'open_ex',
734 { stdin_pipe => 1, stdout_pipe => 1, stderr_to_stdout => 1 },
735 q{export PERLCODE='use Storable;$Storable::Eval=1;my $input;while ($input .= <STDIN>) { if ($input =~ /\d+START_STORABLE(.*)STOP_STORABLE\d+/) { my @result = eval { my $in_hr = Storable::thaw(pack("H*", $1)); if ( ref $in_hr->{code} ) { return $in_hr->{wantarray} ? $in_hr->{code}->(@{$in_hr->{args}}) : scalar $in_hr->{code}->(@{$in_hr->{args}});} return $in_hr->{wantarray} ? eval $in_hr->{code} : scalar eval $in_hr->{code};}; print $$ . "START_STORABLE" . unpack("H*", Storable::freeze( { data => \@result, error => "$@" })) . "STOP_STORABLE" . $$ . "\n";exit;}}'; }
736 . $exe
737 . q{ -e "$PERLCODE";}
738 );
739  
740 0 ▶ die "Failed to connect: $!" unless ($pid);
Branch: 1 branch
BranchTrueFalseTotal
unless $pid 0 0 0
741 0 print $in_fh $$ . "START_STORABLE" . unpack( "H*", Storable::freeze( { code => $code, args => $args, wantarray => wantarray() } ) ) . "STOP_STORABLE" . $$ . "\n";
742 0 close $in_fh;
743  
744 0 my $output = '';
745 0 ▶ while ( $out_fh->sysread( $output, 4096, length($output) ) > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($out_fh->sysread($output, 4096, length $output) > 0) 0 0 0
746 0 1;
747 }
748 0 close $out_fh;
749 0 waitpid( $pid, 0 );
750  
751 0 my $result = { error => "Unable to deserialize output from remote_eval: $output" };
752 0 ▶ if ( $output =~ /\d+START_STORABLE(.*)STOP_STORABLE\d+/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($output =~ /\d+START_STORABLE(.*)STOP_STORABLE\d+/) 0 0 0
753 0 $result = Storable::thaw( pack( "H*", $1 ) );
754 }
755  
756 0 ▶ die $result->{error} if ( $result->{error} );
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"error"} 0 0 0
757  
758 0 ▶ return wantarray ? @{ $result->{data} } : $result->{data}[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
759 }
760  
761  
762 0 ▶sub cmd_stream {
Subroutine cmd_stream: not called CC=1 SCAR=6.9
Pod documented
763 0 my ( $self, @cmd ) = @_;
764 0 ▶ my $line_reader = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
765 0 my ( $self, $out, $stash_param ) = @_;
766 0 $out =~ s/[\r\n]{1,2}$//;
767 0 $self->diag($out);
768 0 $self->{$stash_param} .= "$out\n";
769  
770 0 return;
771 0 };
772 0 return $send->( $self, $line_reader, @cmd );
773 }
774  
775  
776 9 1;
777  
778 __END__
↑ Summary More/Linux.pm »