<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">##- Nanar &lt;nanardon@mandrake.org&gt;
##-
##- 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, 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.

package Packdrakeng;

use strict;
use warnings;
use POSIX qw(O_WRONLY O_TRUNC O_CREAT O_RDONLY O_APPEND);

(our $VERSION) = q$Id: Packdrakeng.pm,v 1.27 2005/04/04 15:31:54 prigaux Exp $ =~ /(\d+\.\d+)/;

my  ($toc_header, $toc_footer) =
    ('cz[0',      '0]cz');

# File::Temp qw(tempfile) hack to not require it
sub tempfile {
    my ($count, $fname, $handle) = (0, undef, undef);
    do {
        ++$count &gt; 10 and return (undef, undef);
        $fname = sprintf("%s/packdrakeng.%s.%s",
            $ENV{TMP} || '/tmp',
            $$,
            # Generating an random name
            join("", map { $_=rand(51); $_ += $_ &gt; 25 &amp;&amp; $_ &lt; 32 ? 91 : 65 ; chr($_) } (0 .. 4)));
    } while ( ! sysopen($handle, $fname, O_WRONLY | O_APPEND | O_CREAT));
    ($handle, $fname)
}

# File::Path hack to not require it
sub mkpath {
    my ($path) = @_;
    $path =~ s:/*$::; # removing leading '/'
    -d $path and return 1;
    # need parent creation ?
    if (index($path, '/') &gt; 0) {
        mkpath(substr($path, 0, rindex($path, '/'))) or return 0;
    }
    mkdir($path)
}

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

    my $pack = {
        filename =&gt; $options{archive},

        compress_method =&gt; $options{compress},
        uncompress_method =&gt; $options{uncompress},
        force_extern =&gt; $options{extern} || 0, # Don't use perl-zlib
        use_extern =&gt; 1, # default behaviour, informative only
        noargs =&gt; $options{noargs},

        # compression level, aka -X gzip or bzip option
        level =&gt; defined($options{comp_level}) ? $options{comp_level} : 6,

        # A compressed block will contain 400k of compressed data
        block_size =&gt; defined($options{block_size}) ? $options{block_size} : 400 * 1024, 
        bufsize =&gt; $options{bufsize} || 65536, # Arbitrary buffer size to read files

        # Internal data
        handle =&gt; undef, # Archive handle

        # Toc information
        files =&gt; {}, # filename =&gt; { off, size, coff, csize }
        dir =&gt; {}, # dir =&gt; no matter what value
        'symlink' =&gt; {}, # file =&gt; link

        coff =&gt; 0, # end of current compressed data

        # Compression sub
        subcompress =&gt; \&amp;extern_compress,
        subuncompress =&gt; \&amp;extern_uncompress,
        direct_write =&gt; 0, # Define if wrapper write directly in archive and not into temp file

        # Data we need keep in memory to achieve the storage
        current_block_files =&gt; {}, # Files in pending compressed block
        current_block_csize =&gt; 0,  # Actual size in pending compressed block
        current_block_coff =&gt; 0,   # The block block location (offset)
        current_block_off =&gt; 0,    # Actual uncompressed file offset within the pending block

        cstream_data =&gt; undef,     # Wrapper data we need to keep in memory (compression)
        ustream_data =&gt; undef,     # Wrapper data we need to keep in memory (uncompression)

        # log and verbose function:
        log =&gt; $options{quiet} ? sub {} : sub { my @w = @_; $w[0] .= "\n"; printf STDERR @w },
        debug =&gt; $options{debug} ? sub { my @w =@_; $w[0] = "Debug: $w[0]\n"; printf STDERR @w } : sub {},
    };

    bless($pack, $class)
}

sub new {
    my ($class, %options) = @_;
    my $pack = _new($class, %options);
    sysopen($pack-&gt;{handle}, $pack-&gt;{filename}, O_WRONLY | O_TRUNC | O_CREAT) or return undef;
    $pack-&gt;choose_compression_method();
    $pack-&gt;{need_build_toc} = 1;
    $pack-&gt;{debug}-&gt;("Creating new archive with '%s' / '%s'%s.",
        $pack-&gt;{compress_method}, $pack-&gt;{uncompress_method},
        $pack-&gt;{use_extern} ? "" : " (internal compression)");
    $pack
}

sub open {
    my ($class, %options) = @_;
    my $pack = _new($class, %options);
    sysopen($pack-&gt;{handle}, $pack-&gt;{filename}, O_RDONLY) or return undef;
    $pack-&gt;read_toc() or return undef;
    $pack-&gt;{debug}-&gt;("Opening archive with '%s' / '%s'%s.",
        $pack-&gt;{compress_method}, $pack-&gt;{uncompress_method},
        $pack-&gt;{use_extern} ? "" : " (internal compression)");
    $pack
}

# look $pack-&gt;{(un)compressed_method} and setup functions/commands to use
# Have some facility about detecting we want gzip/bzip
sub choose_compression_method {
    my ($pack) = @_;

    (!defined($pack-&gt;{compress_method}) &amp;&amp; !defined($pack-&gt;{uncompress_method}))
        and $pack-&gt;{compress_method} = "gzip";
    my $test_method = $pack-&gt;{compress_method} || $pack-&gt;{uncompress_method};

    $test_method =~ m/^bzip2|^bunzip2/ and do {
        $pack-&gt;{compress_method} ||= "bzip2";
    };
    $test_method =~ m/^gzip|^gunzip/ and do {
        $pack-&gt;{compress_method} ||= "gzip";
        if (!$pack-&gt;{force_extern}) {
            eval {
		require Compress::Zlib; #- need this to ensure that Packdrakeng::zlib will load properly
		require Packdrakeng::zlib;
		$pack-&gt;{subcompress} = \&amp;Packdrakeng::zlib::gzip_compress;
		$pack-&gt;{subuncompress} = \&amp;Packdrakeng::zlib::gzip_uncompress;
		$pack-&gt;{use_extern} = 0;
		$pack-&gt;{direct_write} = 1;
            };
        }
    };
    if (!$pack-&gt;{noargs}) {
        $pack-&gt;{uncompress_method} ||= "$pack-&gt;{compress_method} -d";
        $pack-&gt;{compress_method} = $pack-&gt;{compress_method} ? "$pack-&gt;{compress_method} -$pack-&gt;{level}" : "";
    }
}

sub DESTROY {
    my ($pack) = @_;
    $pack-&gt;{subuncompress}($pack, undef, undef);
    $pack-&gt;build_toc();
    close($pack-&gt;{handle}) if $pack-&gt;{handle};
    close($pack-&gt;{ustream_data}{handle}) if $pack-&gt;{ustream_data}{handle};
}

# Flush current compressed block
# Write
sub build_toc {
    my ($pack) = @_;
    $pack-&gt;{need_build_toc} or return 1;
    $pack-&gt;end_block();
    $pack-&gt;end_seek() or do {
	$pack-&gt;{log}("Can't seek into archive");
	return 0;
    };
    my ($toc_length, $cf, $cd, $cl) = (0, 0, 0, 0);

    foreach my $entry (keys %{$pack-&gt;{'dir'}}) {
	$cd++;
	my $w = syswrite($pack-&gt;{handle}, $entry . "\n") or do {
	    $pack-&gt;{log}("Can't write toc into archive");
	    return 0;
	};
	$toc_length += $w;
    }
    foreach my $entry (keys %{$pack-&gt;{'symlink'}}) {
	$cl++;
	my $w = syswrite($pack-&gt;{handle}, sprintf("%s\n%s\n", $entry, $pack-&gt;{'symlink'}{$entry})) or do {
	    $pack-&gt;{log}("Can't write toc into archive");
	    return 0;
	};
	$toc_length += $w
    }
    foreach my $entry (sort keys %{$pack-&gt;{files}}) {
	$cf++;
	my $w = syswrite($pack-&gt;{handle}, $entry ."\n") or do {
	    $pack-&gt;{log}("Can't write toc into archive");
	    return 0;
	};
	$toc_length += $w;
    }
    foreach my $file (sort keys %{$pack-&gt;{files}}) {
	my $entry = $pack-&gt;{files}{$file};
	syswrite($pack-&gt;{handle}, pack('NNNN', $entry-&gt;{coff}, $entry-&gt;{csize}, $entry-&gt;{off}, $entry-&gt;{size})) or do {
	    $pack-&gt;{log}("Can't write toc into archive");
	    return 0;
	};
    }
    syswrite($pack-&gt;{handle}, pack("a4NNNNa40a4",
    $toc_header,
    $cd, $cl, $cf,
    $toc_length,
    $pack-&gt;{uncompress_method},
    $toc_footer)) or do {
	$pack-&gt;{log}("Can't write toc into archive");
	return 0;
    };
    1;
}

sub read_toc {
    my ($pack) = @_;
    sysseek($pack-&gt;{handle}, -64, 2) ; #or return 0;
    sysread($pack-&gt;{handle}, my $buf, 64);# == 64 or return 0;
    my ($header, $toc_d_count, $toc_l_count, $toc_f_count, $toc_str_size, $uncompress, $trailer) =
        unpack("a4NNNNZ40a4", $buf);
    $header eq $toc_header &amp;&amp; $trailer eq $toc_footer or do {
        $pack-&gt;{log}("Error reading toc: wrong header/trailer");
        return 0;
    };

    $pack-&gt;{uncompress_method} ||= $uncompress;
    $pack-&gt;choose_compression_method();

    sysseek($pack-&gt;{handle}, -64 - ($toc_str_size + 16 * $toc_f_count) ,2);
    sysread($pack-&gt;{handle}, my $fileslist, $toc_str_size);
    my @filenames = split("\n", $fileslist);
    sysread($pack-&gt;{handle}, my $sizes_offsets, 16 * $toc_f_count);
    my @size_offset = unpack("N" . 4*$toc_f_count, $sizes_offsets);

    foreach (1 .. $toc_d_count) {
        $pack-&gt;{dir}{shift(@filenames)} = 1;
    }
    foreach (1 .. $toc_l_count) {
        my $n = shift(@filenames);
        $pack-&gt;{'symlink'}{$n} = shift(@filenames);
    }

    foreach (1 .. $toc_f_count) {
        my $f = shift(@filenames);
        $pack-&gt;{files}{$f}{coff} = shift(@size_offset);
        $pack-&gt;{files}{$f}{csize} = shift(@size_offset);
        $pack-&gt;{files}{$f}{off} = shift(@size_offset);
        $pack-&gt;{files}{$f}{size} = shift(@size_offset);
        # looking for offset for this archive
        $pack-&gt;{files}{$f}{coff} + $pack-&gt;{files}{$f}{csize} &gt; $pack-&gt;{coff}
	    and $pack-&gt;{coff} = $pack-&gt;{files}{$f}{coff} + $pack-&gt;{files}{$f}{csize};
    }
    $pack-&gt;{toc_f_count} = $toc_f_count;
    1;
}

sub sort_files_by_packing {
    my ($pack, @files) = @_;
    sort {
        defined($pack-&gt;{files}{$a}) &amp;&amp; defined($pack-&gt;{files}{$b}) ?
            ($pack-&gt;{files}{$a}{coff} == $pack-&gt;{files}{$b}{coff} ?
            $pack-&gt;{files}{$a}{off} &lt;=&gt; $pack-&gt;{files}{$b}{off} :
            $pack-&gt;{files}{$a}{coff} &lt;=&gt; $pack-&gt;{files}{$b}{coff}) :
        $a cmp $b
    } @files;
}

# Goto to the end of written compressed data
sub end_seek {
    my ($pack) = @_;
    my $seekvalue = $pack-&gt;{direct_write} ? $pack-&gt;{coff} + $pack-&gt;{current_block_csize} : $pack-&gt;{coff};
    sysseek($pack-&gt;{handle}, $seekvalue, 0) == $seekvalue
}

#- To terminate a compressed block, flush the pending compressed data,
#- fill toc data still unknown
sub end_block {
    my ($pack) = @_;
    $pack-&gt;end_seek() or return 0;
    my (undef, $csize) = $pack-&gt;{subcompress}($pack, undef);
    $pack-&gt;{current_block_csize} += $csize;
    foreach (keys %{$pack-&gt;{current_block_files}}) {
        $pack-&gt;{files}{$_} = $pack-&gt;{current_block_files}{$_};
        $pack-&gt;{files}{$_}{csize} = $pack-&gt;{current_block_csize};
    }
    $pack-&gt;{coff} += $pack-&gt;{current_block_csize};
    $pack-&gt;{current_block_coff} += $pack-&gt;{current_block_csize};
    $pack-&gt;{current_block_csize} = 0;
    $pack-&gt;{current_block_files} = {};
    $pack-&gt;{current_block_off} = 0;
}

#######################
# Compression wrapper #
#######################

sub extern_compress {
    my ($pack, $sourcefh) = @_;
    my ($insize, $outsize, $filesize) = (0, 0, 0); # aka uncompressed / compressed data length
    my $hout; # handle for gzip

    if (defined($pack-&gt;{cstream_data})) {
        $hout = $pack-&gt;{cstream_data}{hout};
        $filesize = (stat($pack-&gt;{cstream_data}{file_block}))[7];
    }
    if (defined($sourcefh)) {
        if (!defined($pack-&gt;{cstream_data})) {
            my $hin;
            ($hin, $pack-&gt;{cstream_data}{file_block}) = tempfile();
            close($hin); # ensure the flush
            $pack-&gt;{cstream_data}{pid} = CORE::open($hout,
                "|$pack-&gt;{compress_method} &gt; $pack-&gt;{cstream_data}{file_block}") or do {
                $pack-&gt;{log}("Unable to start $pack-&gt;{compress_method}");
                return 0, 0;
            };
            $pack-&gt;{cstream_data}{hout} = $hout;
            binmode $hout;
        }
        # until we have data to push or data to read
        while (my $length = sysread($sourcefh, my $data, $pack-&gt;{bufsize})) {
            # pushing data to compressor
            (my $l = syswrite($hout, $data)) == $length or do {
                $pack-&gt;{log}("Can't push all data to compressor");
            };
            $insize += $l;
            $outsize = (stat($pack-&gt;{cstream_data}{file_block}))[7];
        }
    } elsif (defined($pack-&gt;{cstream_data})) {
        # If $sourcefh is not set, this mean we want a flush(), for end_block()
        close($hout);
        waitpid $pack-&gt;{cstream_data}{pid}, 0;
        sysopen(my $hin, $pack-&gt;{cstream_data}{file_block}, O_RDONLY) or do {
            $pack-&gt;{log}("Can't open temp block file");
            return 0, 0;
        };
        $outsize = (stat($pack-&gt;{cstream_data}{file_block}))[7];
        unlink($pack-&gt;{cstream_data}{file_block});
        while (my $lenght = sysread($hin, my $data, $pack-&gt;{bufsize})) {
            (my $l = syswrite($pack-&gt;{handle}, $data)) == $lenght or do {
                $pack-&gt;{log}("Can't write all data in archive");
            };
        }
        close($hin);
        $pack-&gt;{cstream_data} = undef;
    }
    ($insize, $outsize - $pack-&gt;{current_block_csize})
}

sub extern_uncompress {
    my ($pack, $destfh, $fileinfo) = @_;

    if (defined($pack-&gt;{ustream_data}) &amp;&amp; (
            !defined($fileinfo) ||
            ($fileinfo-&gt;{coff} != $pack-&gt;{ustream_data}{coff} || $fileinfo-&gt;{off} &lt; $pack-&gt;{ustream_data}{off})
        )) {
        close($pack-&gt;{ustream_data}{handle});
        unlink($pack-&gt;{ustream_data}{tempname}); # deleting temp file
        $pack-&gt;{ustream_data} = undef;
    }
    
    defined($fileinfo) or return 0;
    # We have to first extract the block to a temp file, burk !
    
    if (!defined($pack-&gt;{ustream_data})) {
        my $tempfh;
        $pack-&gt;{ustream_data}{coff} = $fileinfo-&gt;{coff};
        $pack-&gt;{ustream_data}{read} = 0;

        ($tempfh, $pack-&gt;{ustream_data}{tempname}) = tempfile();

        my $cread = 0;
        while ($cread &lt; $fileinfo-&gt;{csize}) {
            my $cl = sysread($pack-&gt;{handle}, my $data,
                $cread + $pack-&gt;{bufsize} &gt; $fileinfo-&gt;{csize} ?
                    $fileinfo-&gt;{csize} - $cread :
                    $pack-&gt;{bufsize}) or do {
                    $pack-&gt;{log}("Unexpected end of file");
                    close($tempfh);
                    unlink($pack-&gt;{ustream_data}{tempname});
                    $pack-&gt;{ustream_data} = undef;
                    return -1;
            };
            $cread += $cl;
            syswrite($tempfh, $data) == length($data) or do {
                $pack-&gt;{log}("Can't write all data into temp file");
                close($tempfh);
                unlink($pack-&gt;{ustream_data}{tempname});
                $pack-&gt;{ustream_data} = undef;
                return -1;
            };
        }
        close($tempfh);
        
	my $cmd = $pack-&gt;{uncompress_method} eq 'gzip -d' || $pack-&gt;{uncompress_method} eq 'bzip2 -d' ?
	  "$pack-&gt;{uncompress_method} -c '$pack-&gt;{ustream_data}{tempname}'" :
	  "$pack-&gt;{uncompress_method} &lt;  '$pack-&gt;{ustream_data}{tempname}'";
        CORE::open($pack-&gt;{ustream_data}{handle}, "$cmd |") or do {
            $pack-&gt;{log}("Can't start $pack-&gt;{uncompress_method} to uncompress data");
            unlink($pack-&gt;{ustream_data}{tempname});
            $pack-&gt;{ustream_data} = undef;
            return -1;
        };
        binmode($pack-&gt;{ustream_data}{handle});
    }

    my $byteswritten = 0;
    $pack-&gt;{ustream_data}{off} = $fileinfo-&gt;{off};
    #my $read = 0;

    while ($byteswritten &lt; $fileinfo-&gt;{size}) {
        my $data = $pack-&gt;{ustream_data}{buf};
        $pack-&gt;{ustream_data}{buf} = undef;
        my $length;
        if (!defined($data)) {
            $length = sysread($pack-&gt;{ustream_data}{handle}, $data, $pack-&gt;{bufsize}) or do {
                $pack-&gt;{log}("Unexpected end of stream $pack-&gt;{ustream_data}{tempname}");
                unlink($pack-&gt;{ustream_data}{tempname});
                close($pack-&gt;{ustream_data}{handle});
                $pack-&gt;{ustream_data} = undef;
                return -1;
            };
        } else {
            $length = length($data);
        }

        if ($pack-&gt;{ustream_data}{read} &lt; $fileinfo-&gt;{off} &amp;&amp; $pack-&gt;{ustream_data}{read} + $length &gt; $fileinfo-&gt;{off}) {
            $data = substr($data, $fileinfo-&gt;{off} - $pack-&gt;{ustream_data}{read});
        }
        $pack-&gt;{ustream_data}{read} += $length;
        if ($pack-&gt;{ustream_data}{read} &lt;= $fileinfo-&gt;{off}) { next }

        my $bw;
        if ($byteswritten + length($data) &gt; $fileinfo-&gt;{size}) {
            $bw = $fileinfo-&gt;{size} - $byteswritten;
            $pack-&gt;{ustream_data}{buf} = substr($data, $bw); # keeping track of unwritten uncompressed data
            $pack-&gt;{ustream_data}{read} -= length($pack-&gt;{ustream_data}{buf});
        } else {
            $bw = length($data);
        }
        
        syswrite($destfh, $data, $bw) == $bw or do {
            $pack-&gt;{log}("Can't write data into dest");
            return -1;
        };
        $byteswritten += $bw;
    }

    $byteswritten

}

###################
# Debug functions #
###################

# This function extracts in $dest the whole block containing $file, can be useful for debugging
sub extract_block {
    my ($pack, $dest, $file) = @_;

    sysopen(my $handle, $dest, O_WRONLY | O_TRUNC | O_CREAT) or do {
        $pack-&gt;{log}("Can't open $dest");
        return -1;
    };

    sysseek($pack-&gt;{handle}, $pack-&gt;{files}{$file}-&gt;{coff}, 0) == $pack-&gt;{files}{$file}-&gt;{coff} or do {
        $pack-&gt;{log}("Can't seek to offset $pack-&gt;{files}{$file}-&gt;{coff}");
        close($handle);
        return -1;
    };

    {
    my $l;
    $l = sysread($pack-&gt;{handle}, my $buf, $pack-&gt;{files}{$file}-&gt;{csize}) == $pack-&gt;{files}{$file}-&gt;{csize} or $pack-&gt;{log}("Read only $l / $pack-&gt;{files}{$file}-&gt;{csize} bytes");
    syswrite($handle, $buf);
    }

    foreach ($pack-&gt;sort_files_by_packing(keys %{$pack-&gt;{files}})) {
        $pack-&gt;{files}{$_}{coff} == $pack-&gt;{files}{$file}-&gt;{coff} or next;
    }

    close($handle);

}

##################################
# Really working functions       #
# Aka function people should use #
##################################

sub add_virtual {
    my ($pack, $type, $filename, $data) = @_;
    $type eq 'l' and do {
        $pack-&gt;{'symlink'}{$filename} = $data;
        $pack-&gt;{need_build_toc} = 1;
        return 1;
    };
    $type eq 'd' and do {
        $pack-&gt;{dir}{$filename}++;
        $pack-&gt;{need_build_toc} = 1;
        return 1;
    };
    $type eq 'f' and do {
        # Be sure we are at the end, allow extract + add in only one instance
        $pack-&gt;end_seek() or do {
            $pack-&gt;{log}("Can't seek to offset $pack-&gt;{coff}");
            next;
        };

        my ($size, $csize) = $pack-&gt;{subcompress}($pack, $data);
        $pack-&gt;{current_block_files}{$filename} = {
            size =&gt; $size,
            off =&gt; $pack-&gt;{current_block_off},
            coff =&gt; $pack-&gt;{current_block_coff},
            csize =&gt; -1, # Still unknown, will be fill by end_block
        }; # Storing in toc structure availlable info

        # Updating internal info about current block
        $pack-&gt;{current_block_off} += $size;
        $pack-&gt;{current_block_csize} += $csize;
        $pack-&gt;{need_build_toc} = 1;
        if ($pack-&gt;{block_size} &gt; 0 &amp;&amp; $pack-&gt;{current_block_csize} &gt;= $pack-&gt;{block_size}) {
            $pack-&gt;end_block();
        }
        return 1;
    };
    0
}

sub add {
    my ($pack, $prefix, @files) = @_;
    $prefix ||= "";
    foreach my $file (@files) {
        $file =~ s://+:/:;
        my $srcfile = $prefix ? "$prefix/$file" : $file;
        $pack-&gt;{debug}-&gt;("Adding '%s' as '%s' into archive", $srcfile, $file);

        -l $srcfile and do {
            $pack-&gt;add_virtual('l', $file, readlink($srcfile));
            next;
        };
        -d $srcfile and do { # dir simple case
            $pack-&gt;add_virtual('d', $file);
            next;
        };
        -f $srcfile and do {
            sysopen(my $htocompress, $srcfile, O_RDONLY) or do {
                $pack-&gt;{log}("Can't add $srcfile: $!");
                next;
            };
            $pack-&gt;add_virtual('f', $file, $htocompress);
            close($htocompress);
            next;
        };
        $pack-&gt;{log}("Can't pack $srcfile");
    }
    1;
}

sub extract_virtual {
    my ($pack, $destfh, $filename) = @_;
    defined($pack-&gt;{files}{$filename}) or return -1;
    sysseek($pack-&gt;{handle}, $pack-&gt;{files}{$filename}-&gt;{coff}, 0) == $pack-&gt;{files}{$filename}-&gt;{coff} or do {
        $pack-&gt;{log}("Can't seek to offset $pack-&gt;{files}{$filename}-&gt;{coff}");
        return -1;
    };
    $pack-&gt;{subuncompress}($pack, $destfh, $pack-&gt;{files}{$filename});
}

sub extract {
    my ($pack, $destdir, @files) = @_;
    foreach my $f ($pack-&gt;sort_files_by_packing(@files)) {
        my $dest = $destdir ? "$destdir/$f" : "$f";
        my ($dir) = $dest =~ m!(.*)/.*!;
        if (exists($pack-&gt;{dir}{$f})) {
            -d $dest || mkpath($dest)
            or $pack-&gt;{log}("Unable to create dir $dest: $!");
            next;
        } elsif (exists($pack-&gt;{'symlink'}{$f})) {
            -d $dir || mkpath($dir) or
            $pack-&gt;{log}("Unable to create dir $dest: $!");
            -l $dest and unlink $dest;
            symlink($pack-&gt;{'symlink'}{$f}, $dest)
            or $pack-&gt;{log}("Unable to extract symlink $f: $!");
            next;
        } elsif (exists($pack-&gt;{files}{$f})) {
	        -d $dir || mkpath($dir) or do {
		        $pack-&gt;{log}("Unable to create dir $dir");
	        };
	        if (-l $dest) {
		        unlink($dest) or do {
		            $pack-&gt;{log}("Can't remove link $dest: $!");
		            next; # Don't overwrite a file because where the symlink point to
		        };
	        }
	        sysopen(my $destfh, $dest, O_CREAT | O_TRUNC | O_WRONLY) or do {
    		    $pack-&gt;{log}("Unable to extract $dest");
	        	next;
	        };
	        my $written = $pack-&gt;extract_virtual($destfh, $f);
	        $written == -1 and $pack-&gt;{log}("Unable to extract file $f");
	        close($destfh);
	        next;
        } else {
            $pack-&gt;{log}("Can't find $f in archive");
        }
    }
    1;
}

# Return \@dir, \@files, \@symlink list
sub getcontent {
    my ($pack) = @_;
    return(
        [ keys(%{$pack-&gt;{dir}})],
        [ $pack-&gt;sort_files_by_packing(keys %{$pack-&gt;{files}}) ], 
        [ keys(%{$pack-&gt;{'symlink'}}) ]
    );
}

sub infofile {
    my ($pack, $file) = @_;
    if (defined($pack-&gt;{files}{$file})) {
        return ('f', $pack-&gt;{files}{$file}{size});
    } elsif (defined($pack-&gt;{'symlink'}{$file})) {
        return ('l', $pack-&gt;{'symlink'}{$file});
    } elsif (defined($pack-&gt;{dir}{$file})) {
        return ('d', undef);
    } else {
        return(undef, undef);
    }
}

sub list {
    my ($pack, $handle) = @_;
    $handle ||= *STDOUT;
    foreach my $file (keys %{$pack-&gt;{dir}}) {
        printf "d %13c %s\n", ' ', $file;
    }
    foreach my $file (keys %{$pack-&gt;{'symlink'}}) {
        printf "l %13c %s -&gt; %s\n", ' ', $file, $pack-&gt;{'symlink'}{$file};
    }
    foreach my $file ($pack-&gt;sort_files_by_packing(keys %{$pack-&gt;{files}})) {
        printf "f %12d %s\n", $pack-&gt;{files}{$file}{size}, $file;
    }
}

# Print toc info
sub dumptoc {
    my ($pack, $handle) = @_;
    $handle ||= *STDOUT;
    foreach my $file (keys %{$pack-&gt;{dir}}) {
        printf $handle "d %13c %s\n", ' ', $file;
    }
    foreach my $file (keys %{$pack-&gt;{'symlink'}}) {
        printf $handle "l %13c %s -&gt; %s\n", ' ', $file, $pack-&gt;{'symlink'}{$file};
    }
    foreach my $file ($pack-&gt;sort_files_by_packing(keys %{$pack-&gt;{files}})) {
        printf $handle "f %d %d %d %d %s\n", $pack-&gt;{files}{$file}{size}, $pack-&gt;{files}{$file}{off}, $pack-&gt;{files}{$file}{csize}, $pack-&gt;{files}{$file}{coff}, $file;
    }
}

1;

__END__

=head1 NAME

Packdrakeng - Simple Archive Extractor/Builder

=head1 SYNOPSIS

    use Packdrakeng;

    # creating an archive
    $pack = Packdrakeng-&gt;new(archive =&gt; "myarchive.cz");
    # Adding a few files
    $pack-&gt;add("/path/", "file1", "file2");
    # Adding an unamed file
    open($handle, "file");
    $pack-&gt;add_virtual("filename", $handle);
    close($handle);

    $pack = undef;

    # extracting an archive
    $pack = Packdrakeng-&gt;open(archive =&gt; "myarchive.cz");
    # listing files
    $pack-&gt;list();
    # extracting few files
    $pack-&gt;extract("/path/", "file1", "file2");
    # extracting data into a file handle
    open($handle, "file");
    $pack-&gt;extract_virtual($handle, "filename");
    close($handle);

=head1 DESCRIPTION

C&lt;Packdrakeng&gt; is a simple indexed archive builder and extractor using
standard compression methods.

This module is a from scratch rewrite of the original packdrake. Its format is
fully compatible with old packdrake.

=head1 IMPLEMENTATION

Compressed data are stored by block. For example,

 UncompresseddatA1UncompresseddatA2 UncompresseddatA3UncompresseddatA4
 |--- size  1 ---||--- size  2 ---| |--- size  3 ---||--- size  4 ---|
 |&lt;-offset1       |&lt;-offset2        |&lt;-offset3       |&lt;-offset4

gives:

 CompresseD1CompresseD2 CompresseD3CompresseD4
 |--- c. size 1, 2 ---| |--- c. size 3, 4 ---|
 |&lt;-c. offset 1, 2      |&lt;-c. offset 3, 4

A new block is started when its size exceeds the C&lt;block_size&gt; value.

Compressed data are followed by the toc, ie a simple list of packed files.
Each file name is terminated by the "\n" character:

    dir1
    dir2
    ...
    dirN
    symlink1
    point_file1
    symlink2
    point_file2
    ...
    ...
    symlinkN
    point_fileN
    file1
    file2
    ...
    fileN

The file sizes follows, 4 values are stored for each file:
offset into archive of compressed block, size of compressed block,
offset into block of the file and the file's size.

Finally the archive contains a 64-byte trailer, about the
toc and the archive itself:

    'cz[0', strings 4 bytes
    number of directory, 4 bytes
    number of symlinks, 4 bytes
    number of files, 4 bytes
    the toc size, 4 bytes
    the uncompression command, string of 40 bytes length
    '0]cz', string 4 bytes

=head1 FUNCTIONS

=over 2

=item B&lt;new(%options)&gt;

Creates a new archive.
Options:

=over 4

=item archive

The file name of the archive. If the file doesn't exist, it will be created,
else it will be owerwritten. See C&lt;open&gt;.

=item compress

The application to use to compress, if unspecified, gzip is used.

=item uncompress

The application used to extract data from archive. This option is useless if
you're opening an existing archive (unless you want to force it).
If unset, this value is based on compress command followed by '-d' argument.

=item extern

If you're using gzip, by default Packdrakeng will use perl-zlib to save system
ressources. This option forces Packdrakeng to use the external gzip command. This
has no meaning with other compress programs as internal functions are not implemented
yet.

=item comp_level

The compression level passed as an argument to the compression program. By default,
this is set to 6.

=item block_size

The limit size after which we start a new compressed block. The default value
is 400KB. Set it to 0 to be sure a new block will be started for each packed
files, and -1 to never start a new block. Be aware that a big block size will
slow down the file extraction.

=item quiet

Do not output anything, shut up.

=item debug

Print debug messages.

=back

=item B&lt;open(%options)&gt;

Opens an existing archive for extracting or adding files.

The uncompression command is found into the archive, and the compression
command is deduced from it.

If you add files, a new compressed block will be started even if the
last block is smaller than C&lt;block_size&gt;. If some compression options can't be
found in the archive, the new preference will be applied.

Options are same than the C&lt;new()&gt; function.

=item B&lt;&lt; Packdrakeng-&gt;add_virtual($type, $filename, $data) &gt;&gt;

Add a file into archive according passed information.

$type gives the type of the file:

- 'd', the file will be a directory, store as '$filename'. $data is not use;
- 'l', the file will be a symlink named $filename, pointing to the file whose path
  is given by the string $data;
- 'f', the file is a normal file, $filename will be its name, $data is an handle to
  open file, data will be read from current position to the end of file.

=item B&lt;&lt; Packdrakeng-&gt;add($prefix, @files) &gt;&gt;

Add @files into archive located into $prefix. Only directory, files and symlink
will be added. For each file, the path should be relative to $prefix and is
stored as is.

=item B&lt;&lt; Packdrakeng-&gt;extract_virtual(*HANDLE, $filename) &gt;&gt;

Extract $filename data from archive into the *HANDLE. $filename should be a
normal file.

=item B&lt;&lt; Packdrakeng-&gt;extract($destdir, @files) &gt;&gt;

Extract @files from the archive into $destdir prefix.

=item B&lt;&lt; Packdrakeng-&gt;getcontent() &gt;&gt;

Return 3 arrayref about found files into archive, respectively directory list,
files list and symlink list.

=item B&lt;&lt; Packdrakeng-&gt;infofile($file) &gt;&gt;

Return the type and information about a file into the archive.

- return 'f' and the the size of the file for a plain file
- return 'l' and the point file for a link
- return 'd' and undef for a directory
- return undef if the file can't be found into archive.

=item B&lt;&lt; Packdrakeng-&gt;infofile($handle) &gt;&gt;

Print to $handle (STDOUT if not specified) the content of the archive.

=item B&lt;&lt; Packdrakeng-&gt;dumptoc($handle) &gt;&gt;

Print to $handle (STDOUT if not specified) the table of content of the archive.

=back

=head1 AUTHOR

Olivier Thauvin &lt;nanardon@mandrake.org&gt;

=head1 LICENSE

This program is free software; you can redistribute it and/or
modify it under the terms of 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.

If you do not have a copy of the GNU General Public License write to
the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
MA 02139, USA.

=cut
</pre></body></html>