Any/OS/MSWin.pm untested

filter: Statementstmt 0.0% 0 / 280 Branchbran 0.0% 0 / 104 Conditioncond 0.0% 0 / 193 MC/DCmcdc 0.0% 0 / 105 Subroutinesub 0.0% 0 / 33 Podpod 0.0% 0 / 20 totaltotal 0.0% 0 / 735 CC 52 SCAR 44.8
CC
52
Cov
0%
io3
272.0
open4
182.0
__set_pipe_blocking
30.0
CRAP 88.2
1 package Net::SSH::Any::OS::MSWin;
2  
3 use strict;
4 use warnings;
5  
6 use Carp;
7 use Socket;
8 use Errno;
9 use Net::SSH::Any::Util qw($debug _debug _debug_hexdump _first_defined _array_or_scalar_to_list _warn);
10 use Net::SSH::Any::Constants qw(:error);
11 use Time::HiRes qw(sleep time);
12 use Config ();
13 use Win32::API ();
14 use File::Spec ();
15  
16 require Net::SSH::Any::OS::_Base;
17 our @ISA = qw(Net::SSH::Any::OS::_Base);
18  
19 sub pipe {
20 my $any = shift;
21 my ($r, $w);
22 unless (CORE::pipe $r, $w) {
23 $any->_set_error(SSHA_LOCAL_IO_ERROR, "Unable to create pipe: $!");
24 return
25 }
26 binmode $r;
27 binmode $w;
28 ($r, $w);
29 }
30  
31 sub make_dpipe {
32 my ($any, $proc, $in, $out) = @_;
33 require Net::SSH::Any::OS::MSWin::DPipe;
34 Net::SSH::Any::OS::MSWin::DPipe->_upgrade_fh_to_dpipe($out, $any, $proc, $in);
35 }
36  
37 my $win32_set_named_pipe_handle_state;
38 my $win32_get_osfhandle;
39 my $win32_set_handle_information;
40 my $win32_open_process;
41 my $win32_get_exit_code_process;
42 my $win32_close_handle;
43 my $win32_get_version;
44 my $win32_get_final_path_name_by_handle;
45 my $win32_get_file_information_by_handle_ex;
46 my $win32_get_current_process_id;
47  
48 my $win32_handle_flag_inherit = 0x1;
49 my $win32_pipe_nowait = 0x1;
50 my $win32_process_query_information = 0x0400;
51  
52 sub __wrap_win32_functions {
53 unless (defined $win32_set_named_pipe_handle_state) {
54 $Config::Config{libperl} =~ /libperl(\d+)/
55 or croak "unable to infer Perl DLL version";
56 my $perl_dll = "perl$1.dll";
57 $debug and $debug & 1024 and _debug "Perl DLL name is $perl_dll";
58 $win32_get_osfhandle = Win32::API::More->new($perl_dll, <<FSIGN)
59 long WINAPIV win32_get_osfhandle(int fd);
60 FSIGN
61 or croak "unable to wrap $perl_dll win32_get_osfhandle function";
62  
63 $win32_set_named_pipe_handle_state = Win32::API::More->new("kernel32.dll", <<FSIGN)
64 BOOL SetNamedPipeHandleState(HANDLE hNamedPipe,
65 LPDWORD lpMode,
66 int ignore1,
67 int ignore2)
68 FSIGN
69 or croak "unable to wrap kernel32.dll SetNamedPipeHandleState function";
70 $win32_set_handle_information = Win32::API::More->new("kernel32.dll", <<FSIGN)
71 BOOL WINAPI SetHandleInformation(HANDLE hObject,
72 DWORD dwMask,
73 DWORD dwFlags);
74 FSIGN
75 or croak "unable to wrap kernel32.dll SetHandleInformation function";
76  
77  
78 $win32_get_exit_code_process = Win32::API::More->new("kernel32.dll", <<FSIGN)
79 BOOL WINAPI GetExitCodeProcess(HANDLE hProcess,
80 LPDWORD lpExitCode)
81 FSIGN
82 or croak "unable to wrap kernel32.dll GetExitCodeProcess";
83  
84 $win32_open_process = Win32::API::More->new("kernel32.dll", <<FSIGN)
85 HANDLE WINAPI OpenProcess(DWORD dwDesiredAccess,
86 BOOL bInheritHandle,
87 DWORD dwProcessId)
88 FSIGN
89 or croak "unable to wrap kernel32.dll OpenProcess";
90  
91 $win32_close_handle = Win32::API::More->new("kernel32.dll", <<FSIGN)
92 BOOL WINAPI CloseHandle(HANDLE hObject)
93 FSIGN
94 or croak "unable to wrap kernel32.dll CloseHandle";
95  
96 $win32_get_version = Win32::API::More->new("kernel32.dll", <<FSIGN)
97 DWORD WINAPI GetVersion()
98 FSIGN
99 or croak "unable to wrap kernel32.dll GetVersion";
100  
101  
102 $win32_get_current_process_id = Win32::API::More->new("kernel32.dll", <<FSIGN)
103 DWORD WINAPI GetCurrentProcessId();
104 FSIGN
105 or croak "unable to wrap GetCurrentProcessId";
106  
107 # $win32_get_final_path_name_by_handle = Win32::API::More->new("kernel32.dll", <<FSIGN)
108 # DWORD WINAPI GetFinalPathNameByHandle(HANDLE hFile,
109 # LPTSTR lpszFilePath,
110 # DWORD cchFilePath,
111 # DWORD dwFlags)
112 # FSIGN
113 # or croak "unable to wrap kernel32.dll GetFinalPathNameByHandle";
114  
115  
116 # $win32_get_file_information_by_handle_ex = Win32::API::More->new("kernel32.dll", <<FSIGN)
117 # BOOL WINAPI GetFileInformationByHandleEx(HANDLE hFile,
118 # DWORD FileInformationClass,
119 # LPVOID lpFileInformation,
120 # DWORD dwBufferSize)
121 # FSIGN
122 # or croak "unable to wrap kernel32.dll GetFileInformationByHandleEx";
123 }
124 1;
125 }
126  
127 __wrap_win32_functions();
128  
129 sub set_file_inherit_flag {
130 my ($any, $file, $value) = @_;
131 __wrap_win32_functions($any);
132 my $fn = fileno $file;
133 my $wh = $win32_get_osfhandle->Call($fn)
134 or die "internal error: win32_get_osfhandle failed unexpectedly";
135 my $flag = ($value ? $win32_handle_flag_inherit : 0);
136 my $success = $win32_set_handle_information->Call($wh, $win32_handle_flag_inherit, $flag);
137 $debug and $debug & 1024 and
138 _debug "Win32::SetHandleInformation($wh, $win32_handle_flag_inherit, $flag) => $success",
139 ($success ? () : (" \$^E: $^E"));
140 $success;
141 }
142  
143 sub export_handle {
144 my ($any, $file) = @_;
145 my $fn = fileno $file;
146 return $win32_get_osfhandle->Call($fn) if $fn >= 0;
147 ()
148 }
149  
150 sub export_current_process {
151 my $any = shift;
152 $win32_get_current_process_id->Call()
153 }
154  
155 sub get_file_name_from_handle {
156 my ($any, $file) = @_;
157 my $fn = fileno $file;
158 my $wh = $win32_get_osfhandle->Call($fn);
159 Net::SSH::Any::Util::_debugf("fileno: %d, handle: 0x%x", $fn, $wh);
160  
161 my $buffer = "1" x 256;
162 my $ok = $win32_get_file_information_by_handle_ex->Call($wh, 0x2, $buffer, length($buffer) - 1);
163 _debug_hexdump "name (ok: $ok)" => $buffer;
164 ""
165 }
166  
167 sub pty { croak "PTYs are not supported on Windows" }
168  
169 sub open4 {
170 my ($any, $fhs, $close, $pty, $stderr_to_stdout, @cmd) = @_;
171 my (@old, @new, $pid, $error);
172  
173 $pty and croak "PTYs are not supported on Windows";
174 grep tied $_, *STDIN, *STDOUT, *STDERR
175 and croak "STDIN, STDOUT or STDERR is tied";
176 grep { defined $_ and (tied $_ or not defined fileno $_) } @$fhs
177 and croak "At least one of the given file-handles is tied or is not backed by a real OS file handle";
178  
179 for my $fd (0..2) {
180 if (defined $fhs->[$fd]) {
181 my $dir = ($fd ? '>' : '<');
182 open $old[$fd], "$dir&", (\*STDIN, \*STDOUT, \*STDERR)[$fd] or $error = $!;
183 open $new[$fd], "$dir&", $fhs->[$fd] or $error = $!;
184 }
185 }
186 open $old[2], '<&', \*STDERR or $error = $! if $stderr_to_stdout;
187  
188 unless (defined $error) {
189 if (not $new[0] or open STDIN, '<&', $new[0]) {
190 if (not $new[1] or open STDOUT, '>&', $new[1]) {
191 $new[2] = \*STDOUT if $stderr_to_stdout;
192 if (not $new[2] or open STDERR, '>&', $new[2]) {
193 $pid = eval { system 1, @cmd } or $error = $!;
194 open STDERR, '>&', $old[2] or $error = $!
195 if $new[2]
196 }
197 else {
198 $error = $!;
199 }
200 open STDOUT, '>&', $old[1] or $error = $!
201 if $new[1];
202 }
203 else {
204 $error = $!
205 }
206 open STDIN, '<&', $old[0] or $error = $!
207 if $new[0];
208 }
209 else {
210 $error = $!;
211 }
212 }
213  
214 undef $_ for @old, @new;
215  
216 if (defined $error) {
217 $any->_set_error(SSHA_CONNECTION_ERROR, "unable to start slave process: $error");
218 }
219  
220 my $proc = { pid => $pid };
221 bless $proc, 'Net::SSH::Any::OS::MSWin::Process';
222 __wrap_win32_functions($any);
223 $proc->{handle} = $win32_open_process->Call($win32_process_query_information, 0, $pid);
224 $debug and $debug & 1024 and _debug "process $pid forked, process handle: $proc->{handle}";
225 return $proc;
226 }
227  
228 sub native_rc {
229 my ($tssh, $proc) = @_;
230 my $native_rc = 0;
231 $win32_get_exit_code_process->Call($proc->{handle}, $native_rc);
232 return $native_rc;
233 }
234  
235 my @retriable = (Errno::EINTR, Errno::EAGAIN, Errno::ENOSPC, Errno::EINVAL);
236 push @retriable, Errno::EWOULDBLOCK if Errno::EWOULDBLOCK != Errno::EAGAIN;
237  
238  
239 sub __set_pipe_blocking {
240 my ($any, $pipe, $blocking) = @_;
241 if (defined $pipe) {
242 __wrap_win32_functions($any);
243 my $fileno = fileno $pipe;
244 my $handle = $win32_get_osfhandle->Call($fileno);
245 $debug and $debug & 1024 and _debug("setting pipe (pipe: ", $pipe,
246 ", fileno: ", $fileno,
247 ", handle: ", $handle, ") to",
248 ($blocking ? " " : " non "), "blocking");
249 my $success = $win32_set_named_pipe_handle_state->Call($handle,
250 ($blocking ? 0 : $win32_pipe_nowait),
251 0, 0);
252 $debug and $debug & 1024 and _debug("Win32::SetNamedPipeHandleState => $success",
253 ($success ? () : " ($^E)"));
254 }
255 }
256  
257 sub io3 {
258 my ($any, $proc, $timeout, $data, $in, $out, $err) = @_;
259 $timeout = $any->{timeout} unless defined $timeout;
260  
261 $debug and $debug & 1024 and _debug "io3 handles: ", $in, ", ", $out, ", ", $err;
262  
263 $data = $any->_os_io3_check_and_clean_data($data, $in);
264  
265 __set_pipe_blocking($any, $in, 0);
266 __set_pipe_blocking($any, $out, 0);
267 __set_pipe_blocking($any, $err, 0);
268  
269 $debug and $debug & 1024 and _debug "data array has ".scalar(@$data)." elements";
270  
271 my $bout = '';
272 my $berr = '';
273 while (defined $in or defined $out or defined $err) {
274 my $delay = 1;
275 if (defined $in) {
276 while (@$data) {
277 unless (defined $data->[0] and length $data->[0]) {
278 shift @$data;
279 next;
280 }
281 my $bytes = syswrite $in, $data->[0];
282 if ($bytes) {
283 $debug and $debug & 1024 and _debug "$bytes bytes of data sent";
284 substr $data->[0], 0, $bytes, '';
285 undef $delay;
286 }
287 else {
288 unless (grep $! == $_, @retriable) {
289 $any->_set_error(SSHA_LOCAL_IO_ERROR, "failed to write to slave stdin channel: $!");
290 close $in;
291 undef $in;
292 undef $delay;
293 }
294 last;
295 }
296 }
297 unless (@$data) {
298 $debug and $debug & 1024 and _debug "closing slave stdin channel";
299 close $in;
300 undef $in;
301 undef $delay;
302 }
303 }
304  
305 if (defined $out) {
306 my $bytes = sysread($out, $bout, 20480, length($bout));
307 if (defined $bytes) {
308 $debug and $debug & 1024 and _debug "received ", $bytes, " bytes of data over stdout";
309 undef $delay;
310 unless ($bytes) {
311 $debug and $debug & 1024 and _debug "closing slave stdout channel at EOF";
312 close $out;
313 undef $out;
314 }
315 }
316 else {
317 unless (grep $! == $_, @retriable) {
318 $any->_set_error(SSHA_LOCAL_IO_ERROR, "failed to read from slave stdout channel: $!");
319 close $out;
320 undef $out;
321 undef $delay;
322 }
323 }
324 }
325  
326 if (defined $err) {
327 my $bytes = sysread($err, $berr, 20480, length($berr));
328 if (defined $bytes) {
329 $debug and $debug & 1024 and _debug "received ", $bytes, " bytes of data over stderr";
330 undef $delay;
331 unless ($bytes) {
332 $debug and $debug & 1024 and _debug "closing slave stderr channel at EOF";
333 close $err;
334 undef $err;
335 }
336 }
337 else {
338 unless (grep $! == $_, @retriable) {
339 $any->_set_error(SSHA_LOCAL_IO_ERROR, "failed to read from slave stderr channel: $!");
340 close $err;
341 undef $err;
342 undef $delay;
343 }
344 }
345 }
346 if ($delay) {
347 # $debug and $debug & 1024 and _debug "delaying...";
348 sleep 0.02; # experimentation has show the load introduced
349 # with this delay is not noticeable!
350 }
351 }
352  
353 $debug and $debug & 1024 and _debug "waiting for child";
354 # FIXME: _io3 is not limited to ssh processes
355 $any->_wait_ssh_proc($proc, $timeout);
356  
357 $debug and $debug & 1024 and _debug "leaving io3()";
358 return ($bout, $berr);
359 }
360  
361 sub validate_cmd {
362 my ($any, $cmd) = @_;
363 return unless defined $cmd;
364 $any->SUPER::validate_cmd($cmd) //
365 $any->SUPER::validate_cmd("$cmd.EXE");
366 }
367  
368 my @cygwin_variants = qw(Cygwin MinGW MinGW\\MSYS\\1.0);
369  
370 sub find_cygwin_cmd {
371 my ($any, $name) = @_;
372  
373 $any->_load_module('Win32::TieRegistry') or return;
374 my %reg;
375 Win32::TieRegistry->import(TiedHash => \%reg);
376  
377 my @rootdirs = grep defined,
378 $reg{'HKEY_CURRENT_USER\\SOFTWARE\\Cygwin\\setup\\rootdir'},
379 $reg{'HKEY_LOCAL_MACHINE\\SOFTWARE\\Cygwin\\setup\\rootdir'};
380  
381 if (defined (my $drive = $ENV{SystemDrive})) {
382 push @rootdirs, File::Spec->catpath($drive, $_)
383 for @cygwin_variants;
384 }
385  
386 for my $rootdir (@rootdirs) {
387 next unless -d $rootdir;
388 for my $bin (qw(bin sbin usr\\bin usr\\sbin)) {
389 my $cmd = $any->_os_validate_cmd(File::Spec->join($rootdir, $bin, $name));
390 return $cmd if defined $cmd;
391 }
392 }
393 }
394  
395 sub find_cmd_by_app {
396 my ($any, $name, $app) = @_;
397 $app = $app->{MSWin} if ref $app;
398 if (defined $app) {
399 lc($app) eq 'cygwin' and
400 return $any->_os_find_cygwin_cmd($name);
401  
402 for my $env (qw{ProgramFiles ProgramFiles(x86)}) {
403 if (defined (my $pf = $ENV{$env})) {
404 my $cmd = $any->_os_validate_cmd(join('\\', $pf, $app, $name));
405 return $cmd if defined $cmd;
406 }
407 }
408 }
409 ()
410 }
411  
412 sub find_user_dirs {
413 my $any = shift;
414 my $drive = $ENV{SystemDrive};
415 my $user = $ENV{USERNAME};
416 my $appdata = $ENV{APPDATA};
417 my @dirs;
418 for my $name (@_) {
419 my $mswin_name = (ref $name ? $name->{MSWin} : $name);
420 if (defined $mswin_name and
421 defined $appdata) {
422 push @dirs, join('\\', $appdata, $mswin_name);
423 }
424 my $cygwin_name = (ref $name ? $name->{Cygwin} // $name->{POSIX} : $name);
425 if (defined $cygwin_name and
426 defined $drive and
427 defined $user) {
428 for my $path (@cygwin_variants) {
429 push @dirs, join('\\', $drive, $path, 'home', $user, $cygwin_name);
430 }
431 }
432 }
433 grep -d $_, @dirs;
434 }
435  
436 sub create_secret_file {
437 my ($any, $name, $data) = @_;
438 $any->_load_module('Win32::SecretFile') or return;
439 my $path = Win32::SecretFile::create_secret_file(File::Spec->join('libnet-ssh-any-perl', $name),
440 $data,
441 local_appdata => 1,
442 short_path => 1,
443 unique => 1);
444 defined $path or
445 $any->_or_set_error(SSHA_LOCAL_IO_ERROR,
446 "Unable to create secret file: $^E [". ($^E+0) . "]");
447 $path;
448 }
449  
450 sub version {
451 my $any = shift;
452 my $v = $win32_get_version->Call();
453 $v & 0x80000000 and croak "This OS is a joke!";
454 my $mayor = $v & 0xff;
455 my $minor = ($v >> 8) & 0xff;
456 my $build = ($v >> 16);
457 wantarray ? ('MSWin', $mayor, $minor, $build) : "MSWin-$mayor.$minor.$build";
458 }
459  
460 # This method is used by Cygwin commands as most of then can not
461 # handle native Windows paths correctly.
462 sub unix_path {
463 my ($any, $path) = @_;
464 return "/dev/null" if $path eq 'nul';
465 my ($drive, @rest) = File::Spec->splitpath(File::Spec->rel2abs($path));
466 $drive =~ s/:$//;
467 s{\\}{/}g for @rest;
468 return "/cygdrive/$drive" . join('/', @rest);
469 }
470  
471 our $debug; # make debug visible below
472 package Net::SSH::Any::OS::MSWin::Process;
473  
474 sub DESTROY {
475 my $proc = shift;
476 if (defined(my $handle = delete $proc->{handle})) {
477 $debug and $debug & 1024 and Net::SSH::Any::Util::_debug("closing process handle $handle");
478 $win32_close_handle->Call($handle);
479 }
480 }
481  
482  
483  
484 1;