| 1 | package Win32::PowerShell::IPC; | ||
| 2 | $Win32::PowerShell::IPC::VERSION = '0.02'; | ||
| 3 | use Moo 2; | ||
| 4 | use Win32; | ||
| 5 | use Win32::API; | ||
| 6 | use Win32::Process; | ||
| 7 | use Win32API::File 'FdGetOsFHandle'; | ||
| 8 | use Scalar::Util 'weaken'; | ||
| 9 | use Try::Tiny; | ||
| 10 | use Carp; | ||
| 11 | use Log::Any '$log'; | ||
| 12 | |||
| 13 | # ABSTRACT: Set up IPC between Perl and a PowerShell child process | ||
| 14 | |||
| 15 | |||
| 16 | sub running { defined shift->proc } | ||
| 17 | has cleanup_delay => ( is => 'rw', default => sub { 2000 } ); | ||
| 18 | has exe_options => ( is => 'rw', default => sub { +{ -ExecutionPolicy => 'RemoteSigned' } } ); | ||
| 19 | has exe_cmdline => ( is => 'rw', lazy => 1, builder => 1 ); | ||
| 20 | has exe_path => ( is => 'rw', lazy => 1, builder => 1 ); | ||
| 21 | has proc => ( is => 'rwp' ); | ||
| 22 | |||
| 23 | has stdin => ( is => 'rwp' ); | ||
| 24 | has stdout => ( is => 'rwp' ); | ||
| 25 | has stdout_h => ( is => 'lazy', clearer => 1 ); | ||
| 26 | |||
| 27 | has rbuf => ( is => 'rw', default => sub { '' } ); | ||
| 28 | |||
| 29 | has _command_boundary => ( is => 'rw', default => sub { [] } ); | ||
| 30 | has _command_seq_number => ( is => 'rw', default => sub { 0 } ); | ||
| 31 | |||
| 32 | |||
| 33 | sub _build_exe_path { | ||
| 34 | # Find PowerShell executable in PATH. (CreateProcess ought to do this but doesn't for some reason?) | ||
| 35 | my ($exe)= grep { -f $_ } map { "${_}\\PowerShell.exe" } split /;/, $ENV{PATH}; | ||
| 36 | defined $exe or croak "Can't locate PowerShell.exe in PATH: $ENV{PATH}"; | ||
| 37 | $log->debug("Found PowerShell.exe at $exe") if $log->is_debug; | ||
| 38 | return $exe; | ||
| 39 | } | ||
| 40 | |||
| 41 | sub _build_exe_cmdline { | ||
| 42 | my $self= shift; | ||
| 43 | my %opts= %{ $self->exe_options }; | ||
| 44 | delete $opts{'-Command'}; | ||
| 45 | return join(' ', 'PowerShell.exe', map "$_ $opts{$_}", sort keys %opts).' -Command -'; | ||
| 46 | } | ||
| 47 | |||
| 48 | our %_current_shells; | ||
| 49 | END { | ||
| 50 | my @active= grep { defined } values %_current_shells; | ||
| 51 | $log->debugf("Ending %d leftover powershell processes before global destruction", scalar @active) | ||
| 52 | if @active; | ||
| 53 | $_->terminate_shell for @active; | ||
| 54 | } | ||
| 55 | |||
| 56 | sub start_shell { | ||
| 57 | my $self= shift; | ||
| 58 | if ($self->running) { | ||
| 59 | carp "Subprocess is already running\n"; | ||
| 60 | return; | ||
| 61 | } | ||
| 62 | |||
| 63 | # make sure we have this before mucking around with file handles | ||
| 64 | my $exe= $self->exe_path; | ||
| 65 | my $cmdline= $self->exe_cmdline; | ||
| 66 | $cmdline =~ /-Command -/ or die "Powershell command line must contain '-Command -'"; | ||
| 67 | |||
| 68 | my ($in_r, $in_w, $out_r, $out_w, $save_stdin, $save_stdout, $save_stderr); | ||
| 69 | |||
| 70 | # Create pipes | ||
| 71 | pipe($in_r, $in_w) or die "pipe: $!"; | ||
| 72 | pipe($out_r, $out_w) or die "pipe: $!"; | ||
| 73 | |||
| 74 | # Temporarily overwrite the main handles of this process (dangerous... but | ||
| 75 | # Win32::Process doesn't support the other arguments to CreateProcess | ||
| 76 | # to pass the file handles directly.) | ||
| 77 | my @err; | ||
| 78 | try { | ||
| 79 | open $save_stdin, '<&', \*STDIN or die "Can't save STDIN: $!\n"; | ||
| 80 | open STDIN, '<&', $in_r or die "Can't redirect STDIN: $!\n"; | ||
| 81 | open $save_stdout, '>&', \*STDOUT or die "Can't save STDOUT: $!\n"; | ||
| 82 | open STDOUT, '>&', $out_w or die "Can't redirect STDOUT: $!\n"; | ||
| 83 | open $save_stderr, '>&', \*STDERR or die "Can't save STDERR: $!\n"; | ||
| 84 | open STDERR, '>&', $out_w or die "Can't redirect STDERR: $!\n"; | ||
| 85 | $log->tracef('Launching %s "%s"', $exe, $cmdline); | ||
| 86 | Win32::Process::Create( | ||
| 87 | my $proc, $exe, $cmdline, | ||
| 88 | 1, # inherit handles | ||
| 89 | Win32::Process->NORMAL_PRIORITY_CLASS, | ||
| 90 | '.' # cur dir | ||
| 91 | ) or die "Can't launch PowerShell: ".Win32::FormatMessage(Win32::GetLastError())."\n"; | ||
| 92 | $self->_set_proc($proc); | ||
| 93 | $self->_set_stdin($in_w); | ||
| 94 | $self->_set_stdout($out_r); | ||
| 95 | $self->rbuf(''); | ||
| 96 | @{ $self->_command_boundary }= (); | ||
| 97 | weaken($_current_shells{$self->proc->GetProcessID}= $self); | ||
| 98 | } | ||
| 99 | catch { | ||
| 100 | chomp; | ||
| 101 | push @err, $_; | ||
| 102 | }; | ||
| 103 | # Now restore handles before throwing exception | ||
| 104 | open(STDIN, '<&', $save_stdin) or push(@err, "Can't restore STDIN: $!") | ||
| 105 | if defined $save_stdin; | ||
| 106 | open(STDOUT, '>&', $save_stdout) or push(@err, "Can't restore STDOUT: $!") | ||
| 107 | if defined $save_stdout; | ||
| 108 | open(STDERR, '>&', $save_stderr) or push(@err, "Can't restore STDERR: $!") | ||
| 109 | if defined $save_stderr; | ||
| 110 | croak join("; ", @err) if @err; | ||
| 111 | return 1; | ||
| 112 | } | ||
| 113 | |||
| 114 | # Check if the process has exited, or wait for it to exit, or optionally kill | ||
| 115 | # it if the timeout expires. | ||
| 116 | sub _wait_or_kill { | ||
| 117 | my ($self, $timeout, $kill)= @_; | ||
| 118 | return 1 unless $self->proc; | ||
| 119 | my $exit_code; | ||
| 120 | syswrite($self->stdin, "exit\r\n") if $kill; | ||
| 121 | if ($self->proc->Wait($timeout)) { | ||
| 122 | $self->proc->GetExitCode($exit_code= -1); | ||
| 123 | $log->debug("PowerShell exited with code $exit_code"); | ||
| 124 | } elsif ($kill) { | ||
| 125 | $log->warn("Timeout expired, terminating powershell process ".$self->proc->GetProcessID()); | ||
| 126 | $self->proc->Kill(255); | ||
| 127 | $exit_code= 255; | ||
| 128 | } | ||
| 129 | if (defined $exit_code) { | ||
| 130 | delete $_current_shells{$self->proc->GetProcessID}; | ||
| 131 | $self->_set_proc(undef); | ||
| 132 | $self->_set_stdin(undef); | ||
| 133 | $self->_set_stdout(undef); | ||
| 134 | $self->clear_stdout_h; | ||
| 135 | return 1; | ||
| 136 | } | ||
| 137 | return 0; | ||
| 138 | } | ||
| 139 | |||
| 140 | |||
| 141 | sub terminate_shell { | ||
| 142 | my $self= shift; | ||
| 143 | $self->_wait_or_kill($self->cleanup_delay, 1); | ||
| 144 | } | ||
| 145 | |||
| 146 | sub DESTROY { | ||
| 147 | my $self= shift; | ||
| 148 | $self->terminate_shell if $self->running; | ||
| 149 | } | ||
| 150 | |||
| 151 | |||
| 152 | sub begin_command { | ||
| 153 | my ($self, $command)= @_; | ||
| 154 | $self->start_shell unless $self->running; | ||
| 155 | my $boundary; | ||
| 156 | do { | ||
| 157 | $boundary= sprintf('END_COMMAND_%d_%X_%s', ++$self->{_command_seq_number}, time, rand) | ||
| 158 | } while index($command, $boundary) >= 0; | ||
| 159 | push @{ $self->_command_boundary }, $boundary; | ||
| 160 | $log->debug(qq{ PowerShell: send command $command }) | ||
| 161 | if $log->is_debug && !$log->is_trace; | ||
| 162 | $command =~ s/\r?$/\r\n/; | ||
| 163 | $self->write_all($command); | ||
| 164 | $self->write_all("echo $boundary\r\n"); | ||
| 165 | } | ||
| 166 | |||
| 167 | |||
| 168 | sub collect_command { | ||
| 169 | my ($self)= @_; | ||
| 170 | my $next_boundary= $self->_command_boundary->[0] | ||
| 171 | or croak "No command is pending"; | ||
| 172 | while ($self->{rbuf} !~ /\Q$next_boundary\E\r\n/) { | ||
| 173 | $self->read_more; | ||
| 174 | } | ||
| 175 | $self->{rbuf} =~ s/(.*)\Q$next_boundary\E\r\n//s; | ||
| 176 | my $out= $1; | ||
| 177 | shift @{$self->_command_boundary}; | ||
| 178 | $log->debug(qq{ PowerShell: recv output $out }) | ||
| 179 | if $log->is_debug && !$log->is_trace; | ||
| 180 | return $out; | ||
| 181 | } | ||
| 182 | |||
| 183 | |||
| 184 | sub run_command { | ||
| 185 | my ($self, $command)= @_; | ||
| 186 | $self->begin_command($command); | ||
| 187 | my $ret; | ||
| 188 | $ret= $self->collect_command | ||
| 189 | while @{ $self->_command_boundary }; | ||
| 190 | return $ret; | ||
| 191 | } | ||
| 192 | |||
| 193 | |||
| 194 | sub run_or_die { | ||
| 195 | my ($self, $command)= @_; | ||
| 196 | my $result= $self->run_command($command); | ||
| 197 | croak $result if $result =~ /^\s*\+ FullyQualifiedErrorId\s*:/m; | ||
| 198 | return $result; | ||
| 199 | } | ||
| 200 | |||
| 201 | |||
| 202 | sub write_all { | ||
| 203 | my ($self, $buf)= @_; | ||
| 204 | my $ret; | ||
| 205 | $self->running or croak "Powershell not started"; | ||
| 206 | $self->_wait_or_kill(0, 0) and croak "Powershell exited"; | ||
| 207 | while (length($buf) && (($ret= syswrite($self->stdin, $buf))||0) > 0) { | ||
| 208 | if ($log->is_trace) { | ||
| 209 | my $wrote= substr($buf, 0, $ret); | ||
| 210 | $wrote =~ s/([\0-\x1F\x7F])/sprintf("\\x%02X",ord($1))/eg; | ||
| 211 | $log->trace(qq{ PowerShell: wrote input "$wrote"}); | ||
| 212 | } | ||
| 213 | substr($buf, 0, $ret)= ''; | ||
| 214 | } | ||
| 215 | croak "syswrite: $!" unless defined $ret; | ||
| 216 | return $ret > 0; | ||
| 217 | } | ||
| 218 | |||
| 219 | |||
| 220 | sub read_more { | ||
| 221 | my $self= shift; | ||
| 222 | $self->_wait_or_kill(0, 0) and croak "Powershell exited"; | ||
| 223 | my $ret= sysread($self->stdout, my $buf, 4096); | ||
| 224 | defined $ret or croak "sysread: $!"; | ||
| 225 | if ($log->is_trace) { | ||
| 226 | my $recvd= $buf; | ||
| 227 | $recvd =~ s/([\0-\x1F\x7F])/sprintf("\\x%02X",ord($1))/eg; | ||
| 228 | $log->trace(qq{ PowerShell: recv output "$recvd"}); | ||
| 229 | } | ||
| 230 | $self->{rbuf} .= $buf; | ||
| 231 | return $ret; | ||
| 232 | } | ||
| 233 | |||
| 234 | |||
| 235 | sub _build_stdout_h { | ||
| 236 | my $self= shift; | ||
| 237 | my $out= $self->stdout or croak "Stdout not open"; | ||
| 238 | return FdGetOsFHandle(fileno($out)); | ||
| 239 | } | ||
| 240 | |||
| 241 | sub stdout_readable { | ||
| 242 | my $self= shift; | ||
| 243 | my $n; | ||
| 244 | return PeekNamedPipe($self->stdout_h, my $buf, 0, my $got, $n) && $n > 0; | ||
| 245 | } | ||
| 246 | |||
| 247 | my $peek_named_pipe; | ||
| 248 | sub PeekNamedPipe { | ||
| 249 | my ($wh, $buf, $buflen, $got, $avail, $remain)= @_; | ||
| 250 | $peek_named_pipe ||= Win32::API->new("kernel32", 'PeekNamedPipe', 'NPIPPP', 'N') | ||
| 251 | || die "Can't load PeekNamedPipe from kernel32.dll"; | ||
| 252 | # hNamedPipe - Windows Handle (integer) | ||
| 253 | # lpBuffer - Destination buffer where bytes will be written. NULL if not needed. | ||
| 254 | # nBufferSize - size of buffer. | ||
| 255 | # lpBytesRead - destination DWORD of number of bytes stored in buffer. NULL if not needed. | ||
| 256 | # lpTotalBytesAvail - destination DWORD of number of bytes available. NULL if not needed. | ||
| 257 | # lpBytesLeftThisMessage - (not relevant for named or anonymous pipes) NULL if not needed. | ||
| 258 | |||
| 259 | # use actual length of buffer if buflen was not specified | ||
| 260 | $buflen= length($buf) if defined $buf and !defined $buflen; | ||
| 261 | # if buffer length specified and buffer was not, make buffer that long | ||
| 262 | $buf= "\0" x $buflen if defined $buflen and (!defined $buf or length($buf) < $buflen); | ||
| 263 | $got= pack('L', 0); | ||
| 264 | $avail= pack('L', 0); | ||
| 265 | $remain= pack('L', 0); | ||
| 266 | my $ret= $peek_named_pipe->Call($wh, $buf, $buflen, $got, $avail, $remain); | ||
| 267 | # Only overwrite the "out" arguments if the call succeeded | ||
| 268 | if ($ret) { | ||
| 269 | $got= unpack('L', $got); | ||
| 270 | $_[1]= substr($buf, 0, $got > 0? $got : 0) if defined $_[1]; | ||
| 271 | $_[3]= $got if @_ > 3; | ||
| 272 | $_[4]= unpack('L', $avail) if @_ > 4; | ||
| 273 | $_[5]= unpack('L', $remain) if @_ > 5; | ||
| 274 | } | ||
| 275 | return $ret; | ||
| 276 | } | ||
| 277 | |||
| 278 | |||
| 279 | 1; | ||
| 280 | |||
| 281 | __END__ |