1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
|
package Net::FTP::RetrHandle;
our $VERSION = '0.2';
use warnings;
use strict;
use constant DEFAULT_MAX_SKIPSIZE => 1024 * 1024 * 2;
use constant DEFAULT_BLOCKSIZE => 10240; # Net::FTP's default
use base 'IO::Seekable';
# We don't use base 'IO::Handle'; it currently confuses Archive::Zip.
use Carp;
use Scalar::Util;
=head1 NAME
Net::FTP::RetrHandle - Tied or IO::Handle-compatible interface to a file retrieved by FTP
=head1 SYNOPSIS
Provides a file reading interface for reading all or parts of files
located on a remote FTP server, including emulation of C<seek> and
support for downloading only the parts of the file requested.
=head1 DESCRIPTION
Support for skipping the beginning of the file is implemented with the
FTP C<REST> command, which starts a retrieval at any point in the
file. Support for skipping the end of the file is implemented with
the FTP C<ABOR> command, which stops the transfer. With these two
commands and some careful tracking of the current file position, we're
able to reliably emulate a C<seek/read> pair, and get only the parts
of the file that are actually read.
This was originally designed for use with
L<Archive::Zip|Archive::Zip>; it's reliable enough that the table of
contents and individual files can be extracted from a remote ZIP
archive without downloading the whole thing. See L<EXAMPLES> below.
An interface compatible with L<IO::Handle|IO::Handle> is provided,
along with a C<tie>-based interface.
Remember that an FTP server can only do one thing at a time, so make
sure to C<close> your connection before asking the FTP server to do
nything else.
=head1 CONSTRUCTOR
=head2 new ( $ftp, $filename, options... )
Creates a new L<IO::Handle|IO::Handle>-compatible object to fetch all
or parts of C<$filename> using the FTP connection C<$ftp>.
Available options:
=over 4
=item MaxSkipSize => $size
If we need to move forward in a file or close the connection,
sometimes it's faster to just read the bytes we don't need than to
abort the connection and restart. This setting tells how many
unnecessary bytes we're willing to read rather than abort. An
appropriate setting depends on the speed of transferring files and the
speed of reconnecting to the server.
=item BlockSize => $size
When doing buffered reads, how many bytes to read at once. The
default is the same as the default for L<Net::FTP|Net::FTP>, so it's
generally best to leave it alone.
=item AlreadyBinary => $bool
If set to a true value, we assume the server is already in binary
mode, and don't try to set it.
=back
=cut
use constant USAGE => "Usage: Net::FTP::RetrHandle\->new(ftp => \$ftp_obj, filename => \$filename)\n";
sub new
{
my $class = shift;
my $ftp = shift
or croak USAGE;
my $filename = shift
or croak USAGE;
my $self = {
MaxSkipSize => DEFAULT_MAX_SKIPSIZE,
BlockSize => DEFAULT_BLOCKSIZE,
@_,
ftp => $ftp,
filename => $filename,
pos => 0,
nextpos => 0
};
$self->{size} = $self->{ftp}->size($self->{filename})
or return undef;
$self->{ftp}->binary()
unless ( $self->{AlreadyBinary} );
bless $self, $class;
}
=head1 METHODS
Most of the methods implemented behave exactly like those from
L<IO::Handle|IO::Handle>.
These methods are implemented: C<binmode>, C<clearerr>, C<close>, C<eof>,
C<error>, C<getc>, C<getline>, C<getlines>, C<getpos>, C<read>,
C<seek>, C<setpos>, C<sysseek>, C<tell>, C<ungetc>, C<opened>.
=cut ;
sub opened { 1; }
sub seek
{
my $self = shift;
my $pos = shift || 0;
my $whence = shift || 0;
warn " SEEK: self=$self, pos=$pos, whence=$whence\n"
if ( $ENV{DEBUG} );
my $curpos = $self->tell();
my $newpos = _newpos($self->tell(), $self->{size}, $pos, $whence);
my $ret;
if ( $newpos == $curpos ) {
return $curpos;
} elsif ( defined($self->{_buf}) and ($newpos > $curpos) and ($newpos < ($curpos + length($self->{_buf}))) ) {
# Just seeking within the buffer (or not at all)
substr($self->{_buf}, 0, $newpos - $curpos, '');
$ret = $newpos;
} else {
$ret = $self->sysseek($newpos, 0);
$self->{_buf} = '';
}
return $ret;
}
sub _newpos
{
my($curpos, $size, $pos, $whence) = @_;
if ( $whence == 0 ) # seek_set
{
return $pos;
} elsif ( $whence == 1 ) # seek_cur
{
return $curpos + $pos;
} elsif ( $whence == 2 ) # seek_end
{
return $size + $pos;
} else {
die "Invalid value $whence for whence!";
}
}
sub sysseek
{
my $self = shift;
my $pos = shift || 0;
my $whence = shift || 0;
warn "SYSSEEK: self=$self, pos=$pos, whence=$whence\n"
if ( $ENV{DEBUG} );
my $newpos = _newpos($self->{nextpos}, $self->{size}, $pos, $whence);
$self->{eof} = undef;
return $self->{nextpos} = $newpos;
}
sub tell
{
my $self = shift;
return $self->{nextpos} - (defined($self->{_buf}) ? length($self->{_buf}) : 0);
}
# WARNING: ASCII mode probably breaks seek.
sub binmode
{
my $self = shift;
my $mode = shift || ':raw';
return if ( defined($self->{curmode}) && ($self->{curmode} eq $mode) );
if ( defined($mode) and $mode eq ':crlf' ) {
$self->_finish_connection();
$self->{ftp}->ascii()
or return $self->seterr();
} else {
$self->_finish_connection();
$self->{ftp}->binary()
or return $self->seterr();
}
$self->{curmode} = $mode;
}
sub _min
{
return $_[0] < $_[1] ? $_[0] : $_[1];
}
sub _max
{
return $_[0] > $_[1] ? $_[0] : $_[1];
}
sub read
{
my $self = shift;
# return $self->sysread(@_);
my(undef, $len, $offset) = @_;
$offset ||= 0;
warn "READ(buf,$len,$offset)\n"
if ( $ENV{DEBUG} );
if ( !defined($self->{_buf}) || length($self->{_buf}) <= 0 ) {
$self->sysread($self->{_buf}, _max($len, $self->{BlockSize}))
or return 0;
} elsif ( length($self->{_buf}) < $len ) {
$self->sysread($self->{_buf}, _max($len - length($self->{_buf}), $self->{BlockSize}), length($self->{_buf}));
}
my $ret = _min($len, length($self->{_buf}));
if ( !defined($_[0]) ) { $_[0] = '' }
substr($_[0], $offset) = substr($self->{_buf}, 0, $len, '');
$self->{read_count}++;
return $ret;
}
sub sysread
{
my $self = shift;
if ( $self->{eof} ) {
return 0;
}
my(undef, $len, $offset) = @_;
$offset ||= 0;
warn "SYSREAD(buf,$len,$offset)\n"
if ( $ENV{DEBUG} );
if ( $self->{nextpos} >= $self->{size} ) {
$self->{eof} = 1;
$self->{pos} = $self->{nextpos};
return 0;
}
if ( $self->{pos} != $self->{nextpos} ) {
# They seeked.
if ( $self->{ftp_running} ) {
warn "Seek detected, nextpos=$self->{nextpos}, pos=$self->{pos}, MaxSkipSize=$self->{MaxSkipSize}\n"
if ( $ENV{DEBUG} );
if ( $self->{nextpos} > $self->{pos} and ($self->{nextpos} - $self->{pos}) < $self->{MaxSkipSize} ) {
my $br = $self->{nextpos} - $self->{pos};
warn "Reading $br bytes to skip ahead\n"
if ( $ENV{DEBUG} );
my $junkbuff;
while ( $br > 0 ) {
warn "Trying to read $br more bytes\n"
if ( $ENV{DEBUG} );
my $b = $self->{ftp_data}->read($junkbuff, $br);
if ( $b == 0 ) {
$self->_at_eof();
return 0;
} elsif ( !defined($b) || $b < 0 ) {
return $self->seterr();
} else {
$br -= $b;
}
}
$self->{pos} = $self->{nextpos};
} else {
warn "Aborting connection to move to new position\n"
if ( $ENV{DEBUG} );
$self->_finish_connection();
}
}
}
if ( !$self->{ftp_running} ) {
$self->{ftp}->restart($self->{nextpos});
$self->{ftp_data} = $self->{ftp}->retr($self->{filename})
or return $self->seterr();
$self->{ftp_running} = 1;
$self->{pos} = $self->{nextpos};
}
my $tmpbuf;
my $rb = $self->{ftp_data}->read($tmpbuf, $len);
if ( $rb == 0 ) {
$self->_at_eof();
return 0;
} elsif ( !defined($rb) || $rb < 0 ) {
return $self->seterr();
}
if ( !defined($_[0]) ) { $_[0] = '' }
substr($_[0], $offset) = $tmpbuf;
$self->{pos} += $rb;
$self->{nextpos} += $rb;
$self->{sysread_count}++;
$rb;
}
sub _at_eof
{
my $self = shift;
$self->{eof} = 1;
$self->_finish_connection();
# $self->{ftp_data}->_close();
$self->{ftp_running} = $self->{ftp_data} = undef;
}
sub _finish_connection
{
my $self = shift;
warn "_finish_connection\n"
if ( $ENV{DEBUG} );
return unless ( $self->{ftp_running} );
if ( $self->{size} - $self->{pos} < $self->{MaxSkipSize} ) {
warn "Skipping " . ($self->{size} - $self->{pos}) . " bytes\n"
if ( $ENV{DEBUG} );
my $junkbuff;
my $br;
while ( ($br = $self->{ftp_data}->read($junkbuff, 8192)) ) {
# Read until EOF or error
}
defined($br)
or $self->seterr();
}
warn "Shutting down existing FTP DATA session...\n"
if ( $ENV{DEBUG} );
my $closeret;
{
eval { $closeret = $self->{ftp_data}->close(); };
# Work around a timeout bug in Net::FTP
if ( $@ && $@ =~ /^Timeout / ) {
warn "Timeout closing connection, retrying...\n"
if ( $ENV{DEBUG} );
select(undef, undef, undef, 1);
redo;
}
}
$self->{ftp_running} = $self->{ftp_data} = undef;
return $closeret ? 1 : $self->seterr();
}
sub write
{
die "Only reading currently supported";
}
sub close
{
my $self = shift;
return $self->{ftp_data}
? $self->_finish_connection()
: 1;
}
sub eof
{
my $self = shift;
if ( $self->{eof} ) {
return 1;
}
my $c = $self->getc;
if ( !defined($c) ) {
return 1;
}
$self->ungetc(ord($c));
return undef;
}
sub getc
{
my $self = shift;
my $c;
my $rb = $self->read($c, 1);
if ( $rb < 1 ) {
return undef;
}
return $c;
}
sub ungetc
{
my $self = shift;
# Note that $c is the ordinal value of a character, not the
# character itself (for some reason)
my($c) = @_;
$self->{_buf} = chr($c) . $self->{_buf};
}
sub getline
{
my $self = shift;
if ( !defined($/) ) {
my $buf;
while ( $self->read($buf, $self->{BlockSize}, length($buf)) > 0 ) {
# Keep going
}
return $buf;
} elsif ( ref($/) && looks_like_number ${$/} ) {
my $buf;
$self->read($buf, ${$/})
or return undef;
return $buf;
}
my $rs;
if ( $/ eq '' ) {
$rs = "\n\n";
} else {
$rs = $/;
}
my $eol;
if ( !defined($self->{_buf}) ) { $self->{_buf} = '' }
while ( ($eol = index($self->{_buf}, $rs)) < $[ ) {
if ( $self->{eof} ) {
# return what's left
if ( length($self->{_buf}) == 0 ) {
return undef;
} else {
return substr($self->{_buf}, 0, length($self->{_buf}), '');
}
} else {
$self->sysread($self->{_buf}, $self->{BlockSize}, length($self->{_buf}));
}
}
# OK, we should have a match.
my $tmpbuf = substr($self->{_buf}, 0, $eol + length($rs), '');
while ( $/ eq '' and substr($self->{_buf}, 0, 1) eq "\n" ) {
substr($self->{_buf}, 0, 1) = '';
}
return $tmpbuf;
}
sub getlines
{
my $self = shift;
my @lines;
my $line;
while ( defined($line = $self->getline()) ) {
push(@lines, $line);
}
@lines;
}
sub error
{
return undef;
}
sub seterr
{
my $self = shift;
$self->{_error} = 1;
return undef;
}
sub clearerr
{
my $self = shift;
$self->{_error} = undef;
return 0;
}
sub getpos
{
my $self = shift;
return $self->tell();
}
sub setpos
{
my $self = shift;
return $self->seek(@_);
}
sub DESTROY
{
my $self = shift;
if ( UNIVERSAL::isa($self, 'GLOB') ) {
$self = tied *$self
or die "$self not tied?...";
}
if ( $self->{ftp_data} ) {
$self->_finish_connection();
}
warn "sysread called " . $self->{sysread_count} . " times.\n"
if ( $ENV{DEBUG} );
}
=head1 TIED INTERFACE
Instead of a L<IO::Handle|IO::Handle>-compatible interface, you can
use a C<tie>-based interface to use the standard Perl I/O operators.
You can use it like this:
use Net::FTP::RetrHandle;
# Create FTP object in $ftp
# Store filename in $filename
tie *FH, 'Net::FTP::RetrHandle', $ftp, $filename
or die "Error in tie!\n";
=cut
sub TIEHANDLE
{
my $class = shift;
my $obj = $class->new(@_);
$obj;
}
sub READ
{
my $self = shift;
$self->read(@_);
}
sub READLINE
{
my $self = shift;
return wantarray
? $self->getlines(@_)
: $self->getline(@_);
}
sub GETC
{
my $self = shift;
return $self->getc(@_);
}
sub SEEK
{
my $self = shift;
return $self->seek(@_);
}
sub SYSSEEK
{
my $self = shift;
return $self->sysseek(@_);
}
sub TELL
{
my $self = shift;
return $self->tell();
}
sub CLOSE
{
my $self = shift;
return $self->close(@_);
}
sub EOF
{
my $self = shift;
return $self->eof(@_);
}
sub UNTIE
{
tied($_[0])->close(@_);
}
=head1 EXAMPLE
Here's an example of listing a Zip file without downloading the whole
thing:
#!/usr/bin/perl
use warnings;
use strict;
use Net::FTP;
use Net::FTP::AutoReconnect;
use Net::FTP::RetrHandle;
use Archive::Zip;
my $ftp = Net::FTP::AutoReconnect->new("ftp.info-zip.com", Debug => $ENV{DEBUG})
or die "connect error\n";
$ftp->login('anonymous','example@example.com')
or die "login error\n";
$ftp->cwd('/pub/infozip/UNIX/LINUX')
or die "cwd error\n";
my $fh = Net::FTP::RetrHandle->new($ftp,'unz551x-glibc.zip')
or die "Couldn't get handle to remote file\n";
my $zip = Archive::Zip->new($fh)
or die "Couldn't create Zip object\n";
foreach my $fn ($zip->memberNames())
{
print "unz551-glibc.zip: $fn\n";
}
=head1 AUTHOR
Scott Gifford <sgifford@suspectclass.com>
=head1 BUGS
The distinction between tied filehandles and C<IO::Handle>-compatible
filehandles should be blurrier. It seems like other file handle
objects you can freely mix method calls and traditional Perl
operations, but I can't figure out how to do it.
Many FTP servers don't like frequent connection aborts. If that's the
case, try L<Net::FTP::AutoReconnect>, which will hide much of that
from you.
If the filehandle is tied and created with C<gensym>, C<readline>
doesn't work with older versions of Perl. No idea why.
=head1 SEE ALSO
L<Net::FTP>, L<Net::FTP::AutoReconnect>, L<IO::Handle>.
=head1 COPYRIGHT
Copyright (c) 2006 Scott Gifford. All rights reserved. This program
is free software; you can redistribute it and/or modify it under the
same terms as Perl itself.
=cut
1;
|