More.pm

filter: Statementstmt 59.2% 257 / 434 Branchbran 38.2% 81 / 212 Conditioncond 37.2% 32 / 86 MC/DCmcdc 15.3% 8 / 52 Subroutinesub 69.3% 34 / 49 Podpod 100% 12 / 12 totaltotal 50.1% 424 / 845 CC 144 SCAR 36.1
CC
144
Cov
51%
write
110.0
__ANON__
79.9
eval_full
72.0
CRAP 36.9
↑ Summary More/Linux.pm »
1 package Net::OpenSSH::More;
2 10 $Net::OpenSSH::More::VERSION = '1.07';
3 #ABSTRACT: Net::OpenSSH submodule with many useful features
4  
5 10 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 10 ▶use parent 'Net::OpenSSH';
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 10 ▶use Data::UUID ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 10 ▶use Expect ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 10 ▶use File::HomeDir ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 10 ▶use File::Temp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 10 ▶use Fcntl ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 10 ▶use IO::Pty ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 10 ▶use IO::Socket::INET ();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 10 ▶use IO::Socket::INET6 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 10 ▶use IO::Stty ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 10 ▶use List::Util qw{first};
Subroutine BEGIN: called CC=1 SCAR=0.0
20 10 ▶use Net::DNS::Resolver ();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 10 ▶use Net::IP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
22 10 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 10 ▶use Term::ANSIColor ();
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25  
26 my %defaults = (
27 10 ▶ 'user' => $ENV{'USER'} || getpwuid($>),
Condition33%1/3
$ENV{'USER'} || getpwuid $>
l!l&&r!l&&!r
0100
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 10 our %cache;
38 10 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 10 };
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 10 };
66  
67 11 ▶my $resolve_login_method = sub {
Subroutine __ANON__: called CC=9 SCAR=35.3
68 11 my ($opts) = @_;
69  
70 11 ▶ my $chosen = first { $opts->{$_} } qw{key_path password};
Subroutine __ANON__: called CC=1 SCAR=0.0
71 11 ▶ $chosen //= '';
Condition50%1/2
$chosen //= ""
l!l
110
MC/DC0%0/1
$chosen //= ""
$chosen
Truth table50%1/2
A
A= $chosen
Aresult
11
00
72 11 ▶ 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 11 11
Condition33%1/3
$chosen eq "key_path" and not &$check_local_perms($opts->{"key_path"}, 384)
!ll&&!rl&&r
1100
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 11 ▶ return $chosen if $chosen;
Branch: 1 branch
BranchTrueFalseTotal
if $chosen 11 0 11
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 10 };
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 10 };
93  
94 # Knock on the server till it responds, or doesn't. Try both ipv4 and ipv6.
95 19 ▶my $ping = sub {
Subroutine __ANON__: called CC=10 SCAR=35.9
96 19 my ($opts) = @_;
97  
98 19 my $timeout = 30;
99 19 my ( $host_info, $ip, $r_type );
100 19 ▶ if ( my $ip_obj = Net::IP->new( $opts->{'host'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ip_obj = 'Net::IP'->new($opts->{'host'})) { } 19 0 19
101 19 ▶ $r_type = $ip_obj->ip_is_ipv4 ? 'A' : 'AAAA';
Branch: 1 branch
BranchTrueFalseTotal
$ip_obj->ip_is_ipv4 ? : 19 0 19
102 19 $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 19 my %family_map = ( 'A' => 'INET', 'AAAA' => 'INET6' );
119 19 my $start = time;
120  
121 19 ▶ while ( ( time - $start ) <= $timeout ) {
Branch: 1 branch
BranchTrueFalseTotal
if (time - $start <= $timeout) 19 0 19
122 return 1 if "IO::Socket::$family_map{$r_type}"->new(
123 'PeerAddr' => $ip,
124 19 ▶ 'PeerPort' => $opts->{'port'},
Branch: 1 branch
BranchTrueFalseTotal
if ("IO::Socket::$family_map{$r_type}")->new("PeerAddr", $ip, "PeerPort", $opts->{"port"}, "Proto", "tcp", "Timeout", $timeout) 19 0 19
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 10 };
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 10 };
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 10 my $init_ssh;
155 12 ▶$init_ssh = sub {
Subroutine __ANON__: called CC=41 SCAR=43.8
156 12 my ( $class, $opts ) = @_;
157  
158 # Always clear the cache if possible when we get here.
159 12 ▶ if ( $opts->{'_cache_index'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"_cache_index"}) 12 0 12
160 12 local $disable_destructor = 1;
161 12 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 12 ▶ if ( !$opts->{'_host_sock_key'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts->{"_host_sock_key"}) 11 1 12
168 11 $opts->{'_host_sock_key'} = "NET_OPENSSH_MASTER_$opts->{'host'}_$opts->{'user'}";
169 11 $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 12 ▶ $opts->{'_tmp_obj'} = File::Temp->newdir() if !$opts->{'_tmp_obj'};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"_tmp_obj"} 11 1 12
175 12 my $tmp_dir = $opts->{'_tmp_obj'}->dirname();
176 12 ▶ diag( { '_opts' => $opts }, "Temp dir: $tmp_dir" ) if $opts->{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"debug"} 0 12 12
177 12 my $temp_fh;
178  
179 # Use an existing connection if possible, otherwise make one
180 12 ▶ 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 12 12
Condition33%1/3
$ENV{$opts->{"_host_sock_key"}} and -e $ENV{$opts->{"_host_sock_key"}}
!ll&&!rl&&r
1200
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 12 ▶ if ( !$opts->{'debug'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts->{"debug"}) 12 0 12
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 12 ▶ 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: $!") 12 0 12
192 12 $opts->{'master_stderr_fh'} = $temp_fh;
193 }
194 12 $opts->{'strict_mode'} = 0;
195  
196 12 $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 12 12
204 12 ▶ if ( $opts->{'key_path'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"key_path"}) 0 12 12
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 12 ▶ $opts->{'_restore_auth_sock'} = delete $ENV{SSH_AUTH_SOCK} if $opts->{'no_agent'};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"no_agent"} 0 12 12
215 12 ▶ $opts->{'forward_agent'} = 1 if $ENV{'SSH_AUTH_SOCK'};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"SSH_AUTH_SOCK"} 0 12 12
216 }
217  
218 12 my $status = 0;
219 12 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 12 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 12 };
233 12 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 19 ▶ sleep $opts->{'retry_interval'} if $attempt > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $attempt > 1 7 12 19
238  
239 19 local $@;
240 19 my $up = $ping->($opts);
241 19 ▶ if ( !$up ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($up) 0 19 19
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 19 ▶ $opts->{'ctl_path'} = "$tmp_dir/$attempt" if !$opts->{'external_master'};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"external_master"} 19 0 19
250  
251 # Now, per the POD of Net::OpenSSH, new will NEVER DIE, so just trust it.
252 19 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 19 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 19 ▶ if ($temp_fh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($temp_fh) 19 0 19
259 19 truncate( $temp_fh, 0 );
260 19 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 19 $self = $class4super->SUPER::new( map { $_ => $opts->{$_} } grep { defined $opts->{$_} } @base_module_opts );
268 19 my $ssh_error = $self->error;
269 19 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 19 ▶ if ( $temp_fh && -s $temp_fh ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($temp_fh and -s $temp_fh) 4 15 19
Condition66%2/3
$temp_fh and -s $temp_fh
!ll&&!rl&&r
0154
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 19 ▶ if ( $error && !$opts->{'retry_on_auth_failure'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error and not $opts->{"retry_on_auth_failure"}) 4 15 19
Condition100%3/3
$error and not $opts->{"retry_on_auth_failure"}
!ll&&!rl&&r
964
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 18 ▶ if ( ref $self ne 'Net::OpenSSH::More' || $ssh_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self ne "Net::OpenSSH::More" or $ssh_error) 9 9 18
Condition66%2/3
ref $self ne "Net::OpenSSH::More" or $ssh_error
l!l&&r!l&&!r
099
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 9 ▶ bless $self, $class if ref $self ne $class;
Branch: 1 branch
BranchTrueFalseTotal
if ref $self ne $class 0 9 9
296  
297 9 ▶ if ( $status = $self->check_master() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status = $self->check_master) 9 0 9
298 9 ▶ 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 7 9
299 9 last;
300 }
301 0 $said->( 'the master connection did not answer a check', $attempt );
302 }
303 11 ▶ $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 9 11
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 9 ▶ if ( $opts->{'external_master'} && !$far_end_answers->($self) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"external_master"} and not &$far_end_answers($self)) 0 9 9
Condition33%1/3
$opts->{"external_master"} and not &$far_end_answers($self)
!ll&&!rl&&r
900
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 9 ▶ if ( !$opts->{'no_cache'} && !$ENV{ $opts->{'_host_sock_key'} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts->{"no_cache"} or $ENV{$opts->{"_host_sock_key"}}) 3 6 9
Condition66%2/3
$opts->{"no_cache"} or $ENV{$opts->{"_host_sock_key"}}
l!l&&r!l&&!r
603
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 9 $self->{'host_sock'} = $ENV{ $opts->{'_host_sock_key'} };
336  
337 9 return $self;
338 10 };
339  
340 # Reconnects in place. The caller holds $self and retries on it, so the new
341 # master has to end up inside that object: assigning to $self here rebinds only
342 # this sub's copy, and the retry then runs on the dead connection.
343 1 ▶my $connection_check = sub {
Subroutine __ANON__: called CC=5 SCAR=16.4
344 1 my ($self) = @_;
345 1 ▶ return 1 if $self->check_master;
Branch: 1 branch
BranchTrueFalseTotal
if $self->check_master 0 1 1
346 1 local $@;
347 1 local $disable_destructor = 1;
348 1 my $fresh = eval { $init_ssh->( ref $self, $self->{'_opts'} ) };
349 1 ▶ return 0 if !$fresh;
Branch: 1 branch
BranchTrueFalseTotal
unless $fresh 0 1 1
350  
351 # What belongs to the caller rather than to the connection. The shell ran
352 # over the old master, so it goes with it.
353 1 my %kept = map { $_ => $self->{$_} } grep { exists $self->{$_} } qw{_opts file_backups};
354 1 ▶ $self->{'persistent_shell'}->close() if $self->{'persistent_shell'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"persistent_shell"} 0 1 1
355 1 %$self = ( %$fresh, %kept );
356  
357 # Emptied, so that its destructor finds nothing to tear down, least of all
358 # the master that $self now holds.
359 1 %$fresh = ();
360 1 ▶ $cache{ $self->{'_opts'}{'_cache_index'} } = $self if !$self->{'_opts'}{'no_cache'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_opts"}{"no_cache"} 0 1 1
361 1 return 1;
362 10 };
363  
364 # Try calling the function.
365 # If it fails, then call $connection_check to reconnect if needed.
366 #
367 # The goal is to avoid calling $connection_check
368 # unless something goes wrong since it adds about
369 # 450ms to each ssh command.
370 #
371 # If the control socket has gone away, call
372 # $connection_check ahead of time to reconnect it.
373 1 ▶my $call_ssh_reinit_if_check_fails = sub {
Subroutine __ANON__: called CC=5 SCAR=18.3
374 1 my ( $self, $func, @args ) = @_;
375  
376 1 ▶ $connection_check->($self) if !-S $self->{'_ctl_path'};
Branch: 1 branch
BranchTrueFalseTotal
unless -S $self->{"_ctl_path"} 1 0 1
377  
378 1 local $@;
379 1 my @ret = eval { $self->$func(@args) };
380 1 ▶ my $ssh_error = $@ || $self->error;
Condition33%1/3
$@ || $self->error
l!l&&r!l&&!r
001
MC/DC0%0/2
$@ || $self->error
$@ $self->error
Truth table33%1/3
A || B
A= $@B= $self->error
ABresult
1X1
011
000
381 1 ▶ warn "[WARN] $ssh_error" if $ssh_error;
Branch: 1 branch
BranchTrueFalseTotal
if $ssh_error 0 1 1
382 1 ▶ return @ret if !$ssh_error;
Branch: 1 branch
BranchTrueFalseTotal
unless $ssh_error 1 0 1
383  
384 0 $connection_check->($self);
385 0 return ( $self->$func(@args) );
386 10 };
387  
388 8 ▶my $post_connect = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
389 8 my ( $self, $opts ) = @_;
390  
391 8 ▶ $self->{'persistent_shell'}->close() if $self->{'persistent_shell'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"persistent_shell"} 0 8 8
392 8 undef $self->{'persistent_shell'};
393  
394 8 return;
395 10 };
396  
397 0 ▶my $trim = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
398 0 my ($string) = @_;
399 0 ▶ return '' unless length $string;
Branch: 1 branch
BranchTrueFalseTotal
unless length $string 0 0 0
400 0 $string =~ s/^\s+//;
401 0 $string =~ s/\s+$//;
402 0 return $string;
403 10 };
404  
405 1 ▶my $send = sub {
Subroutine __ANON__: called CC=7 SCAR=20.0
406 1 my ( $self, $line_reader, @command ) = @_;
407  
408 1 ▶ $self->diag( "[DEBUG][$self->{'_opts'}{'host'}] EXEC " . join( " ", @command ) ) if $self->{'_opts'}{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_opts"}{"debug"} 0 1 1
409  
410 1 my ( $pty, $err, $pid ) = $call_ssh_reinit_if_check_fails->( $self, 'open3pty', @command );
411 1 ▶ $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 1 1
Condition33%1/3
not defined $pid or $self->error
l!l&&r!l&&!r
001
MC/DC0%0/2
not defined $pid or $self->error
not defined $pid $self->error
Truth table33%1/3
not(A) or B
A= not defined $pidB= $self->error
ABresult
1X1
011
000
412  
413 1 $self->{'_out'} = "";
414 1 ▶ $line_reader = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
415 1 my ( $self, $out, $stash_param ) = @_;
416 1 $out =~ s/[\r\n]{1,2}$//;
417 1 $self->{$stash_param} .= "$out\n";
418 1 return;
419 }
420 1 ▶ if ref $line_reader ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $line_reader ne "CODE" 1 0 1
421  
422 # TODO make this async so you can stream STDERR *in order*
423 # with STDOUT as well
424 # That said, most only care about error if command fails, so...
425 1 my $out;
426 1 ▶ $line_reader->( $self, $out, '_out' ) while $out = $pty->getline;
Branch: 1 branch
BranchTrueFalseTotal
$out = $pty->getline and do { &$line_reader($self, $out, "_out") } 1 1 2
427 1 $pty->close;
428  
429 # only populate error if there's an error #
430 1 $self->{'_err'} = '';
431 1 ▶ $line_reader->( $self, $out, '_err' ) while $out = $err->getline;
Branch: 1 branch
BranchTrueFalseTotal
$out = $err->getline and do { &$line_reader($self, $out, "_err") } 0 1 1
432 1 $err->close;
433  
434 1 waitpid( $pid, 0 );
435 1 return $? >> 8;
436 10 };
437  
438 10 my $TERMINATOR = "\r\n";
439 0 ▶my $send_persistent_cmd = sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
440 0 my ( $self, $command, $uuid ) = @_;
441  
442 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
443 0 $command = join( ' ', @$command );
444 0 my $actual_cmd = "UUID='$uuid'; echo \"BEGIN \$UUID\"; $command; echo \"___\$?___\"; echo; echo \"EOF \$UUID\"";
445 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
446  
447 #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.
448 0 $self->{'expect'}->print("${actual_cmd}${TERMINATOR}");
449  
450 # Rather than take the approach of cPanel, which commands then polls async,
451 # it is more straightforward to echo unique strings before and after the command.
452 # This made getting the return code somewhat more complicated, as you can see below.
453 # That said, it also makes you not have to worry about doing things asynchronously.
454 0 $self->{'expect'}->expect( $self->{'_opts'}{'expect_timeout'}, '-re', qr/BEGIN $uuid/m );
455 0 $self->{'expect'}->expect( $self->{'_opts'}{'expect_timeout'}, '-re', qr/EOF $uuid/m ); # If nothing is printed in timeout, give up
456  
457 # Get the actual output, remove terminal grunk
458 0 my $message = $trim->( $self->{'expect'}->before() );
459 0 $message =~ s/[\r\n]{1,2}$//; # Remove 'secret newline' control chars
460 0 $message =~ s/\x{d}//g; # More control chars
461 0 $message = Term::ANSIColor::colorstrip($message); # Strip colors
462  
463 # Find the exit code
464 0 my ($code) = $message =~ m/___(\d*)___$/;
465 0 ▶ unless ( defined $code ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $code) 0 0 0
466  
467 # Tell the user if they've made a boo-boo
468 0 my $possible_err = $trim->( $self->{'expect'}->before() );
469 0 $possible_err =~ s/\s//g;
470 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
471  
472 0 $die_no_trace->(
473 "Could not determine exit code!
474 It timed out (went $self->{'_opts'}{'expect_timeout'}s without printing anything).
475 Run command outside of the persistent terminal please."
476 );
477 }
478 0 $message =~ s/___(\d*)___$//g;
479  
480 0 return ( $message, $code );
481 10 };
482  
483 0 ▶my $do_persistent_command = sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
484 0 my ( $self, $command, $no_stderr ) = @_;
485  
486 0 ▶ if ( !$self->{'persistent_shell'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"persistent_shell"}) 0 0 0
487 0 my ( $pty, $pid ) = $call_ssh_reinit_if_check_fails->( $self, 'open2pty', $self->{'_remote_shell'} );
488 0 ▶ die "Got no pty back from open2pty: " . $self->error if !$pty;
Branch: 1 branch
BranchTrueFalseTotal
unless $pty 0 0 0
489  
490 # You might think that the below settings are important.
491 # In most cases, they are not.
492 0 $pty->set_raw();
493 0 $pty->stty( 'raw', 'icrnl', '-echo' );
494 0 $pty->slave->stty( 'raw', 'icrnl', '-echo' );
495  
496 #Hook in expect
497 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
498 0 $self->{'expect'} = Expect->init($pty);
499 0 $self->{'expect'}->restart_timeout_upon_receive(1); #Logabandon by default
500  
501 # XXX WARNING bashisms. That said, I'm not sure how to better do this yet portably.
502 0 my $expect_env_cmd = "export PS1=''; export TERM='dumb'; unset HISTFILE; export FOE='configured'; stty raw icrnl -echo; unalias -a; echo \"EOF=\$FOE\"";
503 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
504 0 $self->{'expect'}->print("${expect_env_cmd}${TERMINATOR}");
505 0 $self->{'expect'}->expect( $self->{'_opts'}{'expect_timeout'}, '-re', qr/EOF=configured/ );
506 0 $self->{'expect'}->clear_accum();
507  
508 #cache
509 0 $self->{'persistent_shell'} = $pty;
510 0 $self->{'persistent_pid'} = $pid;
511 }
512  
513 #execute the command
514 0 my $uuid = Data::UUID->new()->create_str();
515 0 ▶ push @$command, '2>', "/tmp/stderr_$uuid.out" unless $no_stderr;
Branch: 1 branch
BranchTrueFalseTotal
unless $no_stderr 0 0 0
516 0 my ( $oot, $code ) = $send_persistent_cmd->( $self, $command, $uuid );
517 0 $self->{'_out'} = $oot;
518  
519 0 ▶ unless ($no_stderr) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($no_stderr) 0 0 0
520  
521 #Grab stderr
522 0 ( $self->{'_err'} ) = $send_persistent_cmd->( $self, [ '/usr/bin/cat', "/tmp/stderr_$uuid.out" ] );
523  
524 #Clean up
525 0 $send_persistent_cmd->( $self, [ '/usr/bin/rm', '-f', "/tmp/stderr_$uuid.out" ] );
526 }
527  
528 0 return int($code);
529 10 };
530  
531 #######################
532 # END PRIVATE METHODS #
533 #######################
534  
535  
536 12 ▶sub new {
Subroutine new: called CC=11 SCAR=24.5
Pod documented
537 12 my ( $class, %opts ) = @_;
538 12 ▶ $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 12 12
Condition33%1/3
not $opts{"host"} or $opts{"host"} eq "localhost"
l!l&&r!l&&!r
0012
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
539 12 ▶ $opts{'remote_shell'} ||= 'bash'; # prevent stupid defaults
Condition50%1/2
$opts{"remote_shell"} ||= "bash"
l!l
012
MC/DC0%0/1
$opts{"remote_shell"} ||= "bash"
$opts{"remote_shell"}
Truth table50%1/2
A
A= $opts{"remote_shell"}
Aresult
11
00
540 12 ▶ $opts{'expect_timeout'} //= 30; # If your program goes over 30s without printing...
Condition50%1/2
$opts{"expect_timeout"} //= 30
l!l
012
MC/DC0%0/1
$opts{"expect_timeout"} //= 30
$opts{"expect_timeout"}
Truth table50%1/2
A
A= $opts{"expect_timeout"}
Aresult
11
00
541  
542 # Set defaults, check if we can return early
543 12 %opts = ( %defaults, %opts );
544 12 $opts{'_cache_index'} = "$opts{'user'}_$opts{'host'}_$opts{'port'}";
545  
546 # A cached object is only worth having if it still reaches the machine it
547 # was built for. Rebuild a host at the same address -- which is an ordinary
548 # thing to do to a VM -- and the cached object here is pointed at something
549 # that no longer exists, while its local master sits there looking healthy.
550 # Handing that back means the caller's first command dies on a broken pipe
551 # rather than the login failing, which is a long way from the cause.
552 12 ▶ 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 10 12
Condition100%3/3
not $opts{"no_cache"} and $Net::OpenSSH::More::cache{$opts{"_cache_index"}}
!ll&&!rl&&r
822
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
553 2 my $cached = $cache{ $opts{'_cache_index'} };
554 2 ▶ return $cached if $far_end_answers->($cached);
Branch: 1 branch
BranchTrueFalseTotal
if &$far_end_answers($cached) 1 1 2
555  
556 1 local $disable_destructor = 1;
557 1 delete $cache{ $opts{'_cache_index'} };
558 }
559  
560 # Figure out how we're gonna login
561 11 $opts{'_login_method'} = $resolve_login_method->( \%opts );
562  
563 # check permissions on base files if we got here
564 11 ▶ $check_local_perms->( "$opts{'home'}/.ssh", 0700, 1 ) if -e "$opts{'home'}/.ssh";
Branch: 1 branch
BranchTrueFalseTotal
if -e qq[$opts{"home"}/.ssh] 0 11 11
565 11 ▶ $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 11 11
566  
567 # Make the connection
568 11 my $self = $init_ssh->( $class, \%opts );
569 8 ▶ $cache{ $opts{'_cache_index'} } = $self unless $opts{'no_cache'};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"no_cache"} 3 5 8
570  
571 # Stash opts for later
572 8 $self->{'_opts'} = \%opts;
573  
574 # Establish persistent shell, etc.
575 8 $post_connect->( $self, \%opts );
576  
577 8 return $self;
578 }
579  
580  
581 0 ▶sub use_persistent_shell {
Subroutine use_persistent_shell: not called CC=2 SCAR=17.9
Pod documented
582 0 my ( $self, $use_shell ) = @_;
583 0 ▶ return $self->{'_opts'}{'use_persistent_shell'} if !defined($use_shell);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $use_shell 0 0 0
584 0 return $self->{'_opts'}{'use_persistent_shell'} = $use_shell;
585 }
586  
587  
588 0 ▶sub copy {
Subroutine copy: not called CC=1 SCAR=6.9
Pod documented
589 0 die "Unimplemented, use a subclass of this perhaps?";
590 }
591  
592  
593 0 ▶sub backup_files {
Subroutine backup_files: not called CC=4 SCAR=30.0
Pod documented
594 0 my ( $self, @files ) = @_;
595  
596 # For each file passed in
597 0 foreach my $file (@files) {
598  
599 # If the file hasn't already been backed up
600 0 ▶ if ( !defined $self->{'file_backups'}{$file} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"file_backups"}{$file}) 0 0 0
601  
602 # and the file exists
603 0 ▶ if ( $self->sftp->test_e($file) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->sftp->test_e($file)) { } 0 0 0
604  
605 # then back it up
606 0 $self->{'file_backups'}{$file} = time;
607 0 my $bkup = $file . '.' . $self->{'file_backups'}{$file};
608 0 $self->diag("[INFO] Backing up '$file' to '$bkup'");
609 0 $self->copy( $file, $bkup ); # XXX Probably not that portable, maybe move to Linux.pm somehow?
610  
611 # otherwise if the file to be backed up doesn't exist
612 }
613 else {
614 # then just note that a file may need to be deleted later
615 0 $self->{'file_backups'}{$file} = '';
616 }
617 }
618 }
619 0 return;
620 }
621  
622  
623 1 ▶sub restore_files {
Subroutine restore_files: called CC=6 SCAR=29.9
Pod documented
624 1 my ( $self, @files ) = @_;
625  
626 # If no files were passed in then grab all files that have been backed up
627 1 ▶ @files = keys( %{ $self->{'file_backups'} } ) if !@files;
Branch: 1 branch
BranchTrueFalseTotal
unless @files 1 0 1
628  
629 # foreach file
630 1 foreach my $file (@files) {
631  
632 # that has been marked as modified
633 0 ▶ if ( defined $self->{'file_backups'}{$file} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"file_backups"}{$file}) 0 0 0
634  
635 # if a backup exists
636 0 ▶ if ( $self->{'file_backups'}{$file} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'file_backups'}{$file}) { } 0 0 0
637  
638 # then restore the backup
639 0 my $bkup = $file . '.' . $self->{'file_backups'}{$file};
640 0 ▶ if ( $self->sftp->test_e($bkup) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->sftp->test_e($bkup)) 0 0 0
641 0 $self->diag("[INFO] Restoring backup '$file' from '$bkup'");
642 0 $self->sftp->rename( $bkup, $file, 'overwrite' => 1 );
643 }
644  
645 # otherwise no backup exists we just need to delete the modified file
646 }
647 else {
648 0 $self->diag("[INFO] Deleting '$file' to restore system state (beforehand the file didn't exist)");
649 0 $self->sftp->remove($file);
650 }
651 }
652 0 delete $self->{'file_backups'}{$file};
653 }
654 1 return;
655 }
656  
657  
658 21 ▶sub DESTROY {
Subroutine DESTROY: called CC=6 SCAR=18.6
659 21 my ($self) = @_;
660 21 ▶ 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 20 1 21
Condition66%4/6
not $self->{"_perl_pid"} or $$ != $self->{"_perl_pid"} or $Net::OpenSSH::More::disable_destructor
l!l&&r!l&&!r
2001
not $self->{"_perl_pid"} or $$ != $self->{"_perl_pid"}
l!l&&r!l&&!r
2001
MC/DC33%1/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 table50%2/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
661 1 $self->restore_files();
662 1 ▶ $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 1 1
663 1 ▶ $self->{'persistent_shell'}->close() if $self->{'persistent_shell'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"persistent_shell"} 0 1 1
664  
665 1 return $self->SUPER::DESTROY();
666 }
667  
668  
669 8 ▶sub diag {
Subroutine diag: called CC=2 SCAR=6.9
Pod documented
670 8 my ( $self, @msgs ) = @_;
671 8 print STDOUT "$self->{'_opts'}{'output_prefix'}$_\n" for @msgs;
672 8 return;
673 }
674  
675  
676 1 ▶sub cmd {
Subroutine cmd: called CC=6 SCAR=18.9
Pod documented
677 1 my ($self) = shift;
678 1 ▶ my $opts = ref $_[0] eq 'HASH' ? shift : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 0 1 1
679 1 my @command = @_;
680  
681 1 ▶ $die_no_trace->( 'No command specified', 'PEBCAK' ) if !@command;
Branch: 1 branch
BranchTrueFalseTotal
unless @command 0 1 1
682  
683 1 my $ret;
684 1 ▶ $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"} 1 0 1
685 1 ▶ if ( $opts->{'use_persistent_shell'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{'use_persistent_shell'}) { } 0 1 1
686 0 $ret = $do_persistent_command->( $self, \@command, $opts->{'no_stderr'} );
687 }
688 else {
689 1 $ret = $send->( $self, undef, @command );
690 }
691 1 chomp( my $out = $self->{'_out'} );
692 1 ▶ my $err = $self->error || '';
Condition50%1/2
$self->error || ''
l!l
01
MC/DC0%0/1
$self->error || ''
$self->error
Truth table50%1/2
A
A= $self->error
Aresult
11
00
693  
694 1 $self->{'last_exit_code'} = $ret;
695 1 return ( $out, $err, $ret );
696 }
697  
698  
699 0 ▶sub cmd_exit_code {
Subroutine cmd_exit_code: not called CC=1 SCAR=6.9
Pod documented
700 0 my ( $self, @args ) = @_;
701 0 return ( $self->cmd(@args) )[2];
702 }
703  
704 0 ▶sub sftp {
Subroutine sftp: not called CC=3 SCAR=24.8
Pod documented
705 0 my ($self) = @_;
706  
707 0 ▶ unless ( defined $self->{'_sftp'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"_sftp"}) 0 0 0
708 0 $self->{'_sftp'} = $self->SUPER::sftp();
709 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
710 }
711 0 return $self->{'_sftp'};
712 }
713  
714  
715 0 ▶sub write {
Subroutine write: not called CC=10 SCAR=47.0
Pod documented
716 0 my ( $self, $file, $content, $mode, $owner, $group ) = @_;
717  
718 0 ▶ die '[PARAMETER] No file specified' if !defined $file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file 0 0 0
719 0 ▶ die '[PARAMETER] File content not specified' if !defined $content;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 0 0 0
720  
721 0 my %opts;
722 0 ▶ $opts{'perm'} = $mode if $mode;
Branch: 1 branch
BranchTrueFalseTotal
if $mode 0 0 0
723 0 my $ret = $self->sftp()->put_content( $content, $file, %opts );
724 0 ▶ warn "[WARN] Write failed: " . $self->sftp()->error() if !$ret;
Branch: 1 branch
BranchTrueFalseTotal
unless $ret 0 0 0
725  
726 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
727 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
728 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
729 0 $ret = $self->sftp()->chown( $file, $owner, $group );
730 0 ▶ warn "[WARN] Couldn't chown $file" if $ret;
Branch: 1 branch
BranchTrueFalseTotal
if $ret 0 0 0
731 }
732  
733 0 return $ret;
734 }
735  
736  
737 0 ▶sub eval_full {
Subroutine eval_full: not called CC=8 SCAR=42.8
Pod documented
738 0 my ( $self, %options ) = @_;
739 0 my $code = $options{code};
740 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
741 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
742  
743 0 require Storable;
744 0 local $Storable::Deparse = 1;
745  
746 0 my ( $in_fh, $out_fh, undef, $pid ) = $call_ssh_reinit_if_check_fails->(
747 $self,
748 'open_ex',
749 { stdin_pipe => 1, stdout_pipe => 1, stderr_to_stdout => 1 },
750 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;}}'; }
751 . $exe
752 . q{ -e "$PERLCODE";}
753 );
754  
755 0 ▶ die "Failed to connect: $!" unless ($pid);
Branch: 1 branch
BranchTrueFalseTotal
unless $pid 0 0 0
756 0 print $in_fh $$ . "START_STORABLE" . unpack( "H*", Storable::freeze( { code => $code, args => $args, wantarray => wantarray() } ) ) . "STOP_STORABLE" . $$ . "\n";
757 0 close $in_fh;
758  
759 0 my $output = '';
760 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
761 0 1;
762 }
763 0 close $out_fh;
764 0 waitpid( $pid, 0 );
765  
766 0 my $result = { error => "Unable to deserialize output from remote_eval: $output" };
767 0 ▶ if ( $output =~ /\d+START_STORABLE(.*)STOP_STORABLE\d+/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($output =~ /\d+START_STORABLE(.*)STOP_STORABLE\d+/) 0 0 0
768 0 $result = Storable::thaw( pack( "H*", $1 ) );
769 }
770  
771 0 ▶ die $result->{error} if ( $result->{error} );
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"error"} 0 0 0
772  
773 0 ▶ return wantarray ? @{ $result->{data} } : $result->{data}[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
774 }
775  
776  
777 0 ▶sub cmd_stream {
Subroutine cmd_stream: not called CC=1 SCAR=6.9
Pod documented
778 0 my ( $self, @cmd ) = @_;
779 0 ▶ my $line_reader = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
780 0 my ( $self, $out, $stash_param ) = @_;
781 0 $out =~ s/[\r\n]{1,2}$//;
782 0 $self->diag($out);
783 0 $self->{$stash_param} .= "$out\n";
784  
785 0 return;
786 0 };
787 0 return $send->( $self, $line_reader, @cmd );
788 }
789  
790  
791 10 1;
792  
793 __END__
↑ Summary More/Linux.pm »