1 #============================================================= -*-perl-*-
3 # BackupPC::Xfer::Ftp package
7 # This library defines a BackupPC::Xfer::Ftp class for transferring
8 # data from a FTP client.
11 # Paul Mantz <pcmantz@zmanda.com>
14 # (C) 2008, Zmanda Inc.
16 # This program is free software; you can redistribute it and/or
17 # modify it under the terms of the GNU General Public License as
18 # published by the Free Software Foundation; either version 2 of the
19 # License, or (at your option) any later version.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 # General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
32 #========================================================================
34 # Unreleased, planned release in 3.2 (or 3.1.1)
36 # See http://backuppc.sourceforge.net.
38 #========================================================================
41 package BackupPC::Xfer::Ftp;
46 use BackupPC::Attrib qw(:all);
48 use Encode qw/from_to encode/;
49 use File::Listing qw/parse_dir/;
52 use base qw(BackupPC::Xfer::Protocol);
54 use vars qw( $FTPLibOK $FTPLibErr $ARCLibOK );
56 use constant S_IFMT => 0170000;
64 # clear eval error variable
66 my @FTPLibs = qw( Net::FTP Net::FTP::RetrHandle );
68 foreach my $module ( @FTPLibs ) {
75 $FTPLibErr = "module $module doesn't exist: $@";
80 eval "use Net::FTP::AutoReconnect;";
81 $ARCLibOK = (defined($@)) ? 1 : 0;
84 ##############################################################################
86 ##############################################################################
91 # $xfer = new BackupPC::Xfer::Ftp( $bpc, %args );
93 # new() is your default class constructor. it also calls the
94 # constructor for Protocol as well.
98 my ( $class, $bpc, $args ) = @_;
101 my $t = BackupPC::Xfer::Protocol->new(
111 ExistFileCompSize => 0,
115 return bless( $t, $class );
119 ##############################################################################
121 ##############################################################################
127 # start() is called to configure and initiate a dump or restore,
128 # depending on the configured options.
135 my $conf = $t->{conf};
137 my ( @fileList, $logMsg, $incrDate, $args, $dumpText );
140 # initialize the statistics returned by getStats()
142 foreach ( qw/byteCnt fileCnt xferErrCnt xferBadShareCnt
143 xferBadFileCnt xferOK hostAbort hostError
150 # Net::FTP::RetrHandle is necessary.
153 $t->{_errStr} = "Error: FTP transfer selected but module"
154 . " Net::FTP::RetrHandle is not installed.";
160 # standardize the file include/exclude settings if necessary
162 unless ( $t->{type} eq 'restore' ) {
163 $bpc->backupFileConfFix( $conf, "FtpShareName" );
164 $t->loadInclExclRegexps("FtpShareName");
168 # Convert the encoding type of the names if at all possible
170 from_to( $args->{shareName}, "utf8", $conf->{ClientCharset} )
171 if ( $conf->{ClientCharset} ne "" );
174 # Collect FTP configuration arguments and translate them for
175 # passing to the FTP module.
177 unless ( $args = $t->getFTPArgs() ) {
182 # Create the Net::FTP::AutoReconnect or Net::FTP object.
186 $t->{ftp} = ($ARCLibOK) ? Net::FTP::AutoReconnect->new(%$args)
187 : Net::FTP->new(%$args);
190 $t->{_errStr} = "Can't open connection to $args->{Host}: $!";
196 # Log in to the ftp server and set appropriate path information.
199 eval { $t->{ftp}->login( $conf->{FtpUserName}, $conf->{FtpPasswd} ); };
201 $t->{_errStr} = "Can't login to $args->{Host}: $!";
207 eval { $t->{ftp}->binary(); };
210 "Can't enable binary transfer mode to $args->{Host}: $!";
216 eval { $t->{shareName} =~ m/^\.?$/ || $t->{ftp}->cwd( $t->{shareName} ); };
219 "Can't change working directory to $t->{shareName}: $!";
225 eval { $t->{sharePath} = $t->{ftp}->pwd(); };
228 "Can't retrieve full working directory of $t->{shareName}: $!";
234 # log the beginning of action based on type
236 if ( $t->{type} eq 'restore' ) {
237 $logMsg = "restore started on directory $t->{shareName}";
239 } elsif ( $t->{type} eq 'full' ) {
240 $logMsg = "full backup started on directory $t->{shareName}";
242 } elsif ( $t->{type} eq 'incr' ) {
244 $incrDate = $bpc->timeStamp( $t->{incrBaseTime} - 3600, 1 );
245 $logMsg = "incremental backup started back to $incrDate" .
246 " (backup #$t->{incrBaseBkupNum}) for directory" . "
251 # call the recursive function based on the type of action
253 if ( $t->{type} eq 'restore' ) {
256 $logMsg = "Restore of $args->{Host} complete";
258 } elsif ( $t->{type} eq 'incr' ) {
261 $logMsg = "Incremental backup of $args->{Host} complete";
263 } elsif ( $t->{type} eq 'full' ) {
266 $logMsg = "Full backup of $args->{Host} complete";
269 delete $t->{_errStr};
280 my $stats = $t->{stats};
282 my ( $tarErrs, $nFilesExist, $sizeExist,
283 $sizeExistCom, $nFilesTotal, $sizeTotal );
286 # TODO: replace the $stats array with variables at the top level,
287 # ones returned by $getStats. They should be identical.
290 $nFilesExist = $stats->{ExistFileCnt};
291 $sizeExist = $stats->{ExistFileSize};
292 $sizeExistCom = $stats->{ExistFileCompSize};
293 $nFilesTotal = $stats->{TotalFileCnt};
294 $sizeTotal = $stats->{TotalFileSize};
296 if ( $t->{type} eq "restore" ) {
297 return ( $t->{fileCnt}, $t->{byteCnt}, 0, 0 );
300 return \( $tarErrs, $nFilesExist, $sizeExist,
301 $sizeExistCom, $nFilesTotal, $sizeTotal );
310 # TODO: finish or scuttle this function. It is not necessary for a
318 my $fileList = $t->{fileList};
320 my ($path, $fileName, $fileAttr, $fileType );
322 #print STDERR "BackupPC::Xfer::Ftp->restore()";
325 # Prepare the view object
327 $t->{view} = BackupPC::View->new( $bpc, $t->{bkupSrcHost},
329 my $view = $t->{view};
331 SCAN: foreach my $f ( @$fileList ) {
333 #print STDERR "restoring $f...\n";
335 $f =~ /(.*)\/([^\/]*)/;
339 $view->dirCache($path);
341 $fileAttr = $view->fileAttrib($fileName);
342 $fileType = fileType2Text( $fileAttr->{type} );
344 if ( $fileType eq "dir") {
345 $t->restoreDir($fileName, $fileAttr);
347 } elsif ( $fileType eq "file" ) {
348 $t->restoreFile($fileName, $fileAttr);
350 } elsif ( $fileType eq "symlink" ) {
365 my ( $t, $dirName, $dirAttr ) = @_;
369 my $conf = $t->{conf};
370 my $view = $t->{view};
371 my $TopDir = $bpc->TopDir();
373 my $path = "$dirAttr->{relPath}/$dirName";
374 my $dirList = $view->dirAttrib( -1, $t->{shareName}, $path );
376 my ( $fileName, $fileAttr, $fileType );
378 #print STDERR "BackupPC::Xfer::Ftp->restore($dirName)\n";
381 # Create the remote directory
384 eval { $ftp->mkdir( $path, 1 ); };
386 $t->logFileAction( "fail", $dirName, $dirAttr );
390 SCAN: while ( ($fileName, $fileAttr ) = each %$dirList ) {
392 $fileType = fileType2Text( $fileAttr->{type} );
394 if ( $fileType eq "dir" ) {
395 if ( $t->restoreDir( $fileName, $fileAttr ) ) {
396 $t->logWrite( "restored: $path/$fileName\n", 5 );
398 $t->logWrite( "restore failed: $path/$fileName\n", 3 );
401 } elsif ( $fileType eq "file" ) {
402 $t->restoreFile( $fileName, $fileAttr );
404 } elsif ( $fileType eq "hardlink" ) {
406 # Hardlinks cannot be restored. however, if we have the
407 # target file in the pool, we can restore that.
409 $t->restoreFile( $fileName, $fileAttr );
413 } elsif ( $fileType eq "symlink" ) {
415 # Symlinks cannot be restored
421 # Ignore all other types (devices, doors, etc)
431 my ($t, $fileName, $fileAttr ) = @_;
433 my $conf = $t->{conf};
436 my $poolFile = $fileAttr->{fullPath};
437 my $fileDest = ( $conf->{ClientCharset} ne "" )
438 ? from_to( "$fileAttr->{relPath}/$fileName",
439 "utf8", $conf->{ClientCharset} )
440 : "$fileAttr->{relPath}/$fileName";
442 #print STDERR "BackupPC::Xfer::Ftp->restoreFile($fileName)\n";
446 if ( $ftp->put( $poolFile, $fileDest ) ) {
447 $t->logFileAction( "restore", $fileName, $fileAttr );
449 $t->logFileAction( "fail", $fileName, $fileAttr );
453 $t->logFileAction( "fail", $fileName, $fileAttr );
462 # $t->backup() is a recursive function that takes a path as an
463 # argument, and performs a backup on that folder consistent with the
464 # configuration parameters. $path is considered rooted at
465 # $t->{shareName}, so no $ftp->cwd() command is necessary.
473 my $conf = $t->{conf};
474 my $TopDir = $bpc->TopDir();
475 my $OutDir = "$TopDir/pc/$t->{client}/new/"
476 . $bpc->fileNameEltMangle( $t->{shareName} );
479 # Prepare the view object
481 $t->{view} = BackupPC::View->new( $bpc, $t->{client}, $t->{backups} );
484 # Prepare backup folder
486 unless ( eval { mkpath( $OutDir, 0, 0755 ); } ) {
487 $t->{_errStr} = "can't create OutDir: $OutDir";
493 # determine the filetype of the shareName and back it up
494 # appropriately. For now, assume that $t->{shareName} is a
499 fullName => $t->{shareName},
502 if ( $t->handleDir( $f, $OutDir ) ) {
509 $t->{xferBadShareCnt}++;
515 ####################################################################################
516 # FTP-specific functions
517 ####################################################################################
521 # This is an encapulation of the logic necessary to grab the arguments
522 # from %Conf and throw it in a hash pointer to be passed to the
528 my $conf = $t->{conf};
531 Host => $conf->{ClientNameAlias}
534 Firewall => undef, # not used
535 FirewallType => undef, # not used
536 BlockSize => $conf->{FtpBlockSize} || 10240,
537 Port => $conf->{FtpPort} || 21,
538 Timeout => $conf->{FtpTimeout} || 120,
539 Debug => 0, # do not touch
540 Passive => 1, # do not touch
541 Hash => undef, # do not touch
542 LocalAddr => "localhost", # do not touch
549 # $dirList = $t->remotels($path);
551 # remotels() returns a reference to a list of hash references that
552 # describe the contents of each file in the directory of the path
555 # In the future, I would like to make this function return objects in
556 # Attrib format. That would be very optimal, and I could probably
557 # release the code to CPAN.
561 my ( $t, $path ) = @_;
565 my $conf = $t->{conf};
567 my ( $dirContents, $remoteDir, $f );
571 $dirContents = ( $path =~ /^\.?$/ ) ? $ftp->dir()
572 : $ftp->dir("$path/");
576 return "can't retrieve remote directory contents of $path: $!";
579 foreach my $info ( @{parse_dir($dirContents)} ) {
589 $f->{utf8name} = $f->{name};
590 from_to( $f->{utf8name}, $conf->{ClientCharset}, "utf8" );
592 $f->{fullName} = "$t->{sharePath}/$path/$f->{name}";
593 $f->{fullName} =~ s/\/+/\//g;
595 $f->{relPath} = ($path eq "") ? $f->{name} : "$path/$f->{name}";
596 $f->{relPath} =~ s/\/+/\//g;
598 push( @$remoteDir, $f );
605 # ignoreFileCheck() looks at the attributes of the arguments and the
606 # backup types, and determines if the file should be skipped in this
611 my ( $t, $f, $attrib ) = @_;
613 if ( $f->{name} =~ /^\.\.?$/ ) {
617 return ( !$t->checkIncludeExclude( $f->{fullName} ) );
622 # handleSymlink() backs up a symlink.
626 my ( $t, $f, $OutDir, $attrib ) = @_;
628 my $conf = $t->{conf};
630 my ( $target, $targetDesc );
633 type => BPC_FTYPE_SYMLINK,
635 uid => undef, # unsupported
636 gid => undef, # unsupported
638 mtime => $f->{mtime},
642 # If we are following symlinks, back them up as the type of file
643 # they point to. Otherwise, backup the symlink.
645 if ( $conf->{FtpFollowSymlinks} ) {
648 # handle nested symlinks by recurring on the target until a
649 # file or directory is found.
651 $f->{type} =~ /^l (.*)/;
656 if ( $targetDesc = $ftp->dir("$target/") ) {
657 $t->handleSymDir( $f, $OutDir, $attrib, $targetDesc );
659 } elsif ( $targetDesc = $ftp->dir($target) ) {
660 if ( $targetDesc->[4] eq 'file' ) {
661 $t->handleSymFile( $f, $OutDir, $attrib );
663 } elsif ( $targetDesc->[4] =~ /l (.*)/ ) {
664 $t->logFileAction( "fail", $f->{utf8name}, $attribInfo );
673 $t->logFileAction( "fail", $f->{utf8name}, $attribInfo );
679 # If we are not following symlinks, record them normally.
681 $attrib->set( $f->{utf8name}, $attribInfo );
682 $t->logFileAction("create", $f->{utf8name}, $attribInfo);
690 my ($t, $fSym, $OutDir, $attrib, $targetDesc) = @_;
698 my ( $t, $fSym, $OutDir, $attrib, $targetDesc ) = @_;
701 my $conf = $t->{conf};
704 name => $fSym->{name},
705 type => $targetDesc->[1],
706 size => $targetDesc->[2],
707 mtime => $targetDesc->[3],
708 mode => $targetDesc->[4]
711 $f->{utf8name} = $fSym->{name};
712 from_to( $f->{utf8name}, $conf->{ClientCharset}, "utf8" );
714 $f->{relPath} = $fSym->{relPath};
715 $f->{fullName} = "$t->{shareName}/$fSym->{relPath}/$fSym->{name}";
716 $f->{fullName} =~ s/\/+/\//g;
719 # since FTP servers follow symlinks, we can just do this:
721 return $t->handleFile( $f, $OutDir, $attrib );
726 # handleDir() backs up a directory, and initiates a backup of its
731 my ( $t, $dir, $OutDir ) = @_;
735 my $conf = $t->{conf};
736 my $view = $t->{view};
737 my $stats = $t->{stats};
739 my ( $exists, $digest, $outSize, $errs );
740 my ( $poolWrite, $poolFile, $attribInfo );
741 my ( $localDir, $remoteDir, $attrib, %expectedFiles );
743 if ( exists($dir->{utf8name})) {
744 $OutDir .= "/" . $bpc->fileNameMangle( $dir->{utf8name} );
747 unless ( -d $OutDir ) {
749 eval { mkpath( $OutDir, 0, 0755 ) };
751 $t->logFileAction( "fail", $dir->{utf8name}, $dir );
754 $t->logFileAction( "create", $dir->{utf8name}, $dir );
758 $attrib = BackupPC::Attrib->new( { compress => $t->{Compress} } );
759 $remoteDir = $t->remotels( $dir->{relPath} );
761 if ( $t->{type} eq "incr" ) {
762 $localDir = $view->dirAttrib( $t->{incrBaseBkupNum},
763 $t->{shareName}, $dir->{relPath} );
764 %expectedFiles = map { $_ => 0 } sort keys %$localDir
768 # take care of each file in the directory
770 SCAN: foreach my $f ( @{$remoteDir} ) {
772 next SCAN if $t->ignoreFileCheck( $f, $attrib );
775 # handle based on filetype
777 if ( $f->{type} eq 'f' ) {
778 $t->handleFile( $f, $OutDir, $attrib );
780 } elsif ( $f->{type} eq 'd' ) {
783 type => BPC_FTYPE_DIR,
785 uid => undef, # unsupported
786 gid => undef, # unsupported
788 mtime => $f->{mtime},
791 #print STDERR "$f->{utf8name}: ". Dumper($attribInfo);
793 if ( $t->handleDir($f, $OutDir) ) {
794 $attrib->set( $f->{utf8name}, $attribInfo);
797 } elsif ( $f->{type} =~ /^l (.*)/ ) {
798 $t->handleSymlink( $f, $OutDir, $attrib );
807 # Mark file as seen in expected files hash
809 $expectedFiles{ $f->{utf8name} }++ if ( $t->{type} eq "incr" );
811 } # end foreach (@{$remoteDir})
814 # If the backup type is incremental, mark the files that are not
815 # present on the server as deleted.
817 if ( $t->{type} eq "incr" ) {
818 while ( my ($f, $seen) = each %expectedFiles ) {
819 $attrib->set( $f, { type => BPC_FTYPE_DELETED } )
825 # print the directory attributes, now that the directory is done.
827 my $fileName = $attrib->fileName($OutDir);
828 my $data = $attrib->writeData();
830 $poolWrite = BackupPC::PoolWrite->new( $bpc, $fileName, length($data),
832 $poolWrite->write( \$data );
833 ( $exists, $digest, $outSize, $errs ) = $poolWrite->close();
843 # handleFile() backs up a file.
847 my ( $t, $f, $OutDir, $attrib ) = @_;
851 my $view = $t->{view};
852 my $stats = $t->{stats};
853 my $newFilesFH = $t->{newFilesFH};
855 my ( $poolFile, $poolWrite, $data, $localSize );
856 my ( $exists, $digest, $outSize, $errs );
861 # If this is an incremental backup and the file exists in a
862 # previous backup unchanged, write the attribInfo for the file
865 if ( $t->{type} eq "incr" ) {
866 return 1 if $t->incrFileExistCheck( $f, $attrib );
870 type => BPC_FTYPE_FILE,
872 uid => undef, # unsupported
873 gid => undef, # unsupported
875 mtime => $f->{mtime},
879 # If this is a full backup or the file has changed on the host,
883 eval { tie ( *FTP, 'Net::FTP::RetrHandle', $ftp, $f->{fullName} ); };
885 $t->handleFileAction( "fail", $attribInfo );
886 $t->{xferBadFileCnt}++;
891 $poolFile = $OutDir . "/" . $bpc->fileNameMangle( $f->{name} );
892 $poolWrite = BackupPC::PoolWrite->new( $bpc, $poolFile, $f->{size},
893 $bpc->{xfer}{compress} );
900 $localSize += length($_);
901 $poolWrite->write( \$_ );
904 ( $exists, $digest, $outSize, $errs ) = $poolWrite->close();
905 if ( !*FTP || $@ || @$errs ) {
907 $t->logFileAction( "fail", $f->{utf8name}, $attribInfo );
909 $t->{xferBadFileCnt}++;
910 $stats->{errCnt} += scalar @$errs;
915 # this should never happen
917 if ( $localSize != $f->{size} ) {
918 $t->logFileAction( "fail", $f->{utf8name}, $attribInfo );
920 $stats->{xferBadFileCnt}++;
928 $attrib->set( $f->{utf8name}, $attribInfo );
929 $t->logFileAction( $exists ? "pool" : "create",
930 $f->{utf8name}, $attribInfo );
931 print $newFilesFH "$digest $f->{size} $poolFile\n" unless $exists;
936 $stats->{TotalFileCnt}++;
937 $stats->{ExistFileCnt}++;
938 $stats->{ExistFileCompSize} += -s $poolFile;
939 $stats->{ExistFileSize} += $f->{size};
940 $stats->{TotalFileSize} += $f->{size};
942 $t->{byteCnt} += $localSize;
948 # this function checks if the file has been modified on disk, and if
949 # it has, returns. Otherwise, it updates the attrib values.
951 sub incrFileExistCheck
953 my ($t, $f, $attrib) = @_;
955 my $view = $t->{view};
957 my $oldAttribInfo = $view->fileAttrib( $t->{incrBaseBkupNum},
958 $t->{shareName}, $f->{relPath} );
960 #print STDERR "*" x 50 . "\n";
961 #print STDERR "Old data:\n" . Dumper($oldAttribInfo);
962 #print STDERR "New data:\n" . Dumper($f);
963 #print STDERR "$f->{fullName}: $oldAttribInfo->{mtime} ?= $f->{mtime}, $oldAttribInfo->{size} ?= $f->{size}\n";
965 return ( $oldAttribInfo->{mtime} == $f->{mtime}
966 && $oldAttribInfo->{size} == $f->{size} );
971 # Generate a log file message for a completed file. Taken from
972 # BackupPC_tarExtract. $f should be an attrib object.
976 my ( $t, $action, $name, $attrib ) = @_;
978 my $owner = "$attrib->{uid}/$attrib->{gid}";
980 ( ( "", "p", "c", "", "d", "", "b", "", "", "", "l", "", "s" ) )
981 [ ( $attrib->{mode} & S_IFMT ) >> 12 ];
983 $name = "." if ( $name eq "" );
984 $owner = "-/-" if ( $owner eq "/" );
986 my $fileAction = sprintf( " %-6s %1s%4o %9s %11.0f %s\n",
987 $action, $type, $attrib->{mode} & 07777,
988 $owner, $attrib->{size}, $name );
990 return $t->logWrite( $fileAction, 1 );