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 = "ftp restore for host $t->{host} started on directory "
238 . "$t->{shareName}\n";
240 } elsif ( $t->{type} eq 'full' ) {
241 $logMsg = "ftp full backup for host $t->{host} started on directory "
242 . "$t->{shareName}\n";
244 } elsif ( $t->{type} eq 'incr' ) {
245 $incrDate = $bpc->timeStamp( $t->{incrBaseTime} - 3600, 1 );
246 $logMsg = "ftp incremental backup for $t->{host} started back to "
247 . "$incrDate (backup #$t->{incrBaseBkupNum}) for directory "
248 . "$t->{shareName}\n";
250 $t->logWrite($logMsg, 1);
253 # call the recursive function based on the type of action
255 if ( $t->{type} eq 'restore' ) {
258 $logMsg = "Restore of $t->{host} complete";
260 } elsif ( $t->{type} eq 'incr' ) {
263 $logMsg = "Incremental backup of $t->{host} complete";
265 } elsif ( $t->{type} eq 'full' ) {
268 $logMsg = "Full backup of $t->{host} complete";
271 delete $t->{_errStr};
282 my $stats = $t->{stats};
284 my ( $tarErrs, $nFilesExist, $sizeExist,
285 $sizeExistCom, $nFilesTotal, $sizeTotal );
288 # TODO: replace the $stats array with variables at the top level,
289 # ones returned by $getStats. They should be identical.
292 $nFilesExist = $stats->{ExistFileCnt};
293 $sizeExist = $stats->{ExistFileSize};
294 $sizeExistCom = $stats->{ExistFileCompSize};
295 $nFilesTotal = $stats->{TotalFileCnt};
296 $sizeTotal = $stats->{TotalFileSize};
298 if ( $t->{type} eq "restore" ) {
299 return ( $t->{fileCnt}, $t->{byteCnt}, 0, 0 );
302 return ( $tarErrs, $nFilesExist, $sizeExist,
303 $sizeExistCom, $nFilesTotal, $sizeTotal );
312 # TODO: finish or scuttle this function. It is not necessary for a
320 my $fileList = $t->{fileList};
322 my ($path, $fileName, $fileAttr, $fileType );
324 #print STDERR "BackupPC::Xfer::Ftp->restore()";
327 # Prepare the view object
329 $t->{view} = BackupPC::View->new( $bpc, $t->{bkupSrcHost},
331 my $view = $t->{view};
333 SCAN: foreach my $f ( @$fileList ) {
335 #print STDERR "restoring $f...\n";
337 $f =~ /(.*)\/([^\/]*)/;
341 $view->dirCache($path);
343 $fileAttr = $view->fileAttrib($fileName);
344 $fileType = fileType2Text( $fileAttr->{type} );
346 if ( $fileType eq "dir") {
347 $t->restoreDir($fileName, $fileAttr);
349 } elsif ( $fileType eq "file" ) {
350 $t->restoreFile($fileName, $fileAttr);
352 } elsif ( $fileType eq "symlink" ) {
367 my ( $t, $dirName, $dirAttr ) = @_;
371 my $conf = $t->{conf};
372 my $view = $t->{view};
373 my $TopDir = $bpc->TopDir();
375 my $path = "$dirAttr->{relPath}/$dirName";
376 my $dirList = $view->dirAttrib( -1, $t->{shareName}, $path );
378 my ( $fileName, $fileAttr, $fileType );
380 #print STDERR "BackupPC::Xfer::Ftp->restore($dirName)\n";
383 # Create the remote directory
386 eval { $ftp->mkdir( $path, 1 ); };
388 $t->logFileAction( "fail", $dirName, $dirAttr );
392 SCAN: while ( ($fileName, $fileAttr ) = each %$dirList ) {
394 $fileType = fileType2Text( $fileAttr->{type} );
396 if ( $fileType eq "dir" ) {
397 if ( $t->restoreDir( $fileName, $fileAttr ) ) {
398 $t->logWrite( "restored: $path/$fileName\n", 5 );
400 $t->logWrite( "restore failed: $path/$fileName\n", 3 );
403 } elsif ( $fileType eq "file" ) {
404 $t->restoreFile( $fileName, $fileAttr );
406 } elsif ( $fileType eq "hardlink" ) {
408 # Hardlinks cannot be restored. however, if we have the
409 # target file in the pool, we can restore that.
411 $t->restoreFile( $fileName, $fileAttr );
415 } elsif ( $fileType eq "symlink" ) {
417 # Symlinks cannot be restored
423 # Ignore all other types (devices, doors, etc)
433 my ($t, $fileName, $fileAttr ) = @_;
435 my $conf = $t->{conf};
438 my $poolFile = $fileAttr->{fullPath};
439 my $fileDest = ( $conf->{ClientCharset} ne "" )
440 ? from_to( "$fileAttr->{relPath}/$fileName",
441 "utf8", $conf->{ClientCharset} )
442 : "$fileAttr->{relPath}/$fileName";
444 #print STDERR "BackupPC::Xfer::Ftp->restoreFile($fileName)\n";
448 if ( $ftp->put( $poolFile, $fileDest ) ) {
449 $t->logFileAction( "restore", $fileName, $fileAttr );
451 $t->logFileAction( "fail", $fileName, $fileAttr );
455 $t->logFileAction( "fail", $fileName, $fileAttr );
464 # $t->backup() is a recursive function that takes a path as an
465 # argument, and performs a backup on that folder consistent with the
466 # configuration parameters. $path is considered rooted at
467 # $t->{shareName}, so no $ftp->cwd() command is necessary.
475 my $conf = $t->{conf};
476 my $TopDir = $bpc->TopDir();
477 my $OutDir = "$TopDir/pc/$t->{client}/new/"
478 . $bpc->fileNameEltMangle( $t->{shareName} );
481 # Prepare the view object
483 $t->{view} = BackupPC::View->new( $bpc, $t->{client}, $t->{backups} );
486 # Prepare backup folder
488 unless ( eval { mkpath( $OutDir, 0, 0755 ); } ) {
489 $t->{_errStr} = "can't create OutDir: $OutDir";
495 # determine the filetype of the shareName and back it up
496 # appropriately. For now, assume that $t->{shareName} is a
501 fullName => $t->{shareName},
504 if ( $t->handleDir( $f, $OutDir ) ) {
511 $t->{xferBadShareCnt}++;
517 ####################################################################################
518 # FTP-specific functions
519 ####################################################################################
523 # This is an encapulation of the logic necessary to grab the arguments
524 # from %Conf and throw it in a hash pointer to be passed to the
530 my $conf = $t->{conf};
533 Host => $conf->{ClientNameAlias}
536 Firewall => undef, # not used
537 FirewallType => undef, # not used
538 BlockSize => $conf->{FtpBlockSize} || 10240,
539 Port => $conf->{FtpPort} || 21,
540 Timeout => $conf->{FtpTimeout} || 120,
541 Debug => 0, # do not touch
542 Passive => 1, # do not touch
543 Hash => undef, # do not touch
544 LocalAddr => "localhost", # do not touch
551 # $dirList = $t->remotels($path);
553 # remotels() returns a reference to a list of hash references that
554 # describe the contents of each file in the directory of the path
557 # In the future, I would like to make this function return objects in
558 # Attrib format. That would be very optimal, and I could probably
559 # release the code to CPAN.
563 my ( $t, $path ) = @_;
567 my $conf = $t->{conf};
569 my ( $dirContents, $remoteDir, $f );
573 $dirContents = ( $path =~ /^\.?$/ ) ? $ftp->dir()
574 : $ftp->dir("$path/");
578 return "can't retrieve remote directory contents of $path: $!";
581 foreach my $info ( @{parse_dir($dirContents)} ) {
591 $f->{utf8name} = $f->{name};
592 from_to( $f->{utf8name}, $conf->{ClientCharset}, "utf8" )
593 if ( $conf->{ClientCharset} ne "" );
595 $f->{fullName} = "$t->{sharePath}/$path/$f->{name}";
596 $f->{fullName} =~ s/\/+/\//g;
598 $f->{relPath} = ($path eq "") ? $f->{name} : "$path/$f->{name}";
599 $f->{relPath} =~ s/\/+/\//g;
601 push( @$remoteDir, $f );
608 # ignoreFileCheck() looks at the attributes of the arguments and the
609 # backup types, and determines if the file should be skipped in this
614 my ( $t, $f, $attrib ) = @_;
616 if ( $f->{name} =~ /^\.\.?$/ ) {
620 return ( !$t->checkIncludeExclude( $f->{fullName} ) );
625 # handleSymlink() backs up a symlink.
629 my ( $t, $f, $OutDir, $attrib ) = @_;
631 my $conf = $t->{conf};
633 my ( $target, $targetDesc );
636 type => BPC_FTYPE_SYMLINK,
638 uid => undef, # unsupported
639 gid => undef, # unsupported
641 mtime => $f->{mtime},
645 # If we are following symlinks, back them up as the type of file
646 # they point to. Otherwise, backup the symlink.
648 if ( $conf->{FtpFollowSymlinks} ) {
651 # handle nested symlinks by recurring on the target until a
652 # file or directory is found.
654 $f->{type} =~ /^l (.*)/;
659 if ( $targetDesc = $ftp->dir("$target/") ) {
660 $t->handleSymDir( $f, $OutDir, $attrib, $targetDesc );
662 } elsif ( $targetDesc = $ftp->dir($target) ) {
663 if ( $targetDesc->[4] eq 'file' ) {
664 $t->handleSymFile( $f, $OutDir, $attrib );
666 } elsif ( $targetDesc->[4] =~ /l (.*)/ ) {
667 $t->logFileAction( "fail", $f->{utf8name}, $attribInfo );
676 $t->logFileAction( "fail", $f->{utf8name}, $attribInfo );
682 # If we are not following symlinks, record them normally.
684 $attrib->set( $f->{utf8name}, $attribInfo );
685 $t->logFileAction("create", $f->{utf8name}, $attribInfo);
693 my ($t, $fSym, $OutDir, $attrib, $targetDesc) = @_;
701 my ( $t, $fSym, $OutDir, $attrib, $targetDesc ) = @_;
704 my $conf = $t->{conf};
707 name => $fSym->{name},
708 type => $targetDesc->[1],
709 size => $targetDesc->[2],
710 mtime => $targetDesc->[3],
711 mode => $targetDesc->[4]
714 $f->{utf8name} = $fSym->{name};
715 from_to( $f->{utf8name}, $conf->{ClientCharset}, "utf8" )
716 if ( $conf->{ClientCharset} ne "" );
718 $f->{relPath} = $fSym->{relPath};
719 $f->{fullName} = "$t->{shareName}/$fSym->{relPath}/$fSym->{name}";
720 $f->{fullName} =~ s/\/+/\//g;
723 # since FTP servers follow symlinks, we can just do this:
725 return $t->handleFile( $f, $OutDir, $attrib );
730 # handleDir() backs up a directory, and initiates a backup of its
735 my ( $t, $dir, $OutDir ) = @_;
739 my $conf = $t->{conf};
740 my $view = $t->{view};
741 my $stats = $t->{stats};
743 my ( $exists, $digest, $outSize, $errs );
744 my ( $poolWrite, $poolFile, $attribInfo );
745 my ( $localDir, $remoteDir, $attrib, %expectedFiles );
747 if ( exists($dir->{utf8name})) {
748 $OutDir .= "/" . $bpc->fileNameMangle( $dir->{utf8name} );
751 unless ( -d $OutDir ) {
753 eval { mkpath( $OutDir, 0, 0755 ) };
755 $t->logFileAction( "fail", $dir->{utf8name}, $dir );
758 $t->logFileAction( "create", $dir->{utf8name}, $dir );
762 $attrib = BackupPC::Attrib->new( { compress => $t->{compress} } );
763 $remoteDir = $t->remotels( $dir->{relPath} );
765 if ( $t->{type} eq "incr" ) {
766 $localDir = $view->dirAttrib( $t->{incrBaseBkupNum},
767 $t->{shareName}, $dir->{relPath} );
768 %expectedFiles = map { $_ => 0 } sort keys %$localDir
772 # take care of each file in the directory
774 SCAN: foreach my $f ( @{$remoteDir} ) {
776 next SCAN if $t->ignoreFileCheck( $f, $attrib );
779 # handle based on filetype
781 if ( $f->{type} eq 'f' ) {
782 $t->handleFile( $f, $OutDir, $attrib );
784 } elsif ( $f->{type} eq 'd' ) {
787 type => BPC_FTYPE_DIR,
789 uid => undef, # unsupported
790 gid => undef, # unsupported
792 mtime => $f->{mtime},
795 #print STDERR "$f->{utf8name}: ". Dumper($attribInfo);
797 if ( $t->handleDir($f, $OutDir) ) {
798 $attrib->set( $f->{utf8name}, $attribInfo);
801 } elsif ( $f->{type} =~ /^l (.*)/ ) {
802 $t->handleSymlink( $f, $OutDir, $attrib );
811 # Mark file as seen in expected files hash
813 $expectedFiles{ $f->{utf8name} }++ if ( $t->{type} eq "incr" );
815 } # end foreach (@{$remoteDir})
818 # If the backup type is incremental, mark the files that are not
819 # present on the server as deleted.
821 if ( $t->{type} eq "incr" ) {
822 while ( my ($f, $seen) = each %expectedFiles ) {
823 $attrib->set( $f, { type => BPC_FTYPE_DELETED } )
829 # print the directory attributes, now that the directory is done.
831 my $fileName = $attrib->fileName($OutDir);
832 my $data = $attrib->writeData();
834 $poolWrite = BackupPC::PoolWrite->new( $bpc, $fileName, length($data),
836 $poolWrite->write( \$data );
837 ( $exists, $digest, $outSize, $errs ) = $poolWrite->close();
847 # handleFile() backs up a file.
851 my ( $t, $f, $OutDir, $attrib ) = @_;
855 my $view = $t->{view};
856 my $stats = $t->{stats};
857 my $newFilesFH = $t->{newFilesFH};
859 my ( $poolFile, $poolWrite, $data, $localSize );
860 my ( $exists, $digest, $outSize, $errs );
865 # If this is an incremental backup and the file exists in a
866 # previous backup unchanged, write the attribInfo for the file
869 if ( $t->{type} eq "incr" ) {
870 return 1 if $t->incrFileExistCheck( $f, $attrib );
875 type => BPC_FTYPE_FILE,
876 uid => undef, # unsupported
877 gid => undef, # unsupported
879 delete $attribInfo->{utf8name}; # unused value
882 # If this is a full backup or the file has changed on the host,
886 eval { tie ( *FTP, 'Net::FTP::RetrHandle', $ftp, $f->{fullName} ); };
888 $t->logFileAction( "fail", $f->{utf8name}, $attribInfo );
889 $t->{xferBadFileCnt}++;
894 $poolFile = $OutDir . "/" . $bpc->fileNameMangle( $f->{name} );
895 $poolWrite = BackupPC::PoolWrite->new( $bpc, $poolFile, $f->{size},
903 $localSize += length($_);
904 $poolWrite->write( \$_ );
907 ( $exists, $digest, $outSize, $errs ) = $poolWrite->close();
908 if ( !*FTP || $@ || @$errs ) {
910 $t->logFileAction( "fail", $f->{utf8name}, $attribInfo );
912 $t->{xferBadFileCnt}++;
913 $stats->{errCnt} += scalar @$errs;
918 # this should never happen
920 if ( $localSize != $f->{size} ) {
921 $t->logFileAction( "fail", $f->{utf8name}, $attribInfo );
923 $stats->{xferBadFileCnt}++;
931 $attrib->set( $f->{utf8name}, $attribInfo );
932 $t->logFileAction( $exists ? "pool" : "create",
933 $f->{utf8name}, $attribInfo );
935 my $relPoolFile = $bpc->fileNameEltMangle( $t->{shareName} )
937 . $bpc->fileNameMangle($attribInfo->{relPath});
939 print $newFilesFH "$digest $f->{size} $relPoolFile\n" unless $exists;
944 $stats->{TotalFileCnt}++;
945 $stats->{ExistFileCnt}++;
946 $stats->{ExistFileCompSize} += -s $poolFile;
947 $stats->{ExistFileSize} += $f->{size};
948 $stats->{TotalFileSize} += $f->{size};
950 $t->{byteCnt} += $localSize;
956 # this function checks if the file has been modified on disk, and if
957 # it has, returns. Otherwise, it updates the attrib values.
959 sub incrFileExistCheck
961 my ($t, $f, $attrib) = @_;
963 my $view = $t->{view};
965 my $oldAttribInfo = $view->fileAttrib( $t->{incrBaseBkupNum},
966 $t->{shareName}, "/" . $f->{relPath} );
968 ##$t->logWrite( "Old attrib:\n" . Dumper($oldAttribInfo), 1 );
969 ##$t->logWrite( "New attrib:\n" . Dumper($f), 1 );
970 ##$t->logWrite( sprintf("%s: mtime %d vs %d, size %d vs %d\n", $f->{fullName},
971 ## $oldAttribInfo->{mtime}, $f->{mtime},
972 ## $oldAttribInfo->{size}, $f->{size}), 1);
974 return ( $oldAttribInfo->{mtime} == $f->{mtime}
975 && $oldAttribInfo->{size} == $f->{size} );
980 # Generate a log file message for a completed file. Taken from
981 # BackupPC_tarExtract. $f should be an attrib object.
985 my ( $t, $action, $name, $attrib ) = @_;
987 my $owner = "$attrib->{uid}/$attrib->{gid}";
989 ( ( "", "p", "c", "", "d", "", "b", "", "", "", "l", "", "s" ) )
990 [ ( $attrib->{mode} & S_IFMT ) >> 12 ];
992 $name = "." if ( $name eq "" );
993 $owner = "-/-" if ( $owner eq "/" );
995 my $fileAction = sprintf(
996 " %-6s %1s%4o %9s %11.0f %s\n",
997 $action, $type, $attrib->{mode} & 07777,
998 $owner, $attrib->{size}, $attrib->{relPath}
1001 return $t->logWrite( $fileAction, 1 );