r11643@llin: dpavlin | 2005-12-12 22:54:26 +0100
[BackupPC.git] / bin / BackupPC_tarIncCreate
1 #!/usr/bin/perl -w
2 #============================================================= -*-perl-*-
3 #
4 # BackupPC_tarIncCreate: create a tar archive of an existing incremental dump
5
6 #
7 # DESCRIPTION
8 #  
9 #   Usage: BackupPC_tarIncCreate [options]
10 #
11 #   Flags:
12 #     Required options:
13 #
14 #       -h host         Host from which the tar archive is created.
15 #       -n dumpNum      Dump number from which the tar archive is created.
16 #                       A negative number means relative to the end (eg -1
17 #                       means the most recent dump, -2 2nd most recent etc).
18 #       -s shareName    Share name from which the tar archive is created.
19 #
20 #     Other options:
21 #       -t              print summary totals
22 #       -r pathRemove   path prefix that will be replaced with pathAdd
23 #       -p pathAdd      new path prefix
24 #       -b BLOCKS       BLOCKS x 512 bytes per record (default 20; same as tar)
25 #       -w writeBufSz   write buffer size (default 1MB)
26 #
27 #     The -h, -n and -s options specify which dump is used to generate
28 #     the tar archive.  The -r and -p options can be used to relocate
29 #     the paths in the tar archive so extracted files can be placed
30 #     in a location different from their original location.
31 #
32 # AUTHOR
33 #   Craig Barratt  <cbarratt@users.sourceforge.net>
34 #   Ivan Klaric <iklaric@gmail.com>
35 #   Dobrica Pavlinusic <dpavlin@rot13.org>
36 #
37 # COPYRIGHT
38 #   Copyright (C) 2001-2003  Craig Barratt
39 #
40 #   This program is free software; you can redistribute it and/or modify
41 #   it under the terms of the GNU General Public License as published by
42 #   the Free Software Foundation; either version 2 of the License, or
43 #   (at your option) any later version.
44 #
45 #   This program is distributed in the hope that it will be useful,
46 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
47 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
48 #   GNU General Public License for more details.
49 #
50 #   You should have received a copy of the GNU General Public License
51 #   along with this program; if not, write to the Free Software
52 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
53 #
54 #========================================================================
55 #
56 # Version 2.1.0, released 20 Jun 2004.
57 #
58 # See http://backuppc.sourceforge.net.
59 #
60 #========================================================================
61
62 use strict;
63 no  utf8;
64 use lib "__INSTALLDIR__/lib";
65 use File::Path;
66 use Getopt::Std;
67 use DBI;
68 use BackupPC::Lib;
69 use BackupPC::Attrib qw(:all);
70 use BackupPC::FileZIO;
71 use BackupPC::View;
72 use BackupPC::SearchLib;
73 use Time::HiRes qw/time/;
74 use POSIX qw/strftime/;
75 use File::Which;
76 use File::Path;
77 use File::Slurp;
78 use Data::Dumper;       ### FIXME
79
80 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
81 my $TopDir = $bpc->TopDir();
82 my $BinDir = $bpc->BinDir();
83 my %Conf   = $bpc->Conf();
84 %BackupPC::SearchLib::Conf = %Conf;
85 my %opts;
86 my $in_backup_increment;
87
88
89 if ( !getopts("th:n:p:r:s:b:w:vdf", \%opts) ) {
90     print STDERR <<EOF;
91 usage: $0 [options]
92   Required options:
93      -h host         host from which the tar archive is created
94      -n dumpNum      dump number from which the tar archive is created
95                      A negative number means relative to the end (eg -1
96                      means the most recent dump, -2 2nd most recent etc).
97      -s shareName    share name from which the tar archive is created
98
99   Other options:
100      -t              print summary totals
101      -r pathRemove   path prefix that will be replaced with pathAdd
102      -p pathAdd      new path prefix
103      -b BLOCKS       BLOCKS x 512 bytes per record (default 20; same as tar)
104      -w writeBufSz   write buffer size (default 1048576 = 1MB)
105      -f              overwrite existing parts
106      -v              verbose output
107      -d              debug output
108 EOF
109     exit(1);
110 }
111
112 if ( $opts{h} !~ /^([\w\.\s-]+)$/ ) {
113     die "$0: bad host name '$opts{h}'\n";
114 }
115 my $Host = $opts{h};
116
117 if ( $opts{n} !~ /^(-?\d+)$/ ) {
118     die "$0: bad dump number '$opts{n}'\n";
119 }
120 my $Num = $opts{n};
121
122 my $bin;
123 foreach my $c (qw/gzip md5sum tee/) {
124         $bin->{$c} = which($c) || die "$0 needs $c, install it\n";
125 }
126
127 my @Backups = $bpc->BackupInfoRead($Host);
128 my $FileCnt = 0;
129 my $ByteCnt = 0;
130 my $DirCnt = 0;
131 my $SpecialCnt = 0;
132 my $ErrorCnt = 0;
133 my $current_tar_size = 0;
134 my $total_increment_size = 0;
135
136 my $i;
137 $Num = $Backups[@Backups + $Num]{num} if ( -@Backups <= $Num && $Num < 0 );
138 for ( $i = 0 ; $i < @Backups ; $i++ ) {
139     last if ( $Backups[$i]{num} == $Num );
140 }
141 if ( $i >= @Backups ) {
142     die "$0: bad backup number $Num for host $Host\n";
143 }
144
145 my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
146 my $PathAdd    = $1 if ( $opts{p} =~ /(.+)/ );
147 if ( $opts{s} !~ /^([\w\s\.\/\$-]+)$/ && $opts{s} ne "*" ) {
148     die "$0: bad share name '$opts{s}'\n";
149 }
150 our $ShareName = $opts{s};
151 our $view = BackupPC::View->new($bpc, $Host, \@Backups);
152
153 # database
154
155 my $dsn = $Conf{SearchDSN};
156 my $db_user = $Conf{SearchUser} || '';
157
158 my $dbh = DBI->connect($dsn, $db_user, "", { RaiseError => 1, AutoCommit => 0} );
159
160 my $sth_inc_size = $dbh->prepare(qq{
161         update backups set
162                 inc_size = ?,
163                 parts = ?,
164                 inc_deleted = false
165         where id = ?
166 });
167 my $sth_backup_parts = $dbh->prepare(qq{
168         insert into backup_parts (
169                 backup_id,
170                 part_nr,
171                 tar_size,
172                 size,
173                 md5,
174                 items
175         ) values (?,?,?,?,?,?)
176 });
177
178 #
179 # This constant and the line of code below that uses it are borrowed
180 # from Archive::Tar.  Thanks to Calle Dybedahl and Stephen Zander.
181 # See www.cpan.org.
182 #
183 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
184 #                 Copyright 1998 Stephen Zander. All rights reserved.
185 #
186 my $tar_pack_header
187     = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
188 my $tar_header_length = 512;
189
190 my $BufSize    = $opts{w} || 1048576;     # 1MB or 2^20
191 my $WriteBuf   = "";
192 my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
193
194 my(%UidCache, %GidCache);
195 my(%HardLinkExtraFiles, @HardLinks);
196
197 #
198 # Write out all the requested files/directories
199 #
200
201 my $max_file_size = $Conf{'MaxArchiveFileSize'} || die "problem with MaxArchiveFileSize parametar";
202
203 my $tar_dir = $Conf{InstallDir}.'/'.$Conf{GzipTempDir};
204 die "problem with $tar_dir, check GzipTempDir in configuration\n" unless (-d $tar_dir && -w $tar_dir);
205
206 my $tar_file = BackupPC::SearchLib::getGzipName($Host, $ShareName, $Num) || die "can't getGzipName($Host, $ShareName, $Num)";
207
208 my $tar_path_final = $tar_dir . '/' . $tar_file;
209 my $tar_path = $tar_path_final . '.tmp';
210
211 $tar_path =~ s#//#/#g;
212
213 my $sth = $dbh->prepare(qq{
214         SELECT
215                 backups.id
216         FROM backups 
217                 JOIN shares on shares.id = shareid
218                 JOIN hosts on hosts.id = shares.hostid
219         WHERE hosts.name = ? and shares.name = ? and backups.num = ?
220 });
221 $sth->execute($Host, $ShareName, $Num);
222 my ($backup_id) = $sth->fetchrow_array;
223 $sth->finish;
224
225
226 # delete exising backup_parts
227 my $sth_delete_backup_parts = $dbh->prepare(qq{
228         delete from backup_parts
229         where backup_id = ?
230 });
231 $sth_delete_backup_parts->execute($backup_id);
232
233
234 print STDERR "backup_id: $backup_id working dir: $tar_dir, max uncompressed size $max_file_size bytes, tar $tar_file\n" if ($opts{d});
235
236 if (-e $tar_path_final) {
237         if ($opts{f}) {
238                 rmtree $tar_path_final || die "can't remove $tar_path_final: $!";
239         } else {
240                 die "$tar_path_final allready exists\n";
241         }
242 }
243
244 my $fh;
245 my $part = 0;
246 my $no_files = 0;
247 my $items_in_part = 0;
248
249 sub new_tar_part {
250         my $arg = {@_};
251
252         if ($fh) {
253                 return if ($current_tar_size == 0);
254
255                 print STDERR " $part";
256
257                 #
258                 # Finish with two null 512 byte headers,
259                 # and then round out a full block.
260                 # 
261                 my $data = "\0" x ($tar_header_length * 2);
262                 TarWrite($fh, \$data);
263                 TarWrite($fh, undef);
264
265                 close($fh) || die "can't close archive part $part: $!";
266
267                 my $file = $tar_path . '/' . $part;
268
269                 my $md5 = read_file( $file . '.md5' ) || die "can't read md5sum file ${file}.md5";
270                 $md5 =~ s/\s.*$//;
271
272                 my $size = (stat( $file . '.tar.gz' ))[7] || die "can't stat ${file}.tar.gz";
273
274                 $sth_backup_parts->execute(
275                         $backup_id,
276                         $part,
277                         $current_tar_size,
278                         $size,
279                         $md5,
280                         $items_in_part,
281                 );
282
283                 $total_increment_size += $size;
284
285                 if ($arg->{close}) {
286
287                         sub move($$) {
288                                 my ($from,$to) = @_;
289                                 print STDERR "# rename $from -> $to\n" if ($opts{d});
290                                 rename $from, $to || die "can't move $from -> $to: $!\n";
291                         }
292
293                         if ($part == 1) {
294                                 print STDERR " single" if ($opts{v});
295                                 move("${tar_path}/1.tar.gz", "${tar_path_final}.tar.gz");
296                                 move("${tar_path}/1.md5", "${tar_path_final}.md5");
297                                 rmtree $tar_path or die "can't remove temporary dir $tar_path: $!";
298                         } else {
299                                 print STDERR " [last]" if ($opts{v});
300                                 move("${tar_path}", "${tar_path_final}");
301                         }
302
303                         $sth_inc_size->execute(
304                                 $total_increment_size,
305                                 $part,
306                                 $backup_id
307                         );
308
309                         print STDERR ", $total_increment_size bytes\n" if ($opts{v});
310
311                         return;
312                 }
313
314         }
315
316         $part++;
317
318         # if this is first part, create directory
319
320         if ($part == 1) {
321                 if (-e $tar_path) {
322                         print STDERR "# deleting existing $tar_path\n" if ($opts{d});
323                         rmtree($tar_path);
324                 }
325                 mkdir($tar_path) || die "can't create directory $tar_path: $!";
326
327                 sub abort_cleanup {
328                         print STDERR "ABORTED: cleanup temp dir";
329                         rmtree($tar_path);
330                         $dbh->rollback;
331                         exit 1;
332                 }
333
334                 $SIG{'INT'}  = \&abort_cleanup;
335                 $SIG{'QUIT'} = \&abort_cleanup;
336                 $SIG{'__DIE__'} = \&abort_cleanup;
337
338         }
339
340         my $file = $tar_path . '/' . $part;
341
342         #
343         # create comprex pipe which will pass output through gzip
344         # for compression, create file on disk using tee
345         # and pipe same output to md5sum to create checksum
346         #
347
348         my $cmd = '| ' . $bin->{'gzip'}   . ' ' . $Conf{GzipLevel} .      ' ' .
349                   '| ' . $bin->{'tee'}    . ' ' . $file . '.tar.gz' . ' ' .
350                   '| ' . $bin->{'md5sum'} . ' - > ' . $file . '.md5';
351
352         print STDERR "## $cmd\n" if ($opts{d});
353
354         open($fh, $cmd) or die "can't open $cmd: $!";
355         binmode($fh);
356
357         $current_tar_size = 0;
358         $items_in_part = 0;
359 }
360
361 new_tar_part();
362
363 if (seedCache($Host, $ShareName, $Num)) {
364         archiveWrite($fh, '/');
365         archiveWriteHardLinks($fh);
366         new_tar_part( close => 1 );
367 } else {
368         print STDERR "NOTE: no files found for $Host:$ShareName, increment $Num\n" if ($opts{v});
369         # remove temporary files if there are no files
370         rmtree($tar_path);
371 }
372
373 #
374 # print out totals if requested
375 #
376 if ( $opts{t} ) {
377     print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
378                  " $SpecialCnt specials, $ErrorCnt errors\n";
379 }
380 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
381     #
382     # Got errors, with no files or directories; exit with non-zero
383     # status
384     #
385     die "got errors or no files\n";
386 }
387
388 $sth_inc_size->finish;
389 $sth_backup_parts->finish;
390
391 $dbh->commit || die "can't commit changes to database";
392 $dbh->disconnect();
393
394 exit;
395
396 ###########################################################################
397 # Subroutines
398 ###########################################################################
399
400 sub archiveWrite
401 {
402     my($fh, $dir, $tarPathOverride) = @_;
403
404     if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
405         print(STDERR "$0: bad directory '$dir'\n");
406         $ErrorCnt++;
407         return;
408     }
409     $dir = "/" if ( $dir eq "." );
410     #print(STDERR "calling find with $Num, $ShareName, $dir\n");
411     
412     if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
413                 $fh, $tarPathOverride) < 0 ) {
414         print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
415         $ErrorCnt++;
416         return;
417     }
418 }
419
420 #
421 # Write out any hardlinks (if any)
422 #
423 sub archiveWriteHardLinks
424 {
425     my $fh = @_;
426     foreach my $hdr ( @HardLinks ) {
427         $hdr->{size} = 0;
428         if ( defined($PathRemove)
429               && substr($hdr->{linkname}, 0, length($PathRemove)+1)
430                         eq ".$PathRemove" ) {
431             substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
432         }
433         TarWriteFileInfo($fh, $hdr);
434     }
435     @HardLinks = ();
436     %HardLinkExtraFiles = ();
437 }
438
439 sub UidLookup
440 {
441     my($uid) = @_;
442
443     $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
444     return $UidCache{$uid};
445 }
446
447 sub GidLookup
448 {
449     my($gid) = @_;
450
451     $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
452     return $GidCache{$gid};
453 }
454
455 sub TarWrite
456 {
457     my($fh, $dataRef) = @_;
458
459
460     if ( !defined($dataRef) ) {
461         #
462         # do flush by padding to a full $WriteBufSz
463         #
464         my $data = "\0" x ($WriteBufSz - length($WriteBuf));
465         $dataRef = \$data;
466     }
467
468     # poor man's tell :-)
469     $current_tar_size += length($$dataRef);
470
471     if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
472         #
473         # just buffer and return
474         #
475         $WriteBuf .= $$dataRef;
476         return;
477     }
478     my $done = $WriteBufSz - length($WriteBuf);
479     if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
480                                 != $WriteBufSz ) {
481         die "Unable to write to output file ($!)\n";
482     }
483     while ( $done + $WriteBufSz <= length($$dataRef) ) {
484         if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
485                             != $WriteBufSz ) {
486             die "Unable to write to output file ($!)\n";
487         }
488         $done += $WriteBufSz;
489     }
490     $WriteBuf = substr($$dataRef, $done);
491 }
492
493 sub TarWritePad
494 {
495     my($fh, $size) = @_;
496
497     if ( $size % $tar_header_length ) {
498         my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
499         TarWrite($fh, \$data);
500     }
501 }
502
503 sub TarWriteHeader
504 {
505     my($fh, $hdr) = @_;
506
507     $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
508     $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
509     my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
510                                              : "";
511     my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
512                                              : "";
513     my $sizeStr;
514     if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
515         #
516         # GNU extension for files >= 8GB: send size in big-endian binary
517         #
518         $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
519                                   $hdr->{size} / (65536 * 65536),
520                                   $hdr->{size} % (65536 * 65536));
521     } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
522         #
523         # sprintf octal only handles up to 2^32 - 1
524         #
525         $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
526                  . sprintf("%08o", $hdr->{size} % (1 << 24));
527     } else {
528         $sizeStr = sprintf("%011o", $hdr->{size});
529     }
530     my $data = pack($tar_pack_header,
531                      substr($hdr->{name}, 0, 99),
532                      sprintf("%07o", $hdr->{mode}),
533                      sprintf("%07o", $hdr->{uid}),
534                      sprintf("%07o", $hdr->{gid}),
535                      $sizeStr,
536                      sprintf("%011o", $hdr->{mtime}),
537                      "",        #checksum field - space padded by pack("A8")
538                      $hdr->{type},
539                      substr($hdr->{linkname}, 0, 99),
540                      $hdr->{magic} || 'ustar ',
541                      $hdr->{version} || ' ',
542                      $hdr->{uname},
543                      $hdr->{gname},
544                      $devmajor,
545                      $devminor,
546                      ""         # prefix is empty
547                  );
548     substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
549     TarWrite($fh, \$data);
550 }
551
552 sub TarWriteFileInfo
553 {
554     my($fh, $hdr) = @_;
555
556     #
557     # Handle long link names (symbolic links)
558     #
559     if ( length($hdr->{linkname}) > 99 ) {
560         my %h;
561         my $data = $hdr->{linkname} . "\0";
562         $h{name} = "././\@LongLink";
563         $h{type} = "K";
564         $h{size} = length($data);
565         TarWriteHeader($fh, \%h);
566         TarWrite($fh, \$data);
567         TarWritePad($fh, length($data));
568     }
569     #
570     # Handle long file names
571     #
572     if ( length($hdr->{name}) > 99 ) {
573         my %h;
574         my $data = $hdr->{name} . "\0";
575         $h{name} = "././\@LongLink";
576         $h{type} = "L";
577         $h{size} = length($data);
578         TarWriteHeader($fh, \%h);
579         TarWrite($fh, \$data);
580         TarWritePad($fh, length($data));
581     }
582     TarWriteHeader($fh, $hdr);
583 }
584
585 #
586 # seed cache of files in this increment
587 #
588 sub seedCache($$$) {
589         my ($host, $share, $dumpNo) = @_;
590
591         print STDERR curr_time(), "$host:$share #$dumpNo" if ($opts{v});
592         my $sql = q{
593                 SELECT path,size
594                 FROM files
595                         JOIN shares on shares.id = shareid
596                         JOIN hosts on hosts.id = shares.hostid
597                 WHERE hosts.name = ? and shares.name = ? and backupnum = ?
598         };
599
600         my $sth = $dbh->prepare($sql);  
601         $sth->execute($host, $share, $dumpNo);
602         my $count = $sth->rows;
603         print STDERR " $count items, parts:" if ($opts{v});
604         while (my $row = $sth->fetchrow_arrayref) {
605 #print STDERR "+ ", $row->[0],"\n";
606                 $in_backup_increment->{ $row->[0] } = $row->[1];
607         }
608         
609         $sth->finish();
610
611         return $count;
612 }
613
614 #
615 # calculate overhad for one file in tar
616 #
617 sub tar_overhead($) {
618         my $name = shift || '';
619
620         # header, padding of file and two null blocks at end
621         my $len = 4 * $tar_header_length;
622
623         # if filename is longer than 99 chars subtract blocks for
624         # long filename
625         if ( length($name) > 99 ) {
626                 $len += int( ( length($name) + $tar_header_length ) / $tar_header_length ) * $tar_header_length;
627         }
628
629         return $len;
630 }
631
632 my $Attr;
633 my $AttrDir;
634
635 sub TarWriteFile
636 {
637     my($hdr, $fh, $tarPathOverride) = @_;
638
639     my $tarPath = $hdr->{relPath};
640     $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
641
642     $tarPath =~ s{//+}{/}g;
643
644     #print STDERR "? $tarPath\n" if ($opts{d});
645     my $size = $in_backup_increment->{$tarPath};
646     return unless (defined($size));
647
648     # is this file too large to fit into MaxArchiveFileSize?
649
650     if ( ($current_tar_size + tar_overhead($tarPath) + $size) > $max_file_size ) {
651         print STDERR "# tar file $current_tar_size + $tar_header_length + $size > $max_file_size, splitting\n" if ($opts{d});
652         new_tar_part();
653     }
654
655     #print STDERR "A $tarPath [$size] tell: $current_tar_size\n" if ($opts{d});
656     $items_in_part++;
657
658     if ( defined($PathRemove)
659             && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
660         substr($tarPath, 0, length($PathRemove)) = $PathAdd;
661     }
662     $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
663     $tarPath =~ s{//+}{/}g;
664     $hdr->{name} = $tarPath;
665
666     if ( $hdr->{type} == BPC_FTYPE_DIR ) {
667         #
668         # Directory: just write the header
669         #
670         $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
671         TarWriteFileInfo($fh, $hdr);
672         $DirCnt++;
673     } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
674         #
675         # Regular file: write the header and file
676         #
677         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
678         if ( !defined($f) ) {
679             print(STDERR "Unable to open file $hdr->{fullPath}\n");
680             $ErrorCnt++;
681             return;
682         }
683         # do we need to split file?
684         if ($hdr->{size} < $max_file_size) {
685                 TarWriteFileInfo($fh, $hdr);
686                 my($data, $size);
687                 while ( $f->read(\$data, $BufSize) > 0 ) {
688                     TarWrite($fh, \$data);
689                     $size += length($data);
690                 }
691                 $f->close;
692                 TarWritePad($fh, $size);
693                 $FileCnt++;
694                 $ByteCnt += $size;
695         } else {
696                 my $full_size = $hdr->{size};
697                 my $orig_name = $hdr->{name};
698                 my $max_part_size = $max_file_size - tar_overhead($hdr->{name});
699
700                 my $parts = int(($full_size + $max_part_size - 1) / $max_part_size);
701                 print STDERR "# splitting $orig_name [$full_size bytes] into $parts parts\n" if ($opts{d});
702                 foreach my $subpart ( 1 .. $parts ) {
703                         new_tar_part();
704                         if ($subpart < $parts) {
705                                 $hdr->{size} = $max_part_size;
706                         } else {
707                                 $hdr->{size} = $full_size % $max_part_size;
708                         }
709                         $hdr->{name} = $orig_name . '/' . $subpart;
710                         print STDERR "## creating part $subpart ",$hdr->{name}, " [", $hdr->{size}," bytes]\n";
711
712                         TarWriteFileInfo($fh, $hdr);
713                         my($data, $size);
714 if (0) {
715                         for ( 1 .. int($hdr->{size} / $BufSize) ) {
716                                 my $r_size = $f->read(\$data, $BufSize);
717                                 die "expected $BufSize bytes read, got $r_size bytes!" if ($r_size != $BufSize);
718                                 TarWrite($fh, \$data);
719                                 $size += length($data);
720                         }
721 }
722                         my $size_left = $hdr->{size} % $BufSize;
723                         my $r_size = $f->read(\$data, $size_left);
724                         die "expected $size_left bytes last read, got $r_size bytes!" if ($r_size != $size_left);
725
726                         TarWrite($fh, \$data);
727                         $size += length($data);
728                         TarWritePad($fh, $size);
729
730                         $items_in_part++;
731                 }
732                 $f->close;
733                 $FileCnt++;
734                 $ByteCnt += $full_size;
735                 new_tar_part();
736         }
737     } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
738         #
739         # Hardlink file: either write a hardlink or the complete file
740         # depending upon whether the linked-to file will be written
741         # to the archive.
742         #
743         # Start by reading the contents of the link.
744         #
745         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
746         if ( !defined($f) ) {
747             print(STDERR "Unable to open file $hdr->{fullPath}\n");
748             $ErrorCnt++;
749             return;
750         }
751         my $data;
752         while ( $f->read(\$data, $BufSize) > 0 ) {
753             $hdr->{linkname} .= $data;
754         }
755         $f->close;
756         my $done = 0;
757         my $name = $hdr->{linkname};
758         $name =~ s{^\./}{/};
759         if ( $HardLinkExtraFiles{$name} ) {
760             #
761             # Target file will be or was written, so just remember
762             # the hardlink so we can dump it later.
763             #
764             push(@HardLinks, $hdr);
765             $SpecialCnt++;
766         } else {
767             #
768             # Have to dump the original file.  Just call the top-level
769             # routine, so that we save the hassle of dealing with
770             # mangling, merging and attributes.
771             #
772             $HardLinkExtraFiles{$hdr->{linkname}} = 1;
773             archiveWrite($fh, $hdr->{linkname}, $hdr->{name});
774         }
775     } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
776         #
777         # Symbolic link: read the symbolic link contents into the header
778         # and write the header.
779         #
780         my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
781         if ( !defined($f) ) {
782             print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
783             $ErrorCnt++;
784             return;
785         }
786         my $data;
787         while ( $f->read(\$data, $BufSize) > 0 ) {
788             $hdr->{linkname} .= $data;
789         }
790         $f->close;
791         $hdr->{size} = 0;
792         TarWriteFileInfo($fh, $hdr);
793         $SpecialCnt++;
794     } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
795            || $hdr->{type} == BPC_FTYPE_BLOCKDEV
796            || $hdr->{type} == BPC_FTYPE_FIFO ) {
797         #
798         # Special files: for char and block special we read the
799         # major and minor numbers from a plain file.
800         #
801         if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
802             my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
803                                                 $hdr->{compress});
804             my $data;
805             if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
806                 print(STDERR "Unable to open/read char/block special file"
807                            . " $hdr->{fullPath}\n");
808                 $f->close if ( defined($f) );
809                 $ErrorCnt++;
810                 return;
811             }
812             $f->close;
813             if ( $data =~ /(\d+),(\d+)/ ) {
814                 $hdr->{devmajor} = $1;
815                 $hdr->{devminor} = $2;
816             }
817         }
818         $hdr->{size} = 0;
819         TarWriteFileInfo($fh, $hdr);
820         $SpecialCnt++;
821     } else {
822         print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
823         $ErrorCnt++;
824     }
825 }
826
827 my $t_fmt = '%Y-%m-%d %H:%M:%S';
828 sub curr_time {
829         return strftime($t_fmt,localtime());
830 }