This file is indexed.

/usr/lib/perl5/File/RsyncP/FileIO.pm is in libfile-rsyncp-perl 0.70-1ubuntu3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
#============================================================= -*-perl-*-
#
# File::RsyncP::FileIO package
#
# DESCRIPTION
#   Provide file system IO for File::RsyncP.
#
# AUTHOR
#   Craig Barratt  <cbarratt@users.sourceforge.net>
#
# COPYRIGHT
#   File::RsyncP is Copyright (C) 2002  Craig Barratt.
#
#   Rsync is Copyright (C) 1996-2001 by Andrew Tridgell, 1996 by Paul
#   Mackerras, and 2001, 2002 by Martin Pool.
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#========================================================================
#
# Version 0.70, released 25 Jul 2010.
#
# See http://perlrsync.sourceforge.net.
#
#========================================================================

package File::RsyncP::FileIO;

use strict;
use File::RsyncP::Digest;
use File::Path;
use File::Find;

use vars qw($VERSION);
$VERSION = '0.70';

use constant S_IFMT       => 0170000;	# type of file
use constant S_IFDIR      => 0040000; 	# directory
use constant S_IFCHR      => 0020000; 	# character special
use constant S_IFBLK      => 0060000; 	# block special
use constant S_IFREG      => 0100000; 	# regular
use constant S_IFLNK      => 0120000; 	# symbolic link
use constant S_IFSOCK     => 0140000; 	# socket
use constant S_IFIFO      => 0010000; 	# fifo

sub new
{
    my($class, $options) = @_;

    $options ||= {};
    my $self = bless {
        blockSize    => 700,
        logLevel     => 0,
        digest       => File::RsyncP::Digest->new($options->{protocol_version}),
        checksumSeed => 0,
	logHandler   => \&logHandler,
	%$options,
    }, $class;
    return $self;
}

sub blockSize
{
    my($fio, $value) = @_;

    $fio->{blockSize} = $value if ( defined($value) );
    return $fio->{blockSize};
}

#
# We publish our version to File::RsyncP.  This is so File::RsyncP
# can provide backward compatibility to older FileIO code.
#
# Versions:
#
#   undef or 1:  protocol version 26, no hardlinks
#   2:           protocol version 28, supports hardlinks
#
sub version
{
    return 2;
}

sub preserve_hard_links
{   
    my($fio, $value) = @_;

    $fio->{preserve_hard_links} = $value if ( defined($value) );
    return $fio->{preserve_hard_links};
}

sub protocol_version
{
    my($fio, $value) = @_;

    if ( defined($value) ) {
        $fio->{protocol_version} = $value;
        $fio->{digest}->protocol($fio->{protocol_version});
    }
    return $fio->{protocol_version};
}

sub logHandlerSet
{
    my($fio, $sub) = @_;
    $fio->{logHandler} = $sub;
}

#
# Given a remote name, return the local name
#
sub localName
{
    my($fio, $name) = @_;

    return $name if ( !defined($fio->{localDir})
	   	   && !defined($fio->{remoteDir}) );
    if ( substr($name, 0, length($fio->{remoteDir})) eq $fio->{remoteDir} ) {
	substr($name, 0, length($fio->{remoteDir})) = $fio->{localDir};
    }
    return $name;
}

#
# Setup rsync checksum computation for the given file.
#
sub csumStart
{
    my($fio, $f, $needMD4) = @_;
    local(*F);
    my $localName = $fio->localName($f->{name});

    $fio->{file} = $f;
    $fio->csumEnd if ( defined($fio->{fh}) );
    return if ( !-f $localName || -l $localName );
    if ( !open(F, $localName) ) {
        $fio->log("Can't open $localName");
        return -1;
    }
    if ( $needMD4) {
	$fio->{csumDigest}
                    = File::RsyncP::Digest->new($fio->{protocol_version});
	$fio->{csumDigest}->add(pack("V", $fio->{checksumSeed}));
    } else {
	delete($fio->{csumDigest});
    }
    $fio->{fh} = *F;
}

sub csumGet
{
    my($fio, $num, $csumLen, $blockSize) = @_;
    my($fileData);

    $num     ||= 100;
    $csumLen ||= 16;

    return if ( !defined($fio->{fh}) );
    if ( sysread($fio->{fh}, $fileData, $blockSize * $num) <= 0 ) {
        return;
    }
    $fio->{csumDigest}->add($fileData) if ( defined($fio->{csumDigest}) );
    $fio->log(sprintf("%s: getting csum ($num,$csumLen,%d,0x%x)",
                            $fio->{file}{name},
                            length($fileData),
                            $fio->{checksumSeed}))
                if ( $fio->{logLevel} >= 10 );
    return $fio->{digest}->blockDigest($fileData, $blockSize,
                                         $csumLen, $fio->{checksumSeed});
}

sub csumEnd
{
    my($fio) = @_;

    return if ( !defined($fio->{fh}) );
    #
    # make sure we read the entire file for the file MD4 digest
    #
    if ( defined($fio->{csumDigest}) ) {
	while ( sysread($fio->{fh}, my $fileData, 65536) > 0 ) {
	    $fio->{csumDigest}->add($fileData);
	}
    }
    close($fio->{fh});
    delete($fio->{fh});
    return $fio->{csumDigest}->digest if ( defined($fio->{csumDigest}) );
}

sub readStart
{
    my($fio, $f) = @_;
    local(*F);
    my $localName = $fio->localName($f->{name});

    $fio->{file} = $f;
    $fio->readEnd if ( defined($fio->{fh}) );
    return if ( !-f $localName || -l $localName );
    if ( !open(F, $localName) ) {
        $fio->log("Can't open $localName");
        return;
    }
    $fio->{fh} = *F;
}

sub read
{
    my($fio, $num) = @_;
    my($fileData);

    $num ||= 32768;
    return if ( !defined($fio->{fh}) );
    if ( sysread($fio->{fh}, $fileData, $num) <= 0 ) {
        return $fio->readEnd;
    }
    return \$fileData;
}

sub readEnd
{
    my($fio) = @_;

    return if ( !defined($fio->{fh}) );
    close($fio->{fh});
    delete($fio->{fh});
}

sub checksumSeed
{
    my($fio, $checksumSeed) = @_;

    $fio->{checksumSeed} = $checksumSeed;
}

sub dirs
{
    my($fio, $localDir, $remoteDir) = @_;

    $fio->{localDir}  = $localDir;
    $fio->{remoteDir} = $remoteDir;
}

sub attribGet
{
    my($fio, $f) = @_;
    my $localName = $fio->localName($f->{name});

    my @s = stat($localName);
    return if ( !@s );
    return {
        mode  => $s[2],
        uid   => $s[4],
        gid   => $s[5],
        size  => $s[7],
        mtime => $s[9],
    }
}

#
# Set the attributes for a file.  Returns non-zero on error.
#
sub attribSet
{
    my($fio, $f, $placeHolder) = @_;
    my $ret;

    #
    # Ignore placeholder attribute sets: only do real ones.
    #
    return if ( $placeHolder );

    my $lName = $fio->localName($f->{name});
    my @s = stat($lName);
    my $a = {
        mode  => $s[2],
        uid   => $s[4],
        gid   => $s[5],
        size  => $s[7],
        atime => $s[8],
        mtime => $s[9],
    };
    $f->{atime} = $f->{mtime} if ( !defined($f->{atime}) );
    if ( ($f->{mode} & ~S_IFMT) != ($a->{mode} & ~S_IFMT)
		&& !chmod($f->{mode} & ~S_IFMT, $lName) ) {
        $fio->log(sprintf("Can't chmod(%s, 0%o)", $lName, $f->{mode}));
        $ret = -1;
    }
    if ( ($f->{uid} != $a->{uid} || $f->{gid} != $a->{gid})
	    && !chown($f->{uid}, $f->{gid}, $lName) ) {
        $fio->log("Can't chown($f->{uid}, $f->{gid}, $lName)");
        $ret = -1;
    }
    if ( ($f->{mtime} != $a->{mtime} || $f->{atime} != $a->{atime})
            && !utime($f->{atime}, $f->{mtime}, $lName) ) {
        $fio->log("Can't mtime($f->{atime}, $f->{mtime}, $lName)");
        $ret = -1;
    }
    return $ret;
}

sub statsGet
{
    my($fio) = @_;

    return {};
}

#
# Make a given directory.  Returns non-zero on error.
#
sub makePath
{
    my($fio, $f) = @_;
    my $localDir = $fio->localName($f->{name});

    return $fio->attribSet($f) if ( -d $localDir );
    File::Path::mkpath($localDir, 0, $f->{mode});
    return $fio->attribSet($f) if ( -d $localDir );
    $fio->log("Can't create directory $localDir");
    return -1;
}

#
# Make a special file.  Returns non-zero on error.
#
sub makeSpecial
{
    my($fio, $f) = @_;
    my $localPath = $fio->localName($f->{name});

    #
    # TODO: check if the special file is the same, then do nothing.
    # Should also create as a new unique name, then rename/unlink.
    #
    $fio->unlink($f->{name});
    if ( ($f->{mode} & S_IFMT) == S_IFCHR ) {
	my($major, $minor);

	$major = $f->{rdev} >> 8;
	$minor = $f->{rdev} & 0xff;
	return system("mknod $localPath c $major $minor");
    } elsif ( ($f->{mode} & S_IFMT) == S_IFBLK ) {
	my($major, $minor);

	$major = $f->{rdev} >> 8;
	$minor = $f->{rdev} & 0xff;
	return system("mknod $localPath b $major $minor");
    } elsif ( ($f->{mode} & S_IFMT) == S_IFLNK ) {
	if ( !symlink($f->{link}, $localPath) ) {
	    # error
	}
    } elsif ( ($f->{mode} & S_IFMT) == S_IFIFO ) {
	if ( system("mknod $localPath p") ) {
	    # error
	}
    }
    return $fio->attribSet($f);
}

#
# Make a hardlink.  Returns non-zero on error.
# This actually gets called twice for each hardlink.
# Once as the file list is processed, and again at
# the end.  This subroutine should decide whether it
# should do the hardlinks during the transer or at
# the end.  Normally they would be done at the end
# since the target might not exist until them.
# BackupPC does them as it goes (since it is just saving the
# hardlink info and not actually making hardlinks).
#
sub makeHardLink
{
    my($fio, $f, $end) = @_;

    #
    # In this case, only do hardlinks at the end.
    #
    return if ( !$end );
    my $localPath = $fio->localName($f->{name});
    my $destLink  = $fio->localName($f->{hlink});
    $fio->unlink($localPath) if ( -e $localPath );
    return !link($destLink, $localPath);
}


sub unlink
{
    my($fio, $path) = @_;
    my $localPath   = $fio->localName($path);

    return if ( !-e $localPath && !-l $localPath );
    if ( -d _ ) {
	rmtree($localPath);
    } else {
	CORE::unlink($localPath);
    }
}

sub ignoreAttrOnFile
{
    return undef;
}

#
# Start receive of file deltas for a particular file.
#
sub fileDeltaRxStart
{
    my($fio, $f, $cnt, $size, $remainder) = @_;

    $fio->{rxFile}      = $f;           # file attributes
    $fio->{rxBlkCnt}    = $cnt;         # how many blocks we will receive
    $fio->{rxBlkSize}   = $size;        # block size
    $fio->{rxRemainder} = $remainder;   # size of the last block
    $fio->{rxMatchBlk}  = 0;            # current start of match
    $fio->{rxMatchNext} = 0;            # current next block of match
    $fio->{rxSize}      = 0;            # size of received file
    if ( $fio->{rxFile}{size} != ($cnt > 0
				 ? ($cnt - 1) * $size + $remainder
				 : 0) ) {
        $fio->{rxMatchBlk} = undef;     # size different, so no file match
        $fio->log("$fio->{rxFile}{name}: size doesn't match"
                  . " ($fio->{rxFile}{size})")
                        if ( $fio->{logLevel} >= 5 );
    }
    delete($fio->{rxInFd});
    delete($fio->{rxOutFd});
    delete($fio->{rxDigest});
    $fio->{rxFile}{localName} = $fio->localName($fio->{rxFile}{name});
}

#
# Process the next file delta for the current file.  Returns 0 if ok,
# -1 if not.  Must be called with either a block number, $blk, or new data,
# $newData, (not both) defined.
#
sub fileDeltaRxNext
{
    my($fio, $blk, $newData) = @_;

    if ( defined($blk) ) {
        if ( defined($fio->{rxMatchBlk}) && $fio->{rxMatchNext} == $blk ) {
            #
            # got the next block in order; just keep track.
            #
            $fio->{rxMatchNext}++;
            return;
        }
    }
    my $newDataLen = length($newData);
    $fio->log("$fio->{rxFile}{name}: blk=$blk, newData=$newDataLen,"
        . " rxMatchBlk=$fio->{rxMatchBlk}, rxMatchNext=$fio->{rxMatchNext}")
		    if ( $fio->{logLevel} >= 8 );
    if ( !defined($fio->{rxOutFd}) ) {
	#
	# maybe the file has no changes
	#
	if ( $fio->{rxMatchNext} == $fio->{rxBlkCnt}
		&& !defined($blk) && !defined($newData) ) {
	    #$fio->log("$fio->{rxFile}{name}: file is unchanged");
	    #		    if ( $fio->{logLevel} >= 8 );
	    return;
	}

        #
        # need to open a temporary output file where we will build the
        # new version.
        #
        local(*F);
        my $rxTmpFile;
        for ( my $i = 0 ; ; $i++ ) {
            $rxTmpFile = "$fio->{rxFile}{localName}__tmp__$$.$i";
            last if ( !-e $rxTmpFile );
        }
        if ( !open(F, ">$rxTmpFile") ) {
            $fio->log("Can't open/create $rxTmpFile");
            return -1;
        }
        $fio->log("$fio->{rxFile}{name}: opening tmp output file $rxTmpFile")
                        if ( $fio->{logLevel} >= 10 );
        $fio->{rxOutFd} = *F;
        $fio->{rxTmpFile} = $rxTmpFile;

        $fio->{rxDigest} = File::RsyncP::Digest->new($fio->{protocol_version});
        $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
    }
    if ( defined($fio->{rxMatchBlk})
                && $fio->{rxMatchBlk} != $fio->{rxMatchNext} ) {
        #
        # need to copy the sequence of blocks that matched
        #
        if ( !defined($fio->{rxInFd}) ) {
            if ( open(F, "$fio->{rxFile}{localName}") ) {
                $fio->{rxInFd} = *F;
            } else {
                $fio->log("Unable to open $fio->{rxFile}{localName}");
                return -1;
            }
        }
	my $lastBlk = $fio->{rxMatchNext} - 1;
        $fio->log("$fio->{rxFile}{name}: writing blocks $fio->{rxMatchBlk}.."
                  . "$lastBlk")
                        if ( $fio->{logLevel} >= 10 );
        my $seekPosn = $fio->{rxMatchBlk} * $fio->{rxBlkSize};
        if ( !sysseek($fio->{rxInFd}, $seekPosn, 0) ) {
            $fio->log("Unable to seek $fio->{rxFile}{localName} to $seekPosn");
            return -1;
        }
        my $cnt = $fio->{rxMatchNext} - $fio->{rxMatchBlk};
        my($thisCnt, $len, $data);
        for ( my $i = 0 ; $i < $cnt ; $i += $thisCnt ) {
            $thisCnt = $cnt - $i;
            $thisCnt = 512 if ( $thisCnt > 512 );
            if ( $fio->{rxMatchBlk} + $i + $thisCnt == $fio->{rxBlkCnt} ) {
                $len = ($thisCnt - 1) * $fio->{rxBlkSize} + $fio->{rxRemainder};
            } else {
                $len = $thisCnt * $fio->{rxBlkSize};
            }
            if ( sysread($fio->{rxInFd}, $data, $len) != $len ) {
                $fio->log("Unable to read $len bytes from"
                          . " $fio->{rxFile}{localName} ($i,$thisCnt,$fio->{rxBlkCnt})");
                return -1;
            }
            if ( syswrite($fio->{rxOutFd}, $data) != $len ) {
                $fio->log("Unable to write $len bytes to"
                          . " $fio->{rxTmpFile}");
            }
            $fio->{rxDigest}->add($data);
	    $fio->{rxSize} += length($data);
        }
        $fio->{rxMatchBlk} = undef;
    }
    if ( defined($blk) ) {
        #
        # Remember the new block number
        #
        $fio->{rxMatchBlk}  = $blk;
        $fio->{rxMatchNext} = $blk + 1;
    }
    if ( defined($newData) ) {
        #
        # Write the new chunk
        #
        my $len = length($newData);
        $fio->log("$fio->{rxFile}{name}: writing $len bytes new data")
                        if ( $fio->{logLevel} >= 10 );
        if ( syswrite($fio->{rxOutFd}, $newData) != $len ) {
            $fio->log("Unable to write $len bytes to $fio->{rxTmpFile}");
            return -1;
        }
        $fio->{rxDigest}->add($newData);
	$fio->{rxSize} += length($newData);
    }
    return;
}

#
# Finish up the current receive file.  Returns undef if ok, -1 if not.
# Returns 1 if the md4 digest doesn't match.
#
sub fileDeltaRxDone
{
    my($fio, $md4) = @_;

    if ( !defined($fio->{rxDigest}) ) {
        local(*F);
        #
        # File was exact match, but we still need to verify the
        # MD4 checksum.  Therefore open and read the file.
        #
        $fio->{rxDigest} = File::RsyncP::Digest->new($fio->{protocol_version});
        $fio->{rxDigest}->add(pack("V", $fio->{checksumSeed}));
        if ( open(F, $fio->{rxFile}{localName}) ) {
            $fio->{rxInFd} = *F;
	    while ( sysread($fio->{rxInFd}, my $data, 4 * 65536) > 0 ) {
		$fio->{rxDigest}->add($data);
		$fio->{rxSize} += length($data);
	    }
        } else {
	    # error
	}
        $fio->log("$fio->{rxFile}{name}: got exact match")
                        if ( $fio->{logLevel} >= 5 );
    }
    close($fio->{rxInFd})  if ( defined($fio->{rxInFd}) );
    close($fio->{rxOutFd}) if ( defined($fio->{rxOutFd}) );
    my $newDigest = $fio->{rxDigest}->digest;
    if ( $fio->{logLevel} >= 3 ) {
        my $md4Str = unpack("H*", $md4);
        my $newStr = unpack("H*", $newDigest);
        $fio->log("$fio->{rxFile}{name}: got digests $md4Str vs $newStr")
    }
    if ( $md4 eq $newDigest ) {
        #
        # Nothing to do if there is no output file
        #
        if ( !defined($fio->{rxOutFd}) ) {
            $fio->log("$fio->{rxFile}{name}: nothing to do")
                        if ( $fio->{logLevel} >= 5 );
	    return $fio->attribSet($fio->{rxFile});
        }

        #
        # First rename the original file (in case the rename below fails)
        # to a unique temporary name.
        #
	my $oldFile;
	if ( -e $fio->{rxFile}{localName} ) {
	    for ( my $i = 0 ; ; $i++ ) {
		$oldFile = "$fio->{rxFile}{localName}__old__$$.$i";
		last if ( !-e $oldFile );
	    }
	    $fio->log("$fio->{rxFile}{name}: unlinking/renaming")
			if ( $fio->{logLevel} >= 5 );
	    if ( !rename($fio->{rxFile}{localName}, $oldFile) ) {
		$fio->log("Can't rename $fio->{rxFile}{localName}"
			  . " to $oldFile");
		CORE::unlink($fio->{rxTmpFile});
		return -1;
	    }
	}
        if ( !rename($fio->{rxTmpFile}, $fio->{rxFile}{localName}) ) {
            #
            # Restore old file
            #
            if ( !rename($oldFile, $fio->{rxFile}{localName}) ) {
                $fio->log("Can't retore original file $oldFile after rename"
                          . " of $fio->{rxTmpFile} failed");
            } else {
                $fio->log("Can't rename $fio->{rxTmpFile} to"
                          . " $fio->{rxFile}{localName}");
            }
            return -1;
        }
	if ( defined($oldFile) && CORE::unlink($oldFile) != 1 ) {
            $fio->log("Can't unlink old file $oldFile");
            return -1;
        }
    } else {
        $fio->log("$fio->{rxFile}{name}: md4 doesn't match")
                    if ( $fio->{logLevel} >= 1 );
        CORE::unlink($fio->{rxTmpFile}) if ( defined($fio->{rxTmpFile}) );
        return 1;
    }
    delete($fio->{rxDigest});
    $fio->{rxFile}{size} = $fio->{rxSize};
    return $fio->attribSet($fio->{rxFile});
}

sub fileListEltSend
{
    my($fio, $name, $fList, $outputFunc) = @_;
    my @s;
    my $extra = {};

    (my $n = $name) =~ s/^\Q$fio->{localDir}/$fio->{remoteDir}/;
    if ( -l $name ) {
	@s = lstat($name);
	$extra = {
	    %$extra,
            link => readlink($name),
        };
    } else {
	@s = stat($name);
    }
    if ( $fio->{preserve_hard_links}
            && ($s[2] & S_IFMT) == S_IFREG
            && ($fio->{protocol_version} < 27 || $s[3] > 1) ) {
	$extra = {
	    %$extra,
            dev   => $s[0],
            inode => $s[1],
        };
    }
    $fio->log("fileList send $name (remote=$n)") if ( $fio->{logLevel} >= 3 );
    $fList->encode({
            name  => $n,
            mode  => $s[2],
            uid   => $s[4],
            gid   => $s[5],
            rdev  => $s[6],
            size  => $s[7],
            mtime => $s[9],
	    %$extra,
        });
    &$outputFunc($fList->encodeData);
}

sub fileListSend
{
    my($fio, $flist, $outputFunc) = @_;

    find({wanted => sub {
                $fio->fileListEltSend($File::Find::name, $flist, $outputFunc);
          },
          no_chdir => 1
      }, $fio->{localDir});
}

sub finish
{
    my($fio, $isChild) = @_;

    return;
}

#
# Default log handler
#
sub logHandler
{
    my($str) = @_;

    print(STDERR $str, "\n");
}

#
# Handle one or more log messages
#
sub log
{
    my($fio, @logStr) = @_;

    foreach my $str ( @logStr ) {
        next if ( $str eq "" );
        $fio->{logHandler}->($str);
    }
}

1;
__END__

=head1 NAME

File::RsyncP::FileIO - Perl Rsync client file system IO

=head1 SYNOPSIS

    use File::RsyncP::FileIO;

    my $rs = File::RsyncP->new({
                logLevel   => 1,
                rsyncCmd => ["/bin/rsh", $host,  "-l", $user, "/bin/rsync"],
                rsyncArgs  => [qw(
                        --numeric-ids
                        --perms
                        --owner
                        --group
                        --devices
                        --links
                        --ignore-times
                        --block-size=700
                        --relative
                        --recursive
                        -v
                    )],
                logHandler => sub {
			my($str) = @_;    
			print MyHandler "log: $str\n";
		    };
                fio        => File::RsyncP::FileIO->new({
                                logLevel   => 1,
                            });

            });

=head1 DESCRIPTION

File::RsyncP::FileIO contains all of the file system access functions
needed by File::RsyncP.  This functionality is relegated to this
module so it can be subclassed or replaced by different code for
applications where an rsync interface is provided for non-file system
data (eg: databases).

File::RsyncP::FileIO provides the following functions.

=head2 Setup and utility functions

=over 4

=item new({ options... })

Creates a new File::RsyncP::FileIO object.  The single argument is
a hashref of options:

=over 4

=item blockSize

Defaults to 700.  Can be set later using the blockSize function.

=item logLevel

Defaults to 0.  Controls the verbosity of FileIO operations.

=item digest

Defaults to File::RsyncP::Digest->new.  No need to override.

=item checksumSeed

The checksum seed used in digest calculations.  Defaults to 0.
The server-side Rsync generates a checksum seed and sends it to
the client.  This value is usually set later, after the checksum
seed is received from the remote rsync, via the checksumSeed function.

=item logHandler

A subroutine reference to a function that handles all the log
messages.  The default is a subroutine that prints the messages
to STDERR.

=back

=item blockSize($value)

Set the block size to the new value, in case it wasn't set via the
blockSize option to new().

=item checksumSeed($seed)

Set the checksum seed used in digest calculations to the new value.
Usually this value isn't known when new() is called, so it is necessary
to set it later via this function.

=item logHandlerSet

Set the log handler callback function.  Usually this value is specified
via new(), but it can be changed later via this function.

=item dirs($localDir, $remoteDir)

Specify the local and remote directories.

=item log(@msg)

Save one (or more) messages for logging purposes.

=item statsGet

Return an optional hashref of statistics compiled by the FileIO object.
These values are opaquely passed up to File::RsyncP.

=item finish($isChild)

Do any necessary finish-up processing.  The $isChild argument is true
if this is the child process (remember the receiving side has two
processes: the child receives the file deltas while the parent
generates the block digests).

=back

=head2 Checksum computation functions

=over 4

=item csumStart($f, $needMD4)

Get ready to generate block checksums for the given file.  The argument
is a hashref typically returned by File::RsyncP::FileList->get.
Typically this opens the underlying file and creates a
File::RsyncP::Digest object.  If $needMD4 is non-zero, then csumEnd()
will return the file MD4 digest.

=item csumGet($num, $csumLen, $blockSize)

Return $num bkocks work of checksums with the MD4 checksum length of
$csumLen (typically 2 or 16), with a block size of $blockSize.
Typically this reads the file and calls File::RsyncP::Digest->blockDigest.

=item csumEnd()

Finish up the checksum calculation.  Typically closes the underlying file.
Note that csumStart, csumGet, csumEnd are called in strict order so they
don't need to be reentrant (ie: there is only one csum done at a time).
If csumStart() was called with $needMD4 then csumEnd() will return the
file MD4 digest.

=back

=head2 File reading functions

There are used for sending files (currently sending files doesn't
implement deltas; it behaves as though --whole-file was specified):

=over 4

=item readStart($f)

Get ready to read the given file.  The argument is a hashref typically
returned by File::RsyncP::FileList->get.
Typically this opens the underlying file.

=item read($num)

Read $num bytes from the file.

=item readEnd()

Finish up the read operation.  Typically closes the underlying file.
Note that readStart, readGet, readEnd are called in strict order so they
don't need to be reentrant (ie: there is only one read done at a time).

=back

=head2 File operations

=over 4

=item attribGet($f)

Return the attributes for the given file as a hashref.  The argument is a
hashref typically returned by File::RsyncP::FileList->get.

=item attribSet($f, $placeHolder)

Set the attributes for the given file.  The argument is a hashref
typically returned by File::RsyncP::FileList->get.  If $placeHolder
is true then don't do anything.  Returns undef on success.

=item makePath($f)

Create the directory specified by $f.  The argument is a hashref
typically returned by File::RsyncP::FileList->get.  Returns undef
on success.

=item makeSpecial($f)

Create the special file specified by $f.  The argument is a hashref
typically returned by File::RsyncP::FileList->get.  Returns undef on
success.

=item unlink($remotePath)

Unlink the file or directory corresponding to the given remote path.

=item ignoreAttrOnFile($f)

Normally should return undef, meaning use the default setting of
ignore-times.  Otherwise, if this function returns zero or non-zero, the
returned value  overrides the setting of ignore-times for this file.
The argument is a hashref typically returned by File::RsyncP::FileList->get.
See the doPartial option in File::RsyncP->new().

=back

=head2 File delta receiving functions

These functions are only called when we are receiving files.
They are called by the child process.

=over 4

=item fileDeltaRxStart($f, $cnt, $size, $remainder)

Start the receiving of file deltas for file $f, a hashref typically
returned by File::RsyncP::FileList->get.  The remaining arguments
are the number of blocks, size of blocks, and size of the last
(partial) block as generated by the parent on the receiving side
(they are not the values the new file on the sending side).
Returns undef on success.

=item fileDeltaRxNext($blk, $newData)

This function is called repeatedly as the file is constructed.
Exactly one of $blk and $newData are defined.  If $blk is defined
it is an integer that specifies which block of the original file
should be written at this point.  If $newData is defined, it is
literal data (that didn't match any blocks) that should be written
at this point.

=item fileDeltaRxDone($md4)

Finish processing of the file deltas for this file.  $md4 is the MD4
digest of the sent file.  It should be compared against the MD4 digest
of the reconstructed file.
Returns undef on success, 1 if the file's MD4 didn't agree (meaning
it should be repeated for phase 2), and negative on error.

=back

=head2 File list sending function

=over 4

=item fileListSend($fileList, $outputFunc)

Generate the file list (by calling $fileList->encode for every file
to be sent) and call the output function $outputFunc with the output
data by calling

    &$outputFunc($fileList->encodeData);

=back

=head1 AUTHOR

File::RsyncP::FileList was written by Craig Barratt
<cbarratt@users.sourceforge.net> based on rsync 2.5.5.

Rsync was written by Andrew Tridgell <tridge@samba.org>
and Paul Mackerras.  It is available under a GPL license.
See http://rsync.samba.org

=head1 LICENSE

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License in the
LICENSE file along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.

=head1 SEE ALSO

See L<http://perlrsync.sourceforge.net> for File::RsyncP's SourceForge
home page.

See L<File::RsyncP>, L<File::RsyncP::Digest>, and
L<File::RsyncP::FileList>.

Also see BackupPC's lib/BackupPC/Xfer/RsyncFileIO.pm for an example
of another implementation of File::RsyncP::FileIO, in fact one that
is more tested than the default File::RsyncP::FileIO.pm.

=cut