| 1 | package Net::SSH::Perl::Handle::SSH2; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | use Net::SSH::Perl::Buffer; | ||
| 6 | use Net::SSH::Perl::Constants qw( :channels ); | ||
| 7 | |||
| 8 | use constant CHUNK_SIZE => 32000; | ||
| 9 | |||
| 10 | use Tie::Handle; | ||
| 11 | use base qw( Tie::Handle ); | ||
| 12 | |||
| 13 | sub TIEHANDLE { | ||
| 14 | my $class = shift; | ||
| 15 | my($mode, $channel, $r_exit) = @_; | ||
| 16 | my $read = $mode =~ /^[rR]/; | ||
| 17 | my $handle = bless { channel => $channel, exit => $r_exit }, $class; | ||
| 18 | if ($read) { | ||
| 19 | my $incoming = $handle->{incoming} = Net::SSH::Perl::Buffer->new( MP => 'SSH2' ); | ||
| 20 | $channel->register_handler("_output_buffer", sub { | ||
| 21 | my($channel, $buffer) = @_; | ||
| 22 | $incoming->append($buffer->bytes); | ||
| 23 | $channel->{ssh}->break_client_loop; | ||
| 24 | }); | ||
| 25 | } | ||
| 26 | $handle; | ||
| 27 | } | ||
| 28 | |||
| 29 | sub READ { | ||
| 30 | my $h = shift; | ||
| 31 | my $buf = $h->{incoming}; | ||
| 32 | while (!$buf->length) { | ||
| 33 | $h->{channel}{ssh}->client_loop; | ||
| 34 | $_[0] = undef, return 0 unless $buf->length; | ||
| 35 | } | ||
| 36 | $_[0] = $buf->bytes; | ||
| 37 | $buf->empty; | ||
| 38 | length($_[0]); | ||
| 39 | } | ||
| 40 | |||
| 41 | sub WRITE { | ||
| 42 | my $h = shift; | ||
| 43 | my($data) = @_; | ||
| 44 | my $len = length($data); | ||
| 45 | while ($data) { | ||
| 46 | my $chunk = substr($data, 0, CHUNK_SIZE, ''); | ||
| 47 | return undef if $h->{channel}{istate} != CHAN_INPUT_OPEN; | ||
| 48 | $h->{channel}->send_data($chunk); | ||
| 49 | } | ||
| 50 | $len; | ||
| 51 | } | ||
| 52 | |||
| 53 | sub EOF { defined ${$_[0]->{exit}} ? 1 : 0 } | ||
| 54 | |||
| 55 | sub CLOSE { | ||
| 56 | my $h = shift; | ||
| 57 | unless ($h->{incoming}) { | ||
| 58 | my $c = $h->{channel}; | ||
| 59 | my $ssh = $c->{ssh}; | ||
| 60 | $c->drain_outgoing; | ||
| 61 | $c->{istate} = CHAN_INPUT_WAIT_DRAIN; | ||
| 62 | $c->send_eof; | ||
| 63 | $c->{istate} = CHAN_INPUT_CLOSED; | ||
| 64 | $ssh->client_loop; | ||
| 65 | } | ||
| 66 | 1; | ||
| 67 | } | ||
| 68 | |||
| 69 | #sub DESTROY { | ||
| 70 | # my $h = shift; | ||
| 71 | # $h->CLOSE; | ||
| 72 | #} | ||
| 73 | |||
| 74 | 1; |