blib/lib/Remote/Perl/Client.pm untested

filter: Statementstmt 0.0% 0 / 381 Branchbran 0.0% 0 / 180 Conditioncond 0.0% 0 / 125 MC/DCmcdc 0.0% 0 / 69 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 796 CC 86 SCAR 63.4
CC
86
Cov
0%
_relay
1482.0
_do_run
306.0
_make_tmpfile
110.0
CRAP 566.5
1 use strict;
2 use warnings;
3 # NOTE: this file runs on the remote side and must stay compatible with Perl 5.10+.
4 package Remote::Perl::Client;
5  
6 # Remote bootstrap client. Sent verbatim by Bootstrap.pm and eval'd on the
7 # remote side. Only uses Perl core modules.
8 #
9 # Architecture: one persistent relay process, plus one executor per RUN.
10 # Client (relay) -- owns the protocol pipe; runs the select loop permanently.
11 # Executor -- runs the user script with real STDIN/STDOUT/STDERR pipes.
12 #
13 # This split means the protocol loop is never blocked by script I/O, enabling
14 # real-time stdout/stderr streaming and correct signal forwarding.
15  
16 use Fcntl qw(F_SETFD FD_CLOEXEC O_RDWR);
17 use Socket qw(AF_UNIX SOCK_STREAM);
18 use POSIX qw(WNOHANG);
19  
20 # -- Save real pipe handles before any redirection -----------------------------
21 open(my $PIN, '<&', \*STDIN) or die "dup STDIN: $!\n";
22 open(my $POUT, '>&', \*STDOUT) or die "dup STDOUT: $!\n";
23 binmode($PIN); binmode($POUT);
24 { my $old = select $POUT; $| = 1; select $old }
25 $SIG{PIPE} = 'IGNORE';
26  
27 syswrite($POUT, "REMOTEPERL1\n");
28  
29 # -- Constants -----------------------------------------------------------------
30 use constant {
31 HDR => 6,
32 PROTO_VER => 2,
33 MSG_HELLO => 0x00, MSG_READY => 0x01,
34 MSG_RUN => 0x10,
35 MSG_DATA => 0x20, MSG_EOF => 0x21,
36 MSG_CREDIT => 0x30,
37 MSG_MOD_REQ => 0x40, MSG_MOD_MISSING => 0x41,
38 MSG_RETURN => 0x50,
39 MSG_SIGNAL => 0x60, MSG_SIGNAL_ACK => 0x61,
40 MSG_ERROR => 0xE0, MSG_BYE => 0xF0,
41 S_CTRL => 0, S_STDIN => 1,
42 S_STDOUT => 2, S_STDERR => 3,
43 };
44  
45 # -- State ---------------------------------------------------------------------
46 my $pbuf = '';
47 my %sc = (); # send credits: stream_id => bytes remaining
48 my $window = 65536;
49 my $done = 0;
50 my $next_stream = 4;
51  
52 # -- Wire I/O ------------------------------------------------------------------
53  
54 # Write bytes to the protocol pipe.
55 sub _write {
56 my ($bytes) = @_;
57 my ($total, $off) = (length($bytes), 0);
58 while ($off < $total) {
59 my $n = syswrite($POUT, $bytes, $total - $off, $off);
60 die "syswrite: $!\n" unless defined $n;
61 $off += $n;
62 }
63 }
64  
65 sub _send {
66 my ($type, $stream, $body) = @_;
67 $body //= '';
68 _write(pack('CCN', $type, $stream, length($body)) . $body);
69 }
70  
71 # Write all bytes to an arbitrary filehandle (pipes, sockets).
72 sub _write_fh {
73 my ($fh, $bytes) = @_;
74 my ($total, $off) = (length($bytes), 0);
75 while ($off < $total) {
76 my $n = syswrite($fh, $bytes, $total - $off, $off);
77 die "syswrite fh: $!\n" unless defined $n;
78 $off += $n;
79 }
80 }
81  
82 # Blocking read of exactly $n bytes from $fh. Returns undef on EOF.
83 sub _read_fixed {
84 my ($fh, $n) = @_;
85 my $buf = '';
86 while (length($buf) < $n) {
87 my $got = sysread($fh, my $chunk, $n - length($buf));
88 die "sysread fh: $!\n" unless defined $got;
89 return unless $got;
90 $buf .= $chunk;
91 }
92 return $buf;
93 }
94  
95 # -- Protocol parsing ----------------------------------------------------------
96  
97 sub _pump {
98 my $block = @_ ? $_[0] : 1;
99 my $rin = '';
100 vec($rin, fileno($PIN), 1) = 1;
101 return unless select(my $r = $rin, undef, undef, $block ? undef : 0) > 0;
102 my $n = sysread($PIN, my $data, 65536);
103 die "sysread: $!\n" unless defined $n;
104 unless ($n) { $done = 1; return }
105 $pbuf .= $data;
106 _drain_dispatch();
107 }
108  
109 sub _drain_dispatch {
110 while (length($pbuf) >= HDR) {
111 my ($type, $stream, $len) = unpack('CCN', $pbuf);
112 last if length($pbuf) < HDR + $len;
113 substr($pbuf, 0, HDR, '');
114 my $body = $len ? substr($pbuf, 0, $len, '') : '';
115 _dispatch($type, $stream, $body);
116 }
117 }
118  
119 # -- Pre-fork dispatcher (handshake + waiting for RUN) -------------------------
120 my ($run_flags, $run_source, @run_args);
121  
122 sub _decode_run {
123 my ($body) = @_;
124 my $off = 0;
125 my $flags = unpack('C', substr($body, $off, 1)); $off += 1;
126 my $argc = unpack('N', substr($body, $off, 4)); $off += 4;
127 my @argv;
128 for (1 .. $argc) {
129 my $len = unpack('N', substr($body, $off, 4)); $off += 4;
130 push @argv, substr($body, $off, $len); $off += $len;
131 }
132 return ($flags, substr($body, $off), @argv);
133 }
134  
135 sub _dispatch {
136 my ($type, $stream, $body) = @_;
137 if ($type == MSG_CREDIT) { $sc{$stream} = ($sc{$stream}//0) + unpack('N', $body) }
138 elsif ($type == MSG_RUN) { ($run_flags, $run_source, @run_args) = _decode_run($body) }
139 elsif ($type == MSG_BYE) { $done = 1 }
140 elsif ($type == MSG_ERROR) { warn "remperl error: $body\n"; $done = 1 }
141 }
142  
143 sub _read_raw_message {
144 while (length($pbuf) < HDR) {
145 my $n = sysread($PIN, my $data, 65536);
146 die "sysread: $!\n" unless defined $n;
147 die "EOF waiting for message\n" unless $n;
148 $pbuf .= $data;
149 }
150 my ($type, $stream, $len) = unpack('CCN', $pbuf);
151 while (length($pbuf) < HDR + $len) {
152 my $n = sysread($PIN, my $data, 65536);
153 die "sysread: $!\n" unless defined $n;
154 die "EOF waiting for message body\n" unless $n;
155 $pbuf .= $data;
156 }
157 substr($pbuf, 0, HDR, '');
158 my $body = $len ? substr($pbuf, 0, $len, '') : '';
159 return ($type, $stream, $body);
160 }
161  
162 # -- Handshake -----------------------------------------------------------------
163 {
164 my ($type, undef, $body) = _read_raw_message();
165 die sprintf("Expected HELLO(0x00), got 0x%02x\n", $type) unless $type == MSG_HELLO;
166 die sprintf("Malformed HELLO: expected 5 bytes, got %d\n", length($body))
167 unless length($body) >= 5;
168 my ($ver, $win) = unpack('CN', $body);
169 die "Protocol version mismatch: got $ver, expected " . PROTO_VER . "\n"
170 unless $ver == PROTO_VER;
171 $window = $win;
172 $sc{$_} = $window for S_CTRL, S_STDOUT, S_STDERR;
173 _send(MSG_READY, S_CTRL);
174 }
175  
176 # -- Main loop: handle successive RUN commands on the same connection ----------
177 until ($done) {
178 $run_flags = 0;
179 $run_source = undef;
180 @run_args = ();
181 _pump(1) until defined $run_source || $done;
182 last if $done;
183 eval { _do_run($run_flags, $run_source, @run_args) };
184 if ($@ && !$done) { my $err = $@; eval { _send(MSG_ERROR, S_CTRL, $err) } }
185 }
186 _send(MSG_BYE, S_CTRL);
187  
188 # -- Temp file strategies for do-file execution --------------------------------
189  
190 # Returns ($path, $fh): $path is undef for anon strategies (use /proc/self/fd/N).
191 # $fh must stay alive for the lifetime of the executor (keeps anon inode open;
192 # for NAMED, File::Temp destructor removes the file only on global destruction,
193 # which runs after END blocks).
194 # Resolve an anonymous fd to a filesystem path for do().
195 sub _fd_path {
196 my ($fd) = @_;
197 return "/proc/self/fd/$fd" if -r "/proc/self/fd/$fd";
198 return "/dev/fd/$fd" if -r "/dev/fd/$fd";
199 return;
200 }
201  
202 sub _make_tmpfile {
203 my ($source, $strategy) = @_;
204 if ($strategy == 1 || $strategy == 2) {
205 # Try O_TMPFILE: anonymous inode, never has a directory entry.
206 my $O_TMPFILE = eval { Fcntl::O_TMPFILE() };
207 if (defined $O_TMPFILE) {
208 if (sysopen(my $fh, '/tmp', O_RDWR | $O_TMPFILE)) {
209 my $fdpath = _fd_path(fileno($fh));
210 if (defined $fdpath) {
211 print $fh $source or die "print tmpfile: $!\n";
212 seek $fh, 0, 0 or die "seek tmpfile: $!\n";
213 return ($fdpath, $fh);
214 }
215 }
216 }
217 if ($strategy == 1) { # auto: try perl, then named
218 my @r = eval { _make_tmpfile($source, 3) };
219 return @r if @r;
220 return _make_tmpfile($source, 4);
221 }
222 die "tmpfile strategy 'linux' unavailable on this system\n";
223 }
224 if ($strategy == 3) {
225 open(my $fh, '+>', undef) or die "open anon tmpfile: $!\n";
226 my $fdpath = _fd_path(fileno($fh));
227 if (defined $fdpath) {
228 print $fh $source or die "print tmpfile: $!\n";
229 seek $fh, 0, 0 or die "seek tmpfile: $!\n";
230 return ($fdpath, $fh);
231 }
232 close $fh;
233 die "tmpfile strategy 'perl' unavailable: no /proc/self/fd or /dev/fd\n";
234 }
235 if ($strategy == 4) {
236 require File::Temp;
237 my $fh = File::Temp->new(UNLINK => 1);
238 print $fh $source or die "print tmpfile: $!\n";
239 $fh->flush or die "flush tmpfile: $!\n";
240 return ($fh->filename, $fh);
241 }
242 die "unknown tmpfile strategy: $strategy\n";
243 }
244  
245 # -- Per-run entry point -------------------------------------------------------
246 sub _do_run {
247 my ($flags, $source, @args) = @_;
248  
249 # Check linux tmpfile strategy availability before forking so the error
250 # propagates cleanly via MSG_ERROR instead of becoming a broken exit code.
251 if (($flags & 0x07) == 2) {
252 my $o = eval { Fcntl::O_TMPFILE() };
253 die "tmpfile strategy 'linux' unavailable on this system\n" unless defined $o;
254 }
255  
256 pipe(my $stdin_r, my $stdin_w) or die "pipe stdin: $!\n";
257 pipe(my $stdout_r, my $stdout_w) or die "pipe stdout: $!\n";
258 pipe(my $stderr_r, my $stderr_w) or die "pipe stderr: $!\n";
259 pipe(my $result_r, my $result_w) or die "pipe result: $!\n";
260 socketpair(my $mod_c, my $mod_e, AF_UNIX, SOCK_STREAM, 0)
261 or die "socketpair: $!\n";
262 binmode($_) for $stdin_r, $stdin_w,
263 $stdout_r, $stdout_w,
264 $stderr_r, $stderr_w,
265 $result_r, $result_w,
266 $mod_c, $mod_e;
267  
268 my $exec_pid = fork() // die "fork: $!\n";
269  
270 # Extract warnings bit before using flags for tmpfile strategy.
271 my $do_warnings = $flags & 0x08;
272 $flags &= 0x07;
273  
274 if ($exec_pid == 0) {
275 # === EXECUTOR (child) =================================================
276 close($_) for $stdin_w, $stdout_r, $stderr_r, $result_r, $mod_c;
277  
278 open(STDIN, '<&', $stdin_r) or die "dup stdin: $!\n";
279 open(STDOUT, '>&', $stdout_w) or die "dup stdout: $!\n";
280 open(STDERR, '>&', $stderr_w) or die "dup stderr: $!\n";
281 $| = 1;
282 { my $old = select STDERR; $| = 1; select $old }
283 close($_) for $stdin_r, $stdout_w, $stderr_w;
284  
285 # Mark internal fds close-on-exec so they don't leak into any child
286 # processes spawned by user code.
287 fcntl($result_w, F_SETFD, FD_CLOEXEC);
288 fcntl($mod_e, F_SETFD, FD_CLOEXEC);
289  
290 # Enable warnings if requested (mirrors perl -w).
291 $^W = 1 if $do_warnings;
292  
293 # Install the @INC hook if module serving is enabled.
294 our $REMOTE_PERL_SERVE //= 0;
295  
296 if ($REMOTE_PERL_SERVE) {
297 my $inc_hook = sub {
298 my (undef, $filename) = @_;
299 _write_fh($mod_e, pack('N', length($filename)) . $filename);
300 my $status = _read_fixed($mod_e, 1) // return undef;
301 return undef if unpack('C', $status); # MOD_MISSING
302 my $src_len = unpack('N', _read_fixed($mod_e, 4) // return undef);
303 my $src = _read_fixed($mod_e, $src_len) // return undef;
304 open(my $fh, '<', \$src) or die "scalar open: $!\n";
305 return $fh;
306 };
307 push @INC, $inc_hook;
308 }
309  
310 $SIG{PIPE} = 'DEFAULT';
311 @ARGV = @args;
312  
313 my $eval_err;
314 if ($flags == 0) {
315 # Strip all pragmas we enable (strict, warnings) and reset to
316 # package main so Client.pm's imports are not visible —
317 # matching the clean state of `perl -e`.
318 # When $do_warnings is set, omit `no warnings` so $^W takes effect.
319 if ($do_warnings) {
320 { no strict; package main; eval $source }
321 }
322 else {
323 { no strict; no warnings; package main; eval $source }
324 }
325 $eval_err = $@;
326 }
327 else {
328 my ($dopath, $tmpfh) = _make_tmpfile($source, $flags);
329 # Same pragma stripping as eval mode: do FILE inherits %^H from its
330 # calling scope, so strict/warnings must be cleared here.
331 # Capture $@ inside the block: do FILE sets it for compile errors but
332 # does not throw, so eval BLOCK would otherwise clear it on exit.
333 if ($do_warnings) {
334 { no strict; package main;
335 eval { do $dopath; $eval_err = $@ if $@ };
336 $eval_err //= $@ if $@;
337 }
338 }
339 else {
340 { no strict; no warnings; package main;
341 eval { do $dopath; $eval_err = $@ if $@ };
342 $eval_err //= $@ if $@;
343 }
344 }
345 }
346  
347 # Write die message (if any) and close the result pipe before output
348 # streams, so the relay can read it by the time stdout/stderr reach EOF.
349 if ($eval_err) {
350 _write_fh($result_w, pack('N', length($eval_err)) . $eval_err);
351 }
352 close($result_w);
353 close($mod_e);
354 close(STDOUT);
355 close(STDERR);
356 exit($eval_err ? 255 : 0);
357 }
358  
359 # === CLIENT / RELAY (parent) ==============================================
360 close($_) for $stdin_r, $stdout_w, $stderr_w, $result_w, $mod_e;
361  
362 # Grant stdin credits so the local side may send data.
363 _send(MSG_CREDIT, S_STDIN, pack('N', $window));
364  
365 my $die_msg = _relay($exec_pid, $stdin_w, $stdout_r, $stderr_r, $result_r, $mod_c);
366  
367 waitpid($exec_pid, 0);
368 my $exit_code = ($? & 0x7F) ? 1 : (($? >> 8) & 0xFF);
369 _send(MSG_RETURN, S_CTRL, pack('C', $exit_code) . $die_msg);
370 }
371  
372 # -- Relay loop ----------------------------------------------------------------
373  
374 # Send as much of $$bufref as credits allow on $stream.
375 sub _flush_buf {
376 my ($stream, $bufref) = @_;
377 while (($sc{$stream}//0) > 0 && length($$bufref)) {
378 my $take = ($sc{$stream} < length($$bufref)) ? $sc{$stream} : length($$bufref);
379 _send(MSG_DATA, $stream, substr($$bufref, 0, $take, ''));
380 $sc{$stream} -= $take;
381 }
382 }
383  
384 sub _relay {
385 my ($exec_pid, $stdin_w, $stdout_r, $stderr_r, $result_r, $mod_c) = @_;
386 my ($stdout_eof, $stderr_eof, $stdin_w_closed, $mod_c_eof) = (0, 0, 0, 0);
387 my ($stdout_buf, $stderr_buf) = ('', '');
388  
389 # At most one module request in flight at a time: executor blocks until answered.
390 my ($mod_stream, %mod_src, %mod_fin, %mod_miss);
391  
392 RELAY: until ($stdout_eof && $stderr_eof && !length($stdout_buf) && !length($stderr_buf)) {
393 my $rin = '';
394 vec($rin, fileno($PIN), 1) = 1;
395 vec($rin, fileno($stdout_r), 1) = 1 unless $stdout_eof;
396 vec($rin, fileno($stderr_r), 1) = 1 unless $stderr_eof;
397 # Watch for new module requests only when none is in flight.
398 vec($rin, fileno($mod_c), 1) = 1 unless $mod_c_eof || defined $mod_stream;
399  
400 select(my $r = $rin, undef, undef, undef);
401  
402 # -- Protocol pipe -----------------------------------------------------
403 if (vec($r, fileno($PIN), 1)) {
404 my $n = sysread($PIN, my $data, 65536);
405 die "sysread protocol pipe: $!\n" unless defined $n;
406 unless ($n) { $done = 1; last RELAY }
407 $pbuf .= $data;
408  
409 while (length($pbuf) >= HDR) {
410 my ($type, $stream, $len) = unpack('CCN', $pbuf);
411 last if length($pbuf) < HDR + $len;
412 substr($pbuf, 0, HDR, '');
413 my $body = $len ? substr($pbuf, 0, $len, '') : '';
414  
415 if ($type == MSG_CREDIT) {
416 $sc{$stream} = ($sc{$stream}//0) + unpack('N', $body);
417 _flush_buf(S_STDOUT, \$stdout_buf) if $stream == S_STDOUT;
418 _flush_buf(S_STDERR, \$stderr_buf) if $stream == S_STDERR;
419 }
420 elsif ($type == MSG_DATA && $stream == S_STDIN && !$stdin_w_closed) {
421 my $n = length($body);
422 eval { _write_fh($stdin_w, $body) };
423 if ($@) { close($stdin_w); $stdin_w_closed = 1 }
424 # Re-grant credits for the bytes just delivered so the
425 # local side can send more stdin beyond the initial window.
426 else { _send(MSG_CREDIT, S_STDIN, pack('N', $n)) }
427 }
428 elsif ($type == MSG_EOF && $stream == S_STDIN && !$stdin_w_closed) {
429 close($stdin_w);
430 $stdin_w_closed = 1;
431 }
432 elsif ($type == MSG_SIGNAL) {
433 _send(MSG_SIGNAL_ACK, S_CTRL, $body);
434 kill($body, $exec_pid);
435 }
436 elsif ($type == MSG_ERROR) {
437 warn "remperl error: $body\n";
438 kill('TERM', $exec_pid);
439 $done = 1; last RELAY;
440 }
441 elsif ($type == MSG_BYE) {
442 $done = 1; last RELAY;
443 }
444 # Module response from the local side.
445 elsif (defined $mod_stream && $stream == $mod_stream) {
446 $mod_src{$mod_stream} .= $body if $type == MSG_DATA;
447 $mod_fin{$mod_stream} = 1 if $type == MSG_EOF;
448 $mod_miss{$mod_stream} = 1 if $type == MSG_MOD_MISSING;
449 }
450 }
451  
452 # Forward completed module response to the executor.
453 if (defined $mod_stream
454 && ($mod_fin{$mod_stream} || $mod_miss{$mod_stream})) {
455 if ($mod_fin{$mod_stream}) {
456 my $src = $mod_src{$mod_stream};
457 eval { _write_fh($mod_c, pack('CN', 0, length($src)) . $src) };
458 $mod_c_eof = 1 if $@;
459 } else {
460 eval { _write_fh($mod_c, pack('C', 1)) };
461 $mod_c_eof = 1 if $@;
462 }
463 delete $mod_src{$mod_stream};
464 delete $mod_fin{$mod_stream};
465 delete $mod_miss{$mod_stream};
466 $mod_stream = undef;
467 }
468 }
469  
470 # -- Executor stdout ---------------------------------------------------
471 if (!$stdout_eof && vec($r, fileno($stdout_r), 1)) {
472 my $n = sysread($stdout_r, my $data, 65536);
473 die "sysread stdout: $!\n" unless defined $n;
474 if ($n) {
475 $stdout_buf .= $data;
476 _flush_buf(S_STDOUT, \$stdout_buf);
477 } else {
478 _flush_buf(S_STDOUT, \$stdout_buf);
479 _send(MSG_EOF, S_STDOUT);
480 $stdout_eof = 1;
481 }
482 }
483  
484 # -- Executor stderr ---------------------------------------------------
485 if (!$stderr_eof && vec($r, fileno($stderr_r), 1)) {
486 my $n = sysread($stderr_r, my $data, 65536);
487 die "sysread stderr: $!\n" unless defined $n;
488 if ($n) {
489 $stderr_buf .= $data;
490 _flush_buf(S_STDERR, \$stderr_buf);
491 } else {
492 _flush_buf(S_STDERR, \$stderr_buf);
493 _send(MSG_EOF, S_STDERR);
494 $stderr_eof = 1;
495 }
496 }
497  
498 # -- Module socket: new request from executor --------------------------
499 if (!$mod_c_eof && !defined $mod_stream && vec($r, fileno($mod_c), 1)) {
500 my $hdr = _read_fixed($mod_c, 4);
501 if (!defined $hdr) {
502 $mod_c_eof = 1; # executor closed its end; stop watching
503 }
504 else {
505 my $filename = _read_fixed($mod_c, unpack('N', $hdr)) // do { $mod_c_eof = 1; next };
506 $mod_stream = $next_stream++;
507 $mod_src{$mod_stream} = '';
508 $mod_fin{$mod_stream} = 0;
509 $mod_miss{$mod_stream} = 0;
510 _send(MSG_MOD_REQ, $mod_stream, $filename);
511 }
512 }
513 }
514  
515 # Clean up if the connection died before the run completed.
516 unless ($stdout_eof && $stderr_eof) {
517 kill('TERM', $exec_pid);
518 }
519 close($stdin_w) unless $stdin_w_closed;
520  
521 # Read die message from the result pipe. The executor writes the message
522 # (if any) and closes result_w before closing stdout/stderr, so by the time
523 # we reach here the data is already in the kernel pipe buffer.
524 my $die_msg = '';
525 my $hdr = _read_fixed($result_r, 4);
526 if (defined $hdr) {
527 my $len = unpack('N', $hdr);
528 $die_msg = $len ? (_read_fixed($result_r, $len) // '') : '';
529 }
530  
531 return $die_msg;
532 }
533  
534 1;