Unpack.pm

filter: Statementstmt 32.2% 327 / 1014 Branchbran 16.7% 122 / 728 Conditioncond 20.3% 54 / 266 MC/DCmcdc 5.6% 9 / 159 Subroutinesub 65.0% 41 / 63 Podpod 100% 14 / 14 totaltotal 25.2% 567 / 2244 CC 496 SCAR 77.0
CC
496
Cov
25%
mime
7274.5
_run_mime_helper
3906.0
unpack
2868.8
CRAP 2198.3
↑ Summary children_fuser.pl »
1 #
2 # (C) 2010-2014, jnw@cpan.org, all rights reserved.
3 # Distribute under the same license as Perl itself.
4 #
5 #
6 # sudo zypper -v in perl-Compress-Raw-Zlib
7 # -> 'nothing to do'
8 # sudo zypper -v in 'perl-Compress-Raw-Zlib >= 2.027'
9 # -> 'perl' providing 'perl-Compress-Raw-Zlib >= 2.027' is already installed.
10 # sudo zypper -v in --force perl-Compress-Raw-Zlib
11 # -> works,
12 # sudo zypper -v in --from 12 perl-Compress-Raw-Zlib
13 # -> works, if d.l.p is repo #12.
14 #
15 # TODO:
16 # * evaluate File::Extract - Extract Text From Arbitrary File Types
17 # (HTML, PDF, Plain, RTF, Excel)
18 #
19 # * make taint checks really check things, instead of $1 if m{^(.*)$};
20 #
21 # * Implement disk space monitoring.
22 #
23 # * formats:
24 # - use lzmadec/xzdec as fallback to lzcat.
25 # - glest has bzipped tar files named glest-1.0.10-data.tar.bz2.tar;
26 # - Not all suffixes are appended by . e.g. openh323-v1_15_2-src-tar.bz2 is different.
27 # - gzip -dc can unpack old compress .Z, add its mime-type
28 # - java-1_5_0-sun hides zip-files in shell scripts with suffix .bin
29 # - cpio fails on \.delta\.rpm
30 # - rpm files should extract all header info in readable format.
31 # - do we rely on rpm2cpio to handle them all:
32 # rpm -qp --nodigest --nosignature --qf "%{PAYLOADCOMPRESSOR}" $f
33 # - m{\.(otf|ttf|ps|eps)$}i
34 # - application/x-frame # xorg-modular/doc/xorg-docs/specs/XPRINT/xp_libraryTOC.doc
35 #
36 # * blacklisting?
37 # # th_en_US.dat is an 11MB thesaurus in OOo
38 # skip if $from =~ m{(/(ustar|pax)\-big\-\d+g\.tar\.bz2|/th_en_US\.dat|/testtar\.tar|\.html\.(ru|ja|ko\.euc-kr|fr|es|cz))$}
39 #
40 # * use LWP::Simple::getstore() if $archive =~ m{^\w+://}
41 # * application/x-debian-package is a 'application/x-archive' -> (ar xv /dev/stdin) < $qufrom";
42 # * application/x-iso9660 -> "isoinfo -d -i %(src)s"
43 # * PDF improvement: okular says: 'this document contains embedded files.' How can we grab those?
44  
45 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
46 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
47  
48 package File::Unpack;
49  
50 BEGIN
51 {
52 # Requires: shared-mime-info
53 9 ▶ eval 'use File::LibMagic;'; # only needed in mime(); mime() dies, if missing
Subroutine BEGIN: called CC=1 SCAR=1.2
Subroutine BEGIN: called CC=1 SCAR=1.2
54 9 ▶ eval 'use File::MimeInfo::Magic;'; # only needed in mime(); okay, if missing.
Subroutine BEGIN: called CC=1 SCAR=0.0
55 # unless builtin!
56 9 ▶ eval 'use Compress::Raw::Lzma;'; # only needed in mime(); for finding lzma.
Subroutine BEGIN: called CC=1 SCAR=1.2
57 9 ▶ eval 'use Compress::Raw::Bzip2;'; # only needed in mime(); for finding second level types
Subroutine BEGIN: called CC=1 SCAR=0.0
58 9 ▶ eval 'use Compress::Raw::Zlib;'; # only needed in mime(); for finding second level types
Subroutine BEGIN: called CC=1 SCAR=0.0
59 9 ▶ eval 'use BSD::Resource;'; # setrlimit
Subroutine BEGIN: called CC=1 SCAR=0.0
60 9 ▶ eval 'use Filesys::Statvfs;'; # statvfs();
Subroutine BEGIN: called CC=1 SCAR=0.0
61 }
62  
63 9 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
64 9 ▶use File::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
65 9 ▶use File::Temp (); # tempdir() in _run_mime_helper.
Subroutine BEGIN: called CC=1 SCAR=0.0
66 9 ▶use File::Copy ();
Subroutine BEGIN: called CC=1 SCAR=0.0
67 9 ▶use File::Compare ();
Subroutine BEGIN: called CC=1 SCAR=0.0
68 9 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
69 9 ▶use String::ShellQuote; # used in _prep_configdir
Subroutine BEGIN: called CC=1 SCAR=0.0
70 9 ▶use IPC::Run; # implements File::Unpack::run()
Subroutine BEGIN: called CC=1 SCAR=0.0
71 9 ▶use Text::Sprintf::Named; # used to parse @builtin_mime_helpers
Subroutine BEGIN: called CC=1 SCAR=0.0
72 9 ▶use Cwd 'getcwd'; # run(), moves us there and back.
Subroutine BEGIN: called CC=1 SCAR=0.0
73 9 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
74 9 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
75  
76 =head1 NAME
77  
78 File::Unpack - A strong bz2/gz/zip/tar/cpio/rpm/deb/cab/lzma/7z/rar/... archive unpacker, based on mime-types
79  
80 =head1 VERSION
81  
82 Version 0.69
83 =cut
84  
85 # We'll have 1.x versions only after minfree() has a baseline implementation.
86 # Please run perl Makefile.PL after changing the version here.
87 9 our $VERSION = '0.69';
88  
89 9 POSIX::setlocale(&POSIX::LC_ALL, 'C');
90 9 $ENV{PATH} = '/usr/bin:/bin';
91 9 $ENV{SHELL} = '/bin/sh';
92 9 delete $ENV{ENV};
93  
94 # what we name the temporary directories, while helpers are working.
95 9 my $TMPDIR_TEMPL = '_fu_XXXXX';
96  
97 # no longer used by the tick-tick ticker to show where we are.
98 # my $lsof = '/usr/bin/lsof';
99  
100 # Compress::Raw::Bunzip2 needs several 100k of input data, we special case this.
101 # File::LibMagic wants to read ca. 70k of input data, before it says application/vnd.ms-excel
102 # Anything else works with 1024.
103 9 my $UNCOMP_BUFSZ = 1024;
104  
105 # unpack will give up, after unpacking that many levels. It is more likely we
106 # got into a loop by then, than really have that many levels.
107 9 my $RECURSION_LIMIT = 200;
108  
109 # Suggested place, where admins should install the helpers bundled with this module.
110 7 ▶sub _default_helper_dir { $ENV{FILE_UNPACK_HELPER_DIR}||'/usr/share/File-Unpack/helper' }
Subroutine _default_helper_dir: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"FILE_UNPACK_HELPER_DIR"} or "/usr/share/File-Unpack/helper" 7 0 7
111  
112 # we use '=' in the mime_name, this expands to '/(x\-|ANY\+)?'
113 ##
114 ## Caution: always use (?: ... ) below for grouping, so that no extra capturing clauses are created.
115  
116 9 my @builtin_mime_helpers = (
117 # mimetype pattern # suffix_re # command with redirects, as defined with IPC::Run::run
118  
119 # Requires: xz bzip2 gzip unzip lzip
120 [ 'application=x-lzip', qr{(?:lz)}, [qw(/usr/bin/lzip -dc %(src)s)], qw(> %(destfile)s) ],
121 [ 'application=xz', qr{(?:xz|lz(ma)?)}, [qw(/usr/bin/lzcat)], qw(< %(src)s > %(destfile)s) ],
122 [ 'application=xz', qr{(?:xz|lz(ma)?)}, [qw(/usr/bin/xz -dc %(src)s)], qw(> %(destfile)s) ],
123 [ 'application=lzma', qr{(?:xz|lz(ma)?)}, [qw(/usr/bin/lzcat)], qw(< %(src)s > %(destfile)s) ],
124 [ 'application=lzma', qr{(?:xz|lz(ma)?)}, [qw(/usr/bin/xz -dc %(src)s)], qw(> %(destfile)s) ],
125 [ 'application=bzip2', qr{bz2}, [qw(/usr/bin/bunzip2 -dc -f %(src)s)], qw(> %(destfile)s) ],
126 [ 'application=gzip', qr{(?:gz|Z)}, [qw(/usr/bin/gzip -dc -f %(src)s)], qw(> %(destfile)s) ],
127 [ 'application=compress', qr{(?:gz|Z)}, [qw(/usr/bin/gzip -dc -f %(src)s)], qw(> %(destfile)s) ],
128  
129 # Requires: sharutils
130 [ 'text=uuencode', qr{uu}, [qw(/usr/bin/uudecode -o %(destfile)s %(src)s)] ],
131  
132 # Requires: upx
133 [ 'application=upx', qr{(?:upx\.exe|upx)}, [qw(/usr/bin/upx -q -q -q -d -o%(destfile)s %(lsrc)s) ] ],
134  
135 # xml.summary.Mono.Security.Authenticode is twice inside of monodoc-1.0.4.tar.gz/Mono.zip/ -> use -o
136 [ 'application=zip', qr{(?:zip|jar|sar)}, [qw(/usr/bin/unzip -P no_pw -q -o %(src)s)] ],
137  
138 # Requires: unrar
139 [ 'application=rar', qr{rar}, [qw(/usr/bin/unrar x -o- -p- -inul -kb -y %(src)s)] ],
140 # Requires: lha
141 [ 'application=x-lha', qr{lha}, [qw(/usr/bin/lha x -q %(src)s)] ],
142  
143 # Requires: binutils
144 [ 'application=archive', qr{(?:a|ar|deb)}, [qw(/usr/bin/ar x %(src)s)] ],
145 [ 'application=x-deb', qr{deb}, [qw(/usr/bin/ar x %(src)s)] ],
146 [ 'application=x-debian-package', qr{deb}, [qw(/usr/bin/ar x %(src)s)] ],
147  
148 # Requires: cabextract
149 [ 'application/vnd.ms-cab-compressed', qr{cab}, [qw(/usr/bin/cabextract -q %(src)s)] ],
150  
151 # Requires: p7zip
152 [ 'application/x-7z-compressed', qr{7z}, [qw(/usr/bin/7z x -pPass -y %(src)s)] ],
153  
154 # Requires: tar rpm cpio
155 [ 'application=tar', qr{(?:tar|gem)}, [\&_locate_tar, qw(-xf %(src)s)] ],
156 [ 'application=tar+bzip2', qr{(?:tar\.bz2|tbz)}, [\&_locate_tar, qw(-jxf %(src)s)] ],
157 [ 'application=tar+gzip', qr{t(?:ar\.gz|gz)}, [\&_locate_tar, qw(-zxf %(src)s)] ],
158 # [ 'application=tar+gzip', qr{t(?:ar\.gz|gz)}, [qw(/home/testy/src/C/slowcat)], qw(< %(src)s |), [\&_locate_tar, qw(-zxf -)] ],
159 [ 'application=tar+lzma', qr{tar\.(?:xz|lzma|lz)}, [qw(/usr/bin/lzcat)], qw(< %(src)s |), [\&_locate_tar, qw(-xf -)] ],
160 [ 'application=tar+lzma', qr{tar\.(?:xz|lzma|lz)}, [qw(/usr/bin/xz -dc -f %(src)s)], '|', [\&_locate_tar, qw(-xf -)] ],
161 [ 'application=rpm', qr{(?:src\.r|s|r)pm}, [qw(/usr/bin/rpm2cpio %(src)s)], '|', [\&_locate_cpio_i] ],
162 [ 'application=cpio', qr{cpio}, [\&_locate_cpio_i], qw(< %(src)s) ],
163  
164 # Requires: poppler-tools
165 [ 'application=pdf', qr{pdf}, [qw(/usr/bin/pdftotext %(src)s %(destfile)s.txt)], '&', [qw(/usr/bin/pdfimages -j %(src)s pdfimages)] ],
166 );
167  
168 ## CAUTION keep _my_shell_quote in sync with all _locate_* functions.
169 sub _locate_tar
170 {
171 0 ▶ my $self = shift;
Subroutine _locate_tar: not called CC=5 SCAR=34.0
172 0 ▶ return @{$self->{_locate_tar}} if defined $self->{_locate_tar};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_locate_tar"} 0 0 0
173  
174 # cannot use tar -C %(destdir)s, we rely on being chdir'ed inside already :-)
175 # E: /bin/tar: /tmp/xxx/_VASn/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_: Cannot chdir: Permission denied
176  
177 0 ▶ my @tar = (-f '/bin/tar' ? '/bin/tar' : '/usr/bin/tar' );
Branch: 1 branch
BranchTrueFalseTotal
-f '/bin/tar' ? : 0 0 0
178 ## osc co loves to create directories with : in them.
179 ## Tell tar to accept such directories as directores.
180 0 ▶ push @tar, "--force-local"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->run([@tar, "--force-local", "--help"], {"out_err", "/dev/null"}) 0 0 0
181 unless $self->run([@tar, "--force-local", "--help"], { out_err => '/dev/null' });
182 0 ▶ push @tar, "--no-unquote"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->run([@tar, "--no-unquote", "--help"], {"out_err", "/dev/null"}) 0 0 0
183 unless $self->run([@tar, "--no-unquote", "--help"], { out_err => '/dev/null'});
184  
185 0 $self->{_locate_tar} = \@tar;
186 0 return @tar;
187 }
188  
189 sub _locate_cpio_i
190 {
191 0 ▶ my $self = shift;
Subroutine _locate_cpio_i: not called CC=6 SCAR=37.4
192 0 ▶ return @{$self->{_locate_cpio_i}} if defined $self->{_locate_cpio_i};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_locate_cpio_i"} 0 0 0
193  
194 0 my @cpio_i = ('/usr/bin/cpio', '-idm');
195 0 ▶ $cpio_i[1] .= 'u'
Branch: 1 branch
BranchTrueFalseTotal
unless run(["/usr/bin/cpio", "-idmu", "--usage"], {"out_err", "/dev/null"}) 0 0 0
196 unless run(['/usr/bin/cpio', '-idmu', '--usage'], {out_err => '/dev/null'});
197 0 ▶ push @cpio_i, '--sparse'
Branch: 1 branch
BranchTrueFalseTotal
unless run([@cpio_i, "--sparse", "--usage"], {"out_err", "/dev/null"}) 0 0 0
198 unless run([@cpio_i, '--sparse', '--usage'], {out_err => '/dev/null'});
199 0 ▶ push @cpio_i, '--no-absolute-filenames'
Branch: 1 branch
BranchTrueFalseTotal
unless run([@cpio_i, "--no-absolute-filenames", "--usage"], {"out_err", "/dev/null"}) 0 0 0
200 unless run([@cpio_i, '--no-absolute-filenames', '--usage'], {out_err => '/dev/null'});
201 0 ▶ push @cpio_i, '--force-local'
Branch: 1 branch
BranchTrueFalseTotal
unless run([@cpio_i, "--force-local", "--usage"], {"out_err", "/dev/null"}) 0 0 0
202 unless run([@cpio_i, '--force-local', '--usage'], {out_err => '/dev/null'});
203  
204 0 @{$self->{_locate_cpio_i}} = \@cpio_i;
205 0 return @cpio_i;
206 }
207  
208 =head1 SYNOPSIS
209  
210 This perl module comes with an executable script:
211  
212 /usr/bin/file_unpack -h
213  
214 /usr/bin/file_unpack [-1] [-m] ARCHIVE_FILE ...
215  
216  
217 File::Unpack is an unpacker for archives and files
218 (bz2/gz/zip/tar/cpio/iso/rpm/deb/cab/lzma/7z/rar ... pdf/odf) based on
219 MIME types. We call it strong, because it is not fooled by file suffixes, or
220 multiply wrapped packages. It recursively descends into each archive found
221 until it finally exposes all unpackable payload contents.
222  
223 A logfile can be written, precisely describing MIME types and unpack actions.
224  
225 use File::Unpack;
226  
227 my $log;
228 my $u = File::Unpack->new(logfile => \$log);
229  
230 my $m = $u->mime('/etc/init.d/rc');
231 print "$m->[0]; charset=$m->[1]\n";
232 # text/x-shellscript; charset=us-ascii
233  
234 map { print "$_->{name}\n" } @{$u->mime_helper()};
235 # application/%rpm
236 # application/%tar+gzip
237 # application/%tar+bzip2
238 # ...
239  
240 $u->unpack("inputfile.tar.bz2");
241 while ($log =~ m{^\s*"(.*?)":}g) # it's JSON.
242 {
243 print "$1\n"; # report all files unpacked
244 }
245  
246 ...
247  
248 Most of the known archive file formats are supported. Shell-script-style
249 plugins can be added to support additinal formats.
250  
251 Helper shell-scripts can be added to support additional mime-types. Example:
252  
253 F<< $ echo "ar x $1" > /usr/share/File-Unpack/helper/application=x-debian-package >>
254  
255 F<< $ chmod a+x /usr/share/File-Unpack/helper/application=x-debian-package >>
256  
257 This example creates a trivial external equivalent of the builtin MIME helper for *.deb packages.
258 For details see the documentation of the C<unpack()> method.
259  
260 C<unpack> examines the contents of an archive file or directory using an extensive
261 mime-type analysis. The contents is unpacked recursively to the given destination
262 directory; a listing of the unpacked files is reported through the built in
263 logging facility during unpacking. Most common archive file formats are handled
264 directly; more can easily be added as mime-type helper plugins.
265  
266 =head1 SUBROUTINES/METHODS
267  
268 =head2 new
269  
270 my $u = new(destdir => '.', logfile => \*STDOUT, maxfilesize => '2G', verbose => 1,
271 world_readable => 0, one_shot => 0, no_op => 0, archive_name_as_dir => 0,
272 follow_file_symlinks => 0,
273 log_params => {}, log_type => 'JSON');
274  
275 Creates an unpacker instance. The parameter C<destdir> must be a writable location; all output
276 files and directories are placed inside this destdir. Subdirectories will be
277 created in an attempt to reflect the structure of the input. Destdir defaults
278 to the current directory; relative paths are resolved immediatly, so that
279 chdir() after calling new is harmless.
280  
281 The parameter C<logfile> can be a reference to a scalar, a filename, or a filedescriptor.
282 The logfile starts with a JSON formatted prolog, where all lines start
283 with printable characters.
284 For each file unpacked, a one line record is appended, starting with a single
285 whitespace ' ', and terminated by "\n". The format is a JSON-encoded C<< "key":
286 {value},\n >> pair, where key is the filename, and value is a hash including 'mime',
287 'size', and other information.
288 The logfile is terminated by an epilog, where each line starts with a printable character.
289 As part of the epilog, a dummy file named "\" with an empty hash is added to the list.
290 It should be ignored while parsing.
291 Per default, the logfile is sent to STDOUT.
292  
293 The parameter C<maxfilesize> is a safeguard against compressed sparse files and
294 test-files for archivers. Such files could easily fill up any available disk
295 space when unpacked. Files hitting this limit will be silently truncated.
296 Check the logfile records or epilog to see if this has happened. BSD::Resource
297 is used manipulate RLIMIT_FSIZE.
298  
299 The parameter C<one_shot> can optionally be set to non-zero, to limit unpacking
300 to one step of unpacking. Unpacking of well known compressed archives like
301 e.g. '.tar.bz2' is considered one step only. If uncompressing an archive is
302 considered an extra step before unpacking the archive depends on the configured
303 mime helpers.
304  
305 The parameter C<no_op> causes unpack() to only print one shell command to
306 STDOUT and exit. This implies one_shot=1.
307  
308 The parameter C<world_readable> causes unpack() change all directories to 0755,
309 and all files to 444. Otherwise 0700 and 0400 (user readable) is asserted.
310  
311 The parameter C<follow_file_symlinks> causes some or all symlinks to files
312 to be included.
313 A value of 1 follows symlinks that exist in the input directory and point to a file.
314 This has no effect if the input is an archive file. A value of 2 also follows symlinks
315 that were extracted from archives. CAUTION: This may cause unpack() to visit
316 files or archives elsewhere in the local filesystem.
317 Directory symlinks are always excluded.
318  
319 The parameter C<archive_name_as_dir> causes the unpacker to store all unpacked
320 files inside a directory with the same name as their archive.
321  
322 The default depends on how many files are unpacked from the archive: If exactly one
323 file (or one toplevel directory) is unpacked, then no extra directory is used.
324 E.g. F<foo.tar.gz> would unpack to F<foo.tar> or
325 F<foo-1.0.zip> would unpack to F<foo-1.0/*> and no files outside this directory.
326 If multiple files (or directories) are unpacked, and the suffix of the archive can
327 be removed with the C<suffix_re> of its C<mime_helper>, then the
328 shortened name is used as a directory. E.g. F<foo.tar> would unpack to
329 F<foo/*>. Otherwise F<._> is appended to the archive name. E.g. F<foo.tar> would unpack to
330 F<foo.tar._/*>.
331  
332 In any case, the suffix F<._> or F<._B<NNN>> is used to avoid conflicts with
333 already existing names where B<NNN> is a numeric value.
334  
335 =head2 exclude
336  
337 exclude(add => ['.svn', '*.orig' ], del => '.svn', force => 1, follow_file_symlinks => 0)
338  
339 Defines the exclude-list for unpacking. This list is advisory for the MIME helpers.
340 The exclude-list items are shell glob patterns, where '*' or '?' never match '/'.
341  
342 You can use force to have any of these removed after unpacking.
343 Use (vcs => 1) to exclude a long list of known version control system directories, use (vcs => 0) to remove them.
344 The default is C<< exclude(empty => 1) >>, which is the same as C<< exclude(empty_file => 1, empty_dir => 1) >> --
345 having the obvious meaning.
346  
347 (re => 1) returns the active exclude-list as a regexp pattern.
348 Otherwise C<exclude> always returns the list as an array ref.
349  
350 Some symbolic links are included if {follow_file_symlinks} is nonzero. For details see C<<new()>>.
351  
352 If exclude patterns were effective, or if symlinks, fifos, sockets, ... were encountered during unpack(),
353 the logfile contains an additional 'skipped' keyword with statistics.
354  
355 =cut
356  
357 sub _glob_list_re
358 {
359 3 ▶ my @re;
Subroutine _glob_list_re: called CC=3 SCAR=11.0
360 3 ▶ return unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 3 3
361 3 for my $text (@_)
362 {
363 # Taken from pdb2perl:glob2re() and adapted, to not match slashes in wildcards.
364 # This should be kept compatible with tar --exclude .
365  
366 25 $text =~ s{([\.\(\)\[\]\{\}])}{\\$1}g; ## protect magic re characters.
367 25 $text =~ s{\*}{[^/]*}g; ## * -> [^/]*
368 25 $text =~ s{\?}{[^/]}g; ## ? -> [^/]
369 25 push @re, $text;
370 }
371 3 return '(/|^)(' . join('|', @re) . ')(/|$)';
372 }
373  
374 sub _not_excluded
375 {
376 12 ▶ my $self = shift;
Subroutine _not_excluded: called CC=5 SCAR=16.4
377 12 my ($dir, $file) = @_;
378  
379 12 ▶ return 1 unless my $re = $self->{exclude}{re};
Branch: 1 branch
BranchTrueFalseTotal
unless my $re = $self->{"exclude"}{"re"} 0 12 12
380  
381 12 ▶ $dir ||= '';
Condition50%1/2
$dir ||= ""
l!l
120
MC/DC0%0/1
$dir ||= ""
$dir
Truth table50%1/2
A
A= $dir
Aresult
11
00
382 12 ▶ $dir .= '/' unless $dir =~ m{/$};
Branch: 1 branch
BranchTrueFalseTotal
unless $dir =~ m[/$] 0 12 12
383 12 $file = $dir . $file;
384  
385 12 ▶ return 0 if $file =~ m{$re};
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /$re/ 10 2 12
386 2 return 1;
387 }
388  
389 sub exclude
390 {
391 3 ▶ my $self = shift;
Subroutine exclude: called CC=17 SCAR=31.9
Pod documented
392 3 ▶ my %opt = $#_ ? @_ : (add => $_[0]);
Branch: 1 branch
BranchTrueFalseTotal
$#_ ? : 3 0 3
393
394 # ADD to this list from: https://build.opensuse.org/project/show?project=devel%3Atools%3Ascm
395 3 my @vcs = qw(SCCS RCS CVS .svn .git .hg .osc);
396  
397 3 ▶ $opt{add} = [ $opt{add} ] unless ref $opt{add};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $opt{"add"} 0 3 3
398 3 ▶ $opt{del} = [ $opt{del} ] unless ref $opt{del};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $opt{"del"} 3 0 3
399  
400 3 ▶ push @{$opt{add}}, @vcs if defined $opt{vcs} and $opt{vcs};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{"vcs"} and $opt{"vcs"} 3 0 3
Condition33%1/3
defined $opt{"vcs"} and $opt{"vcs"}
!ll&&!rl&&r
003
MC/DC0%0/2
defined $opt{"vcs"} and $opt{"vcs"}
defined $opt{"vcs"} $opt{"vcs"}
Truth table33%1/3
A and B
A= defined $opt{"vcs"}B= $opt{"vcs"}
ABresult
0X0
100
111
401 3 ▶ push @{$opt{del}}, @vcs if defined $opt{vcs} and !$opt{vcs};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{"vcs"} and not $opt{"vcs"} 0 3 3
Condition33%1/3
defined $opt{"vcs"} and not $opt{"vcs"}
!ll&&!rl&&r
030
MC/DC0%0/2
defined $opt{"vcs"} and not $opt{"vcs"}
defined $opt{"vcs"} not $opt{"vcs"}
Truth table33%1/3
A and not(B)
A= defined $opt{"vcs"}B= not $opt{"vcs"}
ABresult
0X0
100
111
402  
403  
404 3 for my $a (@{$opt{add}})
405 {
406 25 ▶ $self->{exclude}{list}{$a}++ if defined $a;
Branch: 1 branch
BranchTrueFalseTotal
if defined $a 25 0 25
407 }
408
409 3 for my $a (@{$opt{del}})
410 {
411 3 ▶ delete $self->{exclude}{list}{$a} if defined $a;
Branch: 1 branch
BranchTrueFalseTotal
if defined $a 0 3 3
412 }
413  
414 3 my @list = sort keys %{$self->{exclude}{list}};
415 3 $self->{exclude}{re} = _glob_list_re(@list);
416  
417 3 ▶ $opt{empty_dir} = $opt{empty_file} = $opt{empty} if defined $opt{empty};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{"empty"} 0 3 3
418  
419 3 for my $o (qw(empty_file empty_dir force))
420 {
421 9 ▶ $self->{exclude}{$o} = $opt{$o} if defined $opt{$o};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{$o} 0 9 9
422 }
423  
424 $self->{follow_file_symlinks} = $opt{follow_file_symlinks}
425 3 ▶ if defined $opt{follow_file_symlinks};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{"follow_file_symlinks"} 0 3 3
426  
427 3 ▶ return $opt{re} ? $self->{exclude}{re} : \@list;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'re'} ? : 1 2 3
428 }
429  
430 =begin private
431  
432 =item log, logf, loggable_pathname
433  
434 The C<log> method is used by C<unpack> to send text to the logfile.
435 The C<logf> method takes a filename and a hash, and logs a JSON formatted line.
436 The trailing newline character of a line is delayed; it is printed by the next call to
437 C<log> or C<logf>. In case of C<logf>, a comma is emitted before the newline
438 from the second call onward.
439  
440 The C<loggable_pathname> shortens a path to be relative to either
441 $self->{destdir} or $self->{input} unless $self->{log_fullpath} is true.
442 If a hash is provided as a second parameter and the path was found to be relative
443 to $self->{input}, then an entry { 'srcdir' => 'input' } is added to this hash.
444  
445 =end private
446  
447 =cut
448 sub log
449 {
450 4 ▶ my ($self, $text) = @_;
Subroutine log: called CC=5 SCAR=17.1
Pod documented
451 4 ▶ if (my $fp = $self->{lfp})
Branch: 1 branch
BranchTrueFalseTotal
if (my $fp = $self->{"lfp"}) 4 0 4
452 {
453 4 my $oldpos = eval { $fp->tell; }; # old perl at SLES11 has no IO::Handle::tell()
454 4 ▶ $fp->write($text) or die "log($self->{logfile}): write failed: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
$fp->write($text) or die qq[log($self->{"logfile"}): write failed: $!\n] 0 4 4
455 4 my $r = eval { $fp->tell - $oldpos; };
456  
457 ## We do not expect any multibyte utf8 issues in here. It is plain 7-bit JSON.
458 ## E.g. /dev/null is not seekable. Be forgiving.
459 4 ▶ die "$oldpos,$r=log($self->{logfile}): write failed: $text\n" if $r and $r != length($text);
Branch: 1 branch
BranchTrueFalseTotal
if $r and $r != length $text 0 4 4
Condition33%1/3
$r and $r != length $text
!ll&&!rl&&r
040
MC/DC0%0/2
$r and $r != length $text
$r $r != length $text
Truth table33%1/3
A and B
A= $rB= $r != length $text
ABresult
0X0
100
111
460 4 $self->{lfp_printed}++;
461 }
462 }
463  
464 sub loggable_pathname
465 {
466 0 ▶ my ($self, $file, $hash) = @_;
Subroutine loggable_pathname: not called CC=6 SCAR=37.4
Pod documented
467  
468 0 ▶ unless ($self->{log_fullpath})
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"log_fullpath"}) 0 0 0
469 {
470 # very frequently, files are inside the destdir
471 0 ▶ unless ($file =~ s{^\Q$self->{destdir}\E/}{})
Branch: 1 branch
BranchTrueFalseTotal
unless ($file =~ s[^\Q$self->{"destdir"}\E/][]) 0 0 0
472 {
473 # less frequently, archives are logged inside the input dir
474 0 ▶ if ($self->{input})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"input"}) 0 0 0
475 {
476 0 ▶ if ($file =~ s{^\Q$self->{input}\E/}{\./input/./})
Branch: 1 branch
BranchTrueFalseTotal
if ($file =~ s[^\Q$self->{"input"}\E/][./input/./]) 0 0 0
477 {
478 0 ▶ $hash->{srcdir} = 'input' if ref $hash eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $hash eq "HASH" 0 0 0
479 }
480 }
481 }
482 }
483 0 return $file;
484 }
485  
486 sub logf
487 {
488 0 ▶ my ($self,$file,$hash,$suff) = @_;
Subroutine logf: not called CC=10 SCAR=47.0
Pod documented
489 0 ▶ $suff = "" unless defined $suff;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $suff 0 0 0
490 0 ▶ my $json = $self->{json} ||= JSON->new()->ascii(1);
Condition0%0/3
$self->{"json"} ||= "JSON"->new->ascii(1)
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"json"} ||= "JSON"->new->ascii(1)
$self->{"json"} "JSON"->new->ascii(1)
Truth table0%0/3
A ||= B
A= $self->{"json"}B= "JSON"->new->ascii(1)
ABresult
1X1
011
000
491 0 $file = $self->loggable_pathname($file, $hash);
492 0 ▶ if (my $fp = $self->{lfp})
Branch: 1 branch
BranchTrueFalseTotal
if (my $fp = $self->{"lfp"}) 0 0 0
493 {
494 0 ▶ if ($self->{log_type} eq 'plain')
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'log_type'} eq 'plain') { } 0 0 0
495 {
496 0 my $str = $file . ' (';
497 0 ▶ $str .= $hash->{mime} if defined $hash->{mime};
Branch: 1 branch
BranchTrueFalseTotal
if defined $hash->{"mime"} 0 0 0
498 0 $str .= ')';
499 0 ▶ $str = "# $str -> " . $hash->{unpacked} if $hash->{unpacked};
Branch: 1 branch
BranchTrueFalseTotal
if $hash->{"unpacked"} 0 0 0
500 0 $str .= "\n";
501 0 $self->log($str);
502 }
503 else
504 {
505 $self->log(qq[{ "oops": "logf used before prolog??",\n"unpacked_files":{\n])
506 0 ▶ unless $self->{lfp_printed}; # sysseek($fp, 0, 1); # }} there is no systell() ...
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"lfp_printed"} 0 0 0
507 0 my $str = $json->encode({$file => $hash});
508 0 $str =~ s{^\{}{}s;
509 0 $str =~ s{\}$}{}s;
510 0 my $pre = " ";
511 0 ▶ $pre = ",\n " if $self->{logf_continuation}++;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"logf_continuation"}++ 0 0 0
512 0 ▶ die "logf failed to encode newline char: $str\n" if $str =~ m{(?:\n|\r)};
Branch: 1 branch
BranchTrueFalseTotal
if $str =~ /(?:\n|\r)/ 0 0 0
513 0 $self->log("$pre$str$suff");
514 }
515 }
516 }
517  
518 $SIG{'XFSZ'} = sub
519 {
520 0 ▶ print STDERR "soft RLIMIT_FSIZE exceeded. SIGXFSZ recieved. Exiting\n";
Subroutine __ANON__: not called CC=1 SCAR=6.9
521 0 exit;
522 9 };
523  
524 # if this returns 0, we test again and call it again, possibly.
525 # if this returns nonzero, we just continue.
526 sub _default_fs_warn
527 {
528 0 ▶ carp "Filesystem (@_) is almost full.\n $0 paused for 30 sec.\n";
Subroutine _default_fs_warn: not called CC=1 SCAR=6.9
529 0 sleep(30);
530 0 return 0;
531 }
532  
533 ## returns 1, if enough space free.
534 ## returns 0, if warn-method was called, and returned nonzero
535 ## returns -1, if no warn method
536 ## or does not return at all, and rechecks the status
537 ## with at least on second delay, if warn-method returns 0.
538 sub _fs_check
539 {
540 0 ▶ my ($self, $needed_b, $needed_i, $needed_p) = @_;
Subroutine _fs_check: not called CC=13 SCAR=52.0
541 0 ▶ $needed_b = '1M' unless defined $needed_b; # bytes
Branch: 1 branch
BranchTrueFalseTotal
unless defined $needed_b 0 0 0
542 0 ▶ $needed_i = 100 unless defined $needed_i; # inodes
Branch: 1 branch
BranchTrueFalseTotal
unless defined $needed_i 0 0 0
543 0 ▶ $needed_p = 1.0 unless defined $needed_p; # percent
Branch: 1 branch
BranchTrueFalseTotal
unless defined $needed_p 0 0 0
544 0 $needed_b = _bytes_unit($needed_b);
545  
546 0 my $DIR;
547 open $DIR, "<", $self->{destdir} or
548 0 ▶ opendir $DIR, $self->{destdir} or return;
Branch: 1 branch
BranchTrueFalseTotal
open $DIR, "<", $self->{"destdir"} or opendir $DIR, $self->{"destdir"} or return 0 0 0
Condition0%0/3
open $DIR, "<", $self->{"destdir"} or opendir $DIR, $self->{"destdir"}
l!l&&r!l&&!r
000
MC/DC0%0/2
open $DIR, "<", $self->{"destdir"} or opendir $DIR, $self->{"destdir"}
open $DIR, "<", $self->{"destdir"} opendir $DIR, $self->{"destdir"}
Truth table0%0/3
A or B
A= open $DIR, "<", $self->{"destdir"}B= opendir $DIR, $self->{"destdir"}
ABresult
1X1
011
000
549 ## fileno() does not work with opendir() handles.
550 0 ▶ my $fd = fileno($DIR); return unless defined $fd;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fd 0 0 0
551  
552 0 for (;;)
553 {
554 0 my $st = eval { [ fstatvfs($fd) ] };
555 0 my $total_b = $st->[1] * $st->[2]; # f_frsize * f_blocks
556 0 my $free_b = $st->[0] * $st->[4]; # f_bsize * f_bavail
557 0 my $free_i = $st->[7]; # f_favail
558 0 ▶ my $perc = 100.0 * ($total_b - $free_b) / ($total_b||1);
Condition0%0/2
$total_b || 1
l!l
00
MC/DC0%0/1
$total_b || 1
$total_b
Truth table0%0/2
A
A= $total_b
Aresult
11
00
559  
560 0 ▶ return 1 if $free_b >= $needed_b &&
Branch: 1 branch
BranchTrueFalseTotal
if $free_b >= $needed_b and $free_i >= $needed_i and 100 - $perc > $needed_p 0 0 0
Condition0%0/6
$free_b >= $needed_b and $free_i >= $needed_i and 100 - $perc > $needed_p
!ll&&!rl&&r
000
$free_b >= $needed_b and $free_i >= $needed_i
!ll&&!rl&&r
000
MC/DC0%0/3
$free_b >= $needed_b and $free_i >= $needed_i and 100 - $perc > $needed_p
$free_b >= $needed_b $free_i >= $needed_i 100 - $perc > $needed_p
Truth table0%0/4
A and B and C
A= $free_b >= $needed_bB= $free_i >= $needed_iC= 100 - $perc > $needed_p
ABCresult
0XX0
10X0
1100
1111
561 $free_i >= $needed_i &&
562 (100-$perc > $needed_p);
563
564 0 ▶ return -1 unless $self->{fs_warn};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"fs_warn"} 0 0 0
565 0 my $w = $self->{fs_warn}->($self->{destdir}, $perc, $free_b, $free_i);
566 0 ▶ return 0 if $w;
Branch: 1 branch
BranchTrueFalseTotal
if $w 0 0 0
567 0 sleep 1;
568 }
569 }
570  
571 sub new
572 {
573 7 ▶ my $self = shift;
Subroutine new: called CC=40 SCAR=44.6
Pod documented
574 7 ▶ my $class = ref($self) || $self;
Condition33%1/3
ref $self || $self
l!l&&r!l&&!r
070
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
575 7 ▶ my %obj = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 0 7 7
576  
577 7 ▶ $obj{verbose} = 1 unless defined $obj{verbose};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $obj{"verbose"} 4 3 7
578 7 ▶ $obj{destdir} ||= '.';
Condition100%2/2
$obj{"destdir"} ||= "."
l!l
34
MC/DC100%1/1
$obj{"destdir"} ||= "."
$obj{"destdir"}
Truth table100%2/2
A
A= $obj{"destdir"}
Aresult
11
00
579 7 ▶ $obj{logfile} ||= \*STDOUT;
Condition100%2/2
$obj{"logfile"} ||= \*STDOUT
l!l
34
MC/DC100%1/1
$obj{"logfile"} ||= \*STDOUT
$obj{"logfile"}
Truth table100%2/2
A
A= $obj{"logfile"}
Aresult
11
00
580 7 ▶ $obj{log_type} ||= 'json'; # or 'plain'
Condition50%1/2
$obj{"log_type"} ||= "json"
l!l
07
MC/DC0%0/1
$obj{"log_type"} ||= "json"
$obj{"log_type"}
Truth table50%1/2
A
A= $obj{"log_type"}
Aresult
11
00
581 7 $obj{log_type} = lc $obj{log_type};
582 7 ▶ $obj{maxfilesize} = $ENV{'FILE_UNPACK_MAXFILESIZE'}||'2.5G' unless defined $obj{maxfilesize};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $obj{"maxfilesize"} 7 0 7
Condition50%1/2
$ENV{'FILE_UNPACK_MAXFILESIZE'} || '2.5G'
l!l
07
MC/DC0%0/1
$ENV{'FILE_UNPACK_MAXFILESIZE'} || '2.5G'
$ENV{'FILE_UNPACK_MAXFILESIZE'}
Truth table50%1/2
A
A= $ENV{'FILE_UNPACK_MAXFILESIZE'}
Aresult
11
00
583 7 $obj{maxfilesize} = _bytes_unit($obj{maxfilesize});
584 7 $ENV{'FILE_UNPACK_MAXFILESIZE'} = $obj{maxfilesize}; # so that children see the same.
585  
586 7 mkpath($obj{destdir}); # abs_path is unreliable if destdir does not exist
587 7 $obj{destdir} = Cwd::fast_abs_path($obj{destdir});
588 7 $obj{destdir} =~ s{(.)/+$}{$1}; # assert no trailing '/'.
589  
590 # used in unpack() to jail mime_helpers deep inside destdir:
591 7 ▶ $obj{dot_dot_safeguard} = 20 unless defined $obj{dot_dot_safeguard};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $obj{"dot_dot_safeguard"} 7 0 7
592 7 ▶ $obj{jail_chmod0} ||= 0;
Condition50%1/2
$obj{"jail_chmod0"} ||= 0
l!l
07
MC/DC0%0/1
$obj{"jail_chmod0"} ||= 0
$obj{"jail_chmod0"}
Truth table50%1/2
A
A= $obj{"jail_chmod0"}
Aresult
11
00
593 # used in unpack, print only:
594 7 ▶ $obj{no_op} ||= 0;
Condition50%1/2
$obj{"no_op"} ||= 0
l!l
07
MC/DC0%0/1
$obj{"no_op"} ||= 0
$obj{"no_op"}
Truth table50%1/2
A
A= $obj{"no_op"}
Aresult
11
00
595 # used in unpack, blocks recursion after archive unpacking:
596 7 ▶ $obj{one_shot} ||= $obj{no_op};
Condition33%1/3
$obj{"one_shot"} ||= $obj{"no_op"}
l!l&&r!l&&!r
007
MC/DC0%0/2
$obj{"one_shot"} ||= $obj{"no_op"}
$obj{"one_shot"} $obj{"no_op"}
Truth table33%1/3
A ||= B
A= $obj{"one_shot"}B= $obj{"no_op"}
ABresult
1X1
011
000
597  
598 # With $self->{within_archives} we know the difference between symlinks found in
599 # the given repository or symlinks that were unpacked from an archive.
600 # Those from an archive are followed only with follow_file_symlinks == 2.
601 7 ▶ $obj{follow_file_symlinks} ||= 0;
Condition50%1/2
$obj{"follow_file_symlinks"} ||= 0
l!l
07
MC/DC0%0/1
$obj{"follow_file_symlinks"} ||= 0
$obj{"follow_file_symlinks"}
Truth table50%1/2
A
A= $obj{"follow_file_symlinks"}
Aresult
11
00
602  
603 7 ▶ warn "WARNING: We are running as root: Malicious archives may clobber your filesystem.\n" if $obj{verbose} and !$>;
Branch: 1 branch
BranchTrueFalseTotal
if $obj{"verbose"} and not $> 0 7 7
Condition66%2/3
$obj{"verbose"} and not $>
!ll&&!rl&&r
340
MC/DC0%0/2
$obj{"verbose"} and not $>
$obj{"verbose"} not $>
Truth table66%2/3
A and not(B)
A= $obj{"verbose"}B= not $>
ABresult
0X0
100
111
604  
605 7 ▶ if (ref $obj{logfile} eq 'SCALAR' or !(ref $obj{logfile}))
Branch: 1 branch
BranchTrueFalseTotal
if (ref $obj{'logfile'} eq 'SCALAR' or not ref $obj{'logfile'}) { } 3 4 7
Condition100%3/3
ref $obj{"logfile"} eq "SCALAR" or not ref $obj{"logfile"}
l!l&&r!l&&!r
124
MC/DC100%2/2
ref $obj{"logfile"} eq "SCALAR" or not ref $obj{"logfile"}
ref $obj{"logfile"} eq "SCALAR" not ref $obj{"logfile"}
Truth table100%3/3
A or not(B)
A= ref $obj{"logfile"} eq "SCALAR"B= not ref $obj{"logfile"}
ABresult
1X1
011
000
606 {
607 3 ▶ open $obj{lfp}, ">", $obj{logfile} or croak "open logfile $obj{logfile} failed: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open $obj{"lfp"}, ">", $obj{"logfile"} or croak(qq[open logfile $obj{"logfile"} failed: $!\n]) 0 3 3
608 }
609 else
610 {
611 4 $obj{lfp} = $obj{logfile};
612 }
613 # make $obj{lfp} unbuffered, so that other processes can read line by line...
614 7 $obj{lfp}->autoflush(1);
615 7 $obj{lfp_printed} = 0;
616  
617 7 $obj{readable_file_modes} = [ 0400 ];
618 7 $obj{readable_dir_modes} = [ 0700, 0500 ];
619  
620 7 ▶ if ($obj{world_readable})
Branch: 1 branch
BranchTrueFalseTotal
if ($obj{"world_readable"}) 0 7 7
621 {
622 0 unshift @{$obj{readable_file_modes}}, 0444;
623 0 unshift @{$obj{readable_dir_modes}}, 0755;
624 }
625  
626 7 ▶ if ($obj{maxfilesize})
Branch: 1 branch
BranchTrueFalseTotal
if ($obj{"maxfilesize"}) 7 0 7
627 {
628 eval
629 7 {
630 9 ▶ no strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
631 # helper/application=x-shellscript calls File::Unpack->new(), with defaults...
632 7 my @have = BSD::Resource::getrlimit(RLIMIT_FSIZE);
633 7 ▶ if ($have[0] == RLIM_INFINITY or $have[0] > $obj{maxfilesize})
Branch: 1 branch
BranchTrueFalseTotal
if ($have[0] == RLIM_INFINITY() or $have[0] > $obj{"maxfilesize"}) 0 7 7
Condition33%1/3
$have[0] == RLIM_INFINITY() or $have[0] > $obj{"maxfilesize"}
l!l&&r!l&&!r
007
MC/DC0%0/2
$have[0] == RLIM_INFINITY() or $have[0] > $obj{"maxfilesize"}
$have[0] == RLIM_INFINITY() $have[0] > $obj{"maxfilesize"}
Truth table33%1/3
A or B
A= $have[0] == RLIM_INFINITY()B= $have[0] > $obj{"maxfilesize"}
ABresult
1X1
011
000
634 {
635 # if RLIM_INFINITY is seen as an attempt to increase limits, we would fail. Ignore this.
636 BSD::Resource::setrlimit(RLIMIT_FSIZE, $obj{maxfilesize}, RLIM_INFINITY) or
637 0 ▶ BSD::Resource::setrlimit(RLIMIT_FSIZE, $obj{maxfilesize}, $obj{maxfilesize}) or
Branch: 1 branch
BranchTrueFalseTotal
&BSD::Resource::setrlimit(scalar RLIMIT_FSIZE(), $obj{"maxfilesize"}, scalar RLIM_INFINITY()) or &BSD::Resource::setrlimit(scalar RLIMIT_FSIZE(), $obj{"maxfilesize"}, $obj{"maxfilesize"}) or warn qq[RLIMIT_FSIZE($obj{"maxfilesize"}), limit=($have[0],$have[1]) failed\n] 0 0 0
Condition0%0/3
&BSD::Resource::setrlimit(scalar RLIMIT_FSIZE(), $obj{"maxfilesize"}, scalar RLIM_INFINITY()) or &BSD::Resource::setrlimit(scalar RLIMIT_FSIZE(), $obj{"maxfilesize"}, $obj{"maxfilesize"})
l!l&&r!l&&!r
000
MC/DC0%0/2
&BSD::Resource::setrlimit(scalar RLIMIT_FSIZE(), $obj{"maxfilesize"}, scalar RLIM_INFINITY()) or &BSD::Resource::setrlimit(scalar RLIMIT_FSIZE(), $obj{"maxfilesize"}, $obj{"maxfilesize"})
&BSD::Resource::setrlimit(scalar RLIMIT_FSIZE(), $obj{"maxfilesize"}, scalar RLIM_INFINITY()) &BSD::Resource::setrlimit(scalar RLIMIT_FSIZE(), $obj{"maxfilesize"}, $obj{"maxfilesize"})
Truth table0%0/3
A or B
A= &BSD::Resource::setrlimit(scalar RLIMIT_FSIZE(), $obj{"maxfilesize"}, scalar RLIM_INFINITY())B= &BSD::Resource::setrlimit(scalar RLIMIT_FSIZE(), $obj{"maxfilesize"}, $obj{"maxfilesize"})
ABresult
1X1
011
000
638 warn "RLIMIT_FSIZE($obj{maxfilesize}), limit=($have[0],$have[1]) failed\n";
639 }
640 };
641 7 ▶ if ($@)
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 7 7
642 {
643 0 carp "WARNING maxfilesize=$obj{maxfilesize} ignored:\n $@ $!\n Maybe package perl-BSD-Resource is not installed??\n\n";
644 }
645 }
646  
647 7 ▶ $obj{minfree}{factor} = 10 unless defined $obj{minfree}{factor};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $obj{"minfree"}{"factor"} 7 0 7
648 7 ▶ $obj{minfree}{bytes} = '1M' unless defined $obj{minfree}{bytes};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $obj{"minfree"}{"bytes"} 7 0 7
649 7 ▶ $obj{minfree}{percent} = '1%' unless defined $obj{minfree}{percent};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $obj{"minfree"}{"percent"} 7 0 7
650 7 ▶ minfree(\%obj, warning => $obj{fs_warn}||\&_default_fs_warn);
Condition50%1/2
$obj{'fs_warn'} || \&File::Unpack::_default_fs_warn
l!l
07
MC/DC0%0/1
$obj{'fs_warn'} || \&File::Unpack::_default_fs_warn
$obj{'fs_warn'}
Truth table50%1/2
A
A= $obj{'fs_warn'}
Aresult
11
00
651  
652 7 ▶ $obj{exclude}{empty_dir} = 1 unless defined $obj{exclude}{empty_dir};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $obj{"exclude"}{"empty_dir"} 7 0 7
653 7 ▶ $obj{exclude}{empty_file} = 1 unless defined $obj{exclude}{empty_file};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $obj{"exclude"}{"empty_file"} 7 0 7
654  
655 7 $self = bless \%obj, $class;
656  
657 7 for my $h (@builtin_mime_helpers)
658 {
659 182 $self->mime_helper(@$h);
660 }
661 7 ▶ $obj{helper_dir} = _default_helper_dir unless exists $obj{helper_dir};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $obj{"helper_dir"} 7 0 7
662 7 ▶ $self->mime_helper_dir($obj{helper_dir}) if defined $obj{helper_dir} and -d $obj{helper_dir};
Branch: 1 branch
BranchTrueFalseTotal
if defined $obj{"helper_dir"} and -d $obj{"helper_dir"} 0 7 7
Condition33%1/3
defined $obj{"helper_dir"} and -d $obj{"helper_dir"}
!ll&&!rl&&r
070
MC/DC0%0/2
defined $obj{"helper_dir"} and -d $obj{"helper_dir"}
defined $obj{"helper_dir"} -d $obj{"helper_dir"}
Truth table33%1/3
A and B
A= defined $obj{"helper_dir"}B= -d $obj{"helper_dir"}
ABresult
0X0
100
111
663  
664 7 ▶ unless ($ENV{PERL5LIB})
Branch: 1 branch
BranchTrueFalseTotal
unless ($ENV{"PERL5LIB"}) 7 0 7
665 {
666 # in case we are using non-standard perl lib dirs, put them into the environment,
667 # so that any helper scripts see them too. They might need them, if written in perl.
668  
669 9 ▶ use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
670 7 my $pat = qr{^(?:\Q$Config{vendorlib}\E|\Q$Config{sitelib}\E|\Q$Config{privlib}\E)\b};
671 7 my @add; # all dirs, that come before the standard dirs.
672 7 for my $i (@INC)
673 {
674 35 ▶ last if $i =~ m{$pat};
Branch: 1 branch
BranchTrueFalseTotal
if $i =~ /$pat/ 7 28 35
675 28 push @add, $i;
676 }
677 7 ▶ $ENV{PERL5LIB} = join ':', @add if @add;
Branch: 1 branch
BranchTrueFalseTotal
if @add 7 0 7
678 }
679  
680 7 return $self;
681 }
682  
683 sub DESTROY
684 {
685 7 ▶ my $self = shift;
Subroutine DESTROY: called CC=14 SCAR=31.0
686 # when unpack() processes an input, it should delete {lfp} afterwards.
687 # Added some 'or' cases, as $self->{input} might be empty, although we had processed an input.
688 #
689 # We rather catch an error, than produce incomplete output.
690 # This happens with ksh/ast-base.2012-08-01.tar.bz2 after unpack('.../ast-base.2012-08-01/src/cmd/pax/data/a'): not much file or directory
691 #
692 7 ▶ if (($self->{input} or
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"input"} || ($self->{"lfp_printed"} || 0) || ($self->{"recursion_level"} || 0) and $self->{"lfp"}) 2 5 7
Condition61%8/13
$self->{"input"} || ($self->{"lfp_printed"} || 0) || ($self->{"recursion_level"} || 0) and $self->{"lfp"}
!ll&&!rl&&r
502
$self->{"input"} or ($self->{"lfp_printed"} or 0) or ($self->{"recursion_level"} or 0)
l!l&&r!l&&!r
205
$self->{"input"} or ($self->{"lfp_printed"} or 0)
l!l&&r!l&&!r
007
$self->{"lfp_printed"} or 0
l!l
25
$self->{"recursion_level"} or 0
l!l
05
MC/DC25%1/4
$self->{"input"} || ($self->{"lfp_printed"} || 0) || ($self->{"recursion_level"} || 0) and $self->{"lfp"}
$self->{"input"} $self->{"lfp_printed"} $self->{"recursion_level"} $self->{"lfp"}
Truth table28%2/7
A or B or C and D
A= $self->{"input"}B= $self->{"lfp_printed"}C= $self->{"recursion_level"}D= $self->{"lfp"}
ABCDresult
000X0
1XX00
01X00
00100
1XX11
01X11
00111
693 ($self->{lfp_printed}||0) or
694 ($self->{recursion_level}||0)) and $self->{lfp})
695 {
696 2 ▶ if ($self->{log_type} eq 'plain')
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'log_type'} eq 'plain') { } 0 2 2
697 {
698 # pass
699 }
700 else
701 {
702 2 ▶ $self->log(sprintf(qq[{"pid":"%d", "unpacked":{], $$)) unless $self->{lfp_printed};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"lfp_printed"} 0 2 2
703 }
704 2 ▶ my $r = $self->{recursion_level}||0;
Condition50%1/2
$self->{'recursion_level'} || 0
l!l
20
MC/DC0%0/1
$self->{'recursion_level'} || 0
$self->{'recursion_level'}
Truth table50%1/2
A
A= $self->{'recursion_level'}
Aresult
11
00
705  
706 # this should never happen.
707 # always delete $self->{lfp} manually, when done.
708 ## {{
709 2 my $msg = "unexpected destructor seen";
710 2 ▶ $msg = join('; ', @{$self->{error}}) if $self->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"error"} 0 2 2
711 2 ▶ if ($self->{log_type} eq 'plain')
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'log_type'} eq 'plain') { } 0 2 2
712 {
713 0 $self->log("# error: (l=$self->{lfp_printed},r=$r): $msg\n");
714 }
715 else
716 {
717 2 $self->log(qq[\n}, "error":"(l=$self->{lfp_printed},r=$r): $msg"}\n]);
718 }
719 2 ▶ close $self->{lfp} if $self->{lfp} ne $self->{logfile};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"lfp"} ne $self->{"logfile"} 2 0 2
720 2 delete $self->{lfp};
721 2 delete $self->{lfp_printed};
722 }
723 7 ▶ if ($self->{configdir})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"configdir"}) 0 7 7
724 {
725 0 rmtree($self->{configdir});
726 0 delete $self->{configdir};
727 }
728 }
729  
730 =head2 unpack
731  
732 $u->unpack($archive, [$destdir])
733  
734 Determines the contents of an archive and recursivly extracts its files.
735 An archive may be the pathname of a file or directory. The extracted contents will be
736 stored in F<destdir/$subdir/$dest_name>, where dest_name is the filename
737 component of archive without any leading pathname components, and possibly
738 stripped or added suffix. (Subdir defaults to ''.) If archive is a directory,
739 then dest_name will also be a directory. If archive is a file, the type of
740 dest_name depends on the type of packing: If the archive expands to multiple
741 files, dest_name will be a directory, otherwise it will be a file. If a file of
742 the same name already exists in the destination subdir, an additional subdir
743 component is created to avoid any conflicts.
744  
745 For each extracted file, a record is written to the logfile.
746 When unpacking is finished, the logfile contains one valid JSON structure.
747 Unpack achieves this by writing suitable prolog and epilog lines to the logfile.
748 The logfile can also be parsed line by line. All file records is one line and start
749 with a ' ' whitespace, and end in a ',' comma. Everything else is prolog or epilog.
750  
751 The actual unpacking is dispatched to MIME type specific helpers,
752 selected using C<mime>. A MIME helper can either be built-in code, or an
753 external shell-script found in a directory registered with
754 C<mime_helper_dir>. The standard place for external helpers is
755 F</usr/share/File-Unpack/helper>; it can be changed by the environment variable
756 F<FILE_UNPACK_HELPER_DIR> or the C<new> parameter C<helper_dir>.
757  
758 The naming of helper scripts is described under C<mime_helper()>.
759  
760 A MIME helper must have executable permission and is called with 6 parameters:
761 source_path, destfile, destination_path, mimetype, description, and config_dir.
762 Note, that destination_path is a freshly created empty working directory, even
763 if the unpacker is expected to unpack only a single file. The unpacker is
764 called after chdir into destination_path, so you usually do not need to
765 evaluate the third parameter.
766  
767 The directory C<config_dir> contains unpack configuration in .sh, .js and possibly
768 other formats. A MIME helper may use this information, but need not.
769 All data passed into C<new> is reflected there, as well as the active exclude-list.
770 Using the config information can help a MIME helper to skip unwanted
771 work or otherwise optimize unpacking.
772  
773 C<unpack> monitors the available filesystem space in destdir. If there is less space
774 than configured with C<minfree>, a warning can be printed and unpacking is
775 optionally paused. It also monitors the MIME helpers progress reading the archive
776 at source_path and reports percentages to STDERR (if verbose is 1 or more).
777  
778 After the MIME helper is finished, C<unpack> examines the files it created.
779 If it created no files in F<destdir>, an error is reported, and the
780 F<source_path> may be passed to other unpackers, or finally be added to the log as is.
781  
782 If the MIME helper wants to express that F<source_path> is already unpacked as far as possible
783 and should be added to the log without any error messages, it creates a symbolic link
784 F<destdir> pointing to F<source_path>.
785  
786  
787 The system considers replacing the
788 directory with a file, if all of the following conditions are met:
789  
790 =over
791  
792 =item *
793  
794 There is exactly one file in the directory.
795  
796 =item *
797  
798 The file name is identical with the directory name,
799 except for one changed or removed
800 suffix-word. (*.tar.gz -> *.tar; or *.tgz -> *.tar)
801  
802 =item *
803  
804 The file must not already exist in the parent directory.
805  
806 =back
807  
808 C<unpack> prepares 20 empty subdirectory levels and chdirs the unpacker
809 in there. This number can be adjusted using C<< new(dot_dot_safeguard => 20) >>.
810 A directory 20 levels up from the current working dir has mode 0 while
811 the MIME helper runs. C<unpack> can optionally chmod(0) the parent of the subdirectory
812 after it chdirs the unpacker inside. Use C<< new(jail_chmod0 => 1) >> for this, default
813 is off. If enabled, a MIME helper trying to place files outside of the specified
814 destination_path may receive 'permission denied' conditions.
815  
816 These are special hacks to keep badly constructed
817 tar-balls, cpio-, or zip-archives at bay.
818  
819 Please note, that this can help against archives containing relative paths
820 (like starting with '../../../foo'), but will be ineffective with absolute paths
821 (starting with '/foo').
822 It is the responsibility of MIME helpers to not create absolute paths;
823 C<unpack> should not be run as the root user, to minimize the risk of
824 compromising the root filesystem.
825  
826 A missing MIME helper is skipped, and subsequent helpers may take effect. A
827 MIME helper is expected to return an exit status of 0 upon success. If it runs
828 into a problem, it should print lines
829 starting with the affected filenames to stderr.
830 Such errors are recorded in the log with the unpacked archive, and as far as
831 files were created, also with these files.
832  
833 Symbolic links are ignored while unpacking.
834  
835 Currently you can call C<unpack> only once.
836  
837 =cut
838  
839 sub unpack
840 {
841 ## as long as $archive is outside $self->{destdir}, we construct our destdir by
842 ## replacing $self->{input_dir} with $self->{destdir}.
843 ## This $self->{input_dir} must be created and kept constant at the earliest
844 ## possible call.
845 ## When the $archive is inside $self->{destdir}, we do not use $self->{input_dir},
846 ## we then use the current $in_dir as destdir.
847 ##
848 ## Whenever an archive path outside $self->{destdir} is found,
849 ## it is first passed through Cwd::fast_abs_path before any other processing occurs.
850 ##
851 15 ▶ my ($self, $archive, $destdir) = @_;
Subroutine unpack: called CC=91 SCAR=79.6
Pod documented
852 15 ▶ $destdir = $self->{destdir} unless defined $destdir;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $destdir 2 13 15
853  
854 15 ▶ $destdir = $1 if $destdir =~ m{^(.*)$}s; # brute force untaint
Branch: 1 branch
BranchTrueFalseTotal
if $destdir =~ /^(.*)$/s 15 0 15
855  
856 15 ▶ if (($self->{recursion_level}||0) > $RECURSION_LIMIT)
Branch: 1 branch
BranchTrueFalseTotal
if (($self->{"recursion_level"} || 0) > $RECURSION_LIMIT) 0 15 15
Condition100%2/2
$self->{'recursion_level'} || 0
l!l
132
MC/DC100%1/1
$self->{'recursion_level'} || 0
$self->{'recursion_level'}
Truth table100%2/2
A
A= $self->{'recursion_level'}
Aresult
11
00
857 {
858 0 push @{$self->{error}}, "unpack('$archive','$destdir'): recursion limit $RECURSION_LIMIT";
859 ## this is only an emergency stop.
860 0 return 1;
861 }
862  
863 15 ▶ if ($archive !~ m{^/} or $archive !~ m{^\Q$self->{destdir}\E/})
Branch: 1 branch
BranchTrueFalseTotal
unless ($archive =~ m[^/] and $archive =~ m[^\Q$self->{"destdir"}\E/]) 15 0 15
Condition66%2/3
$archive =~ m[^/] and $archive =~ m[^\Q$self->{"destdir"}\E/]
!ll&&!rl&&r
2130
MC/DC0%0/2
$archive =~ m[^/] and $archive =~ m[^\Q$self->{"destdir"}\E/]
$archive =~ m[^/] $archive =~ m[^\Q$self->{"destdir"}\E/]
Truth table66%2/3
A and B
A= $archive =~ m[^/]B= $archive =~ m[^\Q$self->{"destdir"}\E/]
ABresult
0X0
100
111
864 {
865 # Cwd::fast_abs_path($archive) not only makes nice absolute paths, but it also expands
866 # file symlinks. This is a bad idea for two reasons:
867 # * when we allow {follow_file_symlinks} the link destination gets into the log file,
868 # rather than the (expected) link itself.
869 # * Also, this could easily trigger "path escaped" below .
870 ######
871 15 ▶ if ($self->{follow_file_symlinks} && $archive =~ m{^(.*)/(.*?)$})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'follow_file_symlinks'} and $archive =~ m[^(.*)/(.*?)$]) { } 0 15 15
Condition33%1/3
$self->{"follow_file_symlinks"} and $archive =~ m[^(.*)/(.*?)$]
!ll&&!rl&&r
1500
MC/DC0%0/2
$self->{"follow_file_symlinks"} and $archive =~ m[^(.*)/(.*?)$]
$self->{"follow_file_symlinks"} $archive =~ m[^(.*)/(.*?)$]
Truth table33%1/3
A and B
A= $self->{"follow_file_symlinks"}B= $archive =~ m[^(.*)/(.*?)$]
ABresult
0X0
100
111
872 {
873 # we solve both issues by doing this:
874 # chop off the filename; expand the path; re-add the filename.
875 0 my ($a_path, $a_file) = ($1,$2);
876 0 ▶ $a_path = Cwd::fast_abs_path($a_path) if -e $a_path;
Branch: 1 branch
BranchTrueFalseTotal
if -e $a_path 0 0 0
877 0 $archive = $a_path . '/' . $a_file;
878 }
879 else
880 {
881 15 ▶ $archive = Cwd::fast_abs_path($archive) if -e $archive;
Branch: 1 branch
BranchTrueFalseTotal
if -e $archive 15 0 15
882 }
883 }
884  
885 15 my $start_time = time;
886 15 ▶ if ($self->{recursion_level}++ == 0)
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"recursion_level"}++ == 0) 2 13 15
887 {
888 2 ▶ print STDERR "unpack: starting...\n" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 2 2
889 ## State that needs to be reset when (re)starting goes in here.
890 #
891 # CAUTION: recursion_level decrements again, as we return from unpack()
892 # how do we assert, that this code only runs at the start,
893 # and not once again at the end?
894 2 $self->{inside_archives} = 0;
895 2 ▶ $self->{json} ||= JSON->new()->ascii(1); # used often, create it unconditionally here and once.
Condition33%1/3
$self->{"json"} ||= "JSON"->new->ascii(1)
l!l&&r!l&&!r
020
MC/DC0%0/2
$self->{"json"} ||= "JSON"->new->ascii(1)
$self->{"json"} "JSON"->new->ascii(1)
Truth table33%1/3
A ||= B
A= $self->{"json"}B= "JSON"->new->ascii(1)
ABresult
1X1
011
000
896 2 $self->{iput} = $archive;
897 2 $self->{progress_tstamp} = $start_time;
898 2 ▶ ($self->{input_dir}, $self->{input_file}) = ($1, $2) if $archive =~ m{^(.*)/([^/]*)$};
Branch: 1 branch
BranchTrueFalseTotal
if $archive =~ m[^(.*)/([^/]*)$] 2 0 2
899  
900 2 ▶ if ($self->{log_type} eq 'plain')
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'log_type'} eq 'plain') { } 0 2 2
901 {
902 # pass
903 }
904 else
905 {
906 # logfile prolog
907 2 my $prolog = {destdir=>$self->{destdir}, fu=>$VERSION, pid=>$$, input => $archive, start => scalar localtime};
908 2 ▶ $prolog->{params} = $self->{log_params} if keys %{$self->{log_params}};
Branch: 1 branch
BranchTrueFalseTotal
if keys %{$$self{"log_params"};} 0 2 2
909 2 my $s = $self->{json}->encode($prolog);
910 2 $s =~ s@}$@, "unpacked":{\n@;
911 2 $self->log($s);
912 }
913 }
914  
915 15 ▶ unless (-e $archive)
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $archive) 0 15 15
916 {
917 # contstucted $archive wrongly
918 # e.g. we have 'pax/data/a/' instead of 'pax/data/_fu_3CEuA/a/'
919 0 push @{$self->{error}}, "unpack('$archive'): not much file or directory; ";
920 0 return 1;
921 }
922  
923 15 ▶ unless ($self->{input_dir})
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"input_dir"}) 0 15 15
924 {
925 0 push @{$self->{error}}, "unpack('$archive'); internal error: no {input_dir}";
926 0 return 1;
927 }
928  
929 15 my ($in_dir, $in_file) = ('/', '');
930 15 ▶ ($in_dir, $in_file) = ($1, $2) if $archive =~ m{^(.*/)([^/]*)$};
Branch: 1 branch
BranchTrueFalseTotal
if $archive =~ m[^(.*/)([^/]*)$] 15 0 15
931  
932 15 my $inside_destdir = 1;
933 15 my $subdir = $in_dir; # remainder after stripping $orig_archive_prefix / $self->{destdir}
934 15 ▶ unless ($subdir =~ s{^\Q$self->{destdir}\E/+}{})
Branch: 1 branch
BranchTrueFalseTotal
unless ($subdir =~ s[^\Q$self->{"destdir"}\E/+][]) 15 0 15
935 {
936 15 $inside_destdir = 0;
937 15 ▶ die "$archive path escaped. Neither inside original $self->{input_dir} nor inside destdir='$self->{destdir}'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $subdir =~ s[^\Q$self->{"input_dir"}\E/+][] 0 15 15
938 unless $subdir =~ s{^\Q$self->{input_dir}\E/+}{};
939 }
940  
941 15 ▶ print STDERR "unpack: r=$self->{recursion_level} in_dir=$in_dir, in_file=$in_file, destdir=$destdir\n" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 15 15
942  
943 15 my @missing_unpacker;
944  
945 15 ▶ if ($self->{progress_tstamp} + 10 < $start_time)
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"progress_tstamp"} + 10 < $start_time) 0 15 15
946 {
947 0 ▶ printf "T: %d files ...\n", $self->{file_count}||0;
Condition0%0/2
$self->{'file_count'} || 0
l!l
00
MC/DC0%0/1
$self->{'file_count'} || 0
$self->{'file_count'}
Truth table0%0/2
A
A= $self->{'file_count'}
Aresult
11
00
948 0 $self->{progress_tstamp} = $start_time;
949 }
950  
951 15 ▶ if (-d $archive)
Branch: 2 branches
BranchTrueFalseTotal
if (-d $archive) { } 3 12 15
elsif (-f $archive) { } 12 0 12
952 {
953 3 $self->_chmod_add($archive, @{$self->{readable_dir_modes}});
954 3 ▶ if (opendir DIR, $archive)
Branch: 1 branch
BranchTrueFalseTotal
if (opendir DIR, $archive) { } 3 0 3
955 {
956 3 ▶ my @f = sort grep { $_ ne '.' && $_ ne '..' } readdir DIR;
Branch: 1 branch
BranchTrueFalseTotal
$_ ne "." and $_ ne ".." 47 3 50
957 3 closedir DIR;
958 3 ▶ print STDERR "dir = @f\n" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 3 3
959 3 for my $f (@f)
960 {
961 13 ▶ if ($self->{exclude}{re} && $f =~ m{$self->{exclude}{re}})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"exclude"}{"re"} and $f =~ /$self->{"exclude"}{"re"}/) 10 3 13
Condition66%2/3
$self->{"exclude"}{"re"} and $f =~ /$self->{"exclude"}{"re"}/
!ll&&!rl&&r
0310
MC/DC50%1/2
$self->{"exclude"}{"re"} and $f =~ /$self->{"exclude"}{"re"}/
$self->{"exclude"}{"re"} $f =~ /$self->{"exclude"}{"re"}/
Truth table66%2/3
A and B
A= $self->{"exclude"}{"re"}B= $f =~ /$self->{"exclude"}{"re"}/
ABresult
0X0
100
111
962 {
963 10 $self->{skipped}{exclude}++;
964 }
965 13 my $new_in = "$archive/$f";
966 ## if $archive is $inside_destdir, then $archive is normally indentical to $destdir.
967 ## ($inside_destdir means inside $self->{destdir}, actually)
968 13 ▶ my $new_destdir = $destdir; $new_destdir .= "/$f" if -d $new_in;
Branch: 1 branch
BranchTrueFalseTotal
if -d $new_in 1 12 13
969 13 my $symlink_to_skip = -l $new_in;
970 13 ▶ my $dangeous_symlink = $self->{inside_archives} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'inside_archives'} ? : 0 13 13
971 13 ▶ if ($symlink_to_skip and ($self->{follow_file_symlinks} > $dangeous_symlink))
Branch: 1 branch
BranchTrueFalseTotal
if ($symlink_to_skip and $self->{"follow_file_symlinks"} > $dangeous_symlink) 0 13 13
Condition33%1/3
$symlink_to_skip and $self->{"follow_file_symlinks"} > $dangeous_symlink
!ll&&!rl&&r
1300
MC/DC0%0/2
$symlink_to_skip and $self->{"follow_file_symlinks"} > $dangeous_symlink
$symlink_to_skip $self->{"follow_file_symlinks"} > $dangeous_symlink
Truth table33%1/3
A and B
A= $symlink_to_skipB= $self->{"follow_file_symlinks"} > $dangeous_symlink
ABresult
0X0
100
111
972 {
973 0 ▶ $symlink_to_skip = 0 if -f $new_in;
Branch: 1 branch
BranchTrueFalseTotal
if -f $new_in 0 0 0
974 # directory and dead symlinks we always skip.
975 # directory symlinks could cause us to recurse out of the current tree.
976 }
977  
978 13 ▶ if ($symlink_to_skip)
Branch: 2 branches
BranchTrueFalseTotal
if ($symlink_to_skip) { } 0 13 13
elsif (-f $new_in or -d _) { } 13 0 13
979 {
980 # test -l first, as -f could be also true here...
981 0 ▶ print STDERR "symlink $new_in: skipped\n" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
982 0 $self->{skipped}{symlink}++;
983 }
984 ▶ elsif (-f $new_in or -d _)
Condition66%2/3
-f $new_in or -d _
l!l&&r!l&&!r
1210
MC/DC0%0/2
-f $new_in or -d _
-f $new_in -d _
Truth table66%2/3
A or B
A= -f $new_inB= -d _
ABresult
1X1
011
000
985 {
986 13 $self->unpack($new_in, $new_destdir);
987 }
988 else
989 {
990 0 ▶ print STDERR "special file $new_in: skipped\n" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
991 0 $self->{skipped}{device_node}++;
992 }
993 10 $self->{progress_tstamp} = time;
994 }
995 }
996 else
997 {
998 0 push @{$self->{error}}, "unpack dir ($archive) failed: $!";
999 }
1000 }
1001 elsif (-f $archive)
1002 {
1003 12 ▶ if ($self->_not_excluded($subdir, $in_file) and
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_not_excluded($subdir, $in_file) and not defined $self->{"done"}{$archive}) 2 10 12
Condition66%2/3
$self->_not_excluded($subdir, $in_file) and not defined $self->{"done"}{$archive}
!ll&&!rl&&r
1002
MC/DC50%1/2
$self->_not_excluded($subdir, $in_file) and not defined $self->{"done"}{$archive}
$self->_not_excluded($subdir, $in_file) not defined $self->{"done"}{$archive}
Truth table66%2/3
A and not(B)
A= $self->_not_excluded($subdir, $in_file)B= not defined $self->{"done"}{$archive}
ABresult
0X0
100
111
1004 !defined($self->{done}{$archive}))
1005 {
1006 2 $self->_chmod_add($archive, @{$self->{readable_file_modes}});
1007  
1008 2 my $m = $self->mime($archive);
1009 0 my ($h, $more) = $self->find_mime_helper($m);
1010 0 my $data = { mime => $m->[0] };
1011 0 ▶ if ($more)
Branch: 1 branch
BranchTrueFalseTotal
if ($more) 0 0 0
1012 {
1013 0 $data->{found} = $more;
1014 0 ▶ push @missing_unpacker, @{$more->{missing}} if $more->{missing};
Branch: 1 branch
BranchTrueFalseTotal
if $more->{"missing"} 0 0 0
1015 }
1016  
1017 0 ▶ if ($m->[0] eq 'text/plain' or !$h)
Branch: 1 branch
BranchTrueFalseTotal
if ($m->[0] eq 'text/plain' or not $h) { } 0 0 0
Condition0%0/3
$m->[0] eq "text/plain" or not $h
l!l&&r!l&&!r
000
MC/DC0%0/2
$m->[0] eq "text/plain" or not $h
$m->[0] eq "text/plain" not $h
Truth table0%0/3
A or not(B)
A= $m->[0] eq "text/plain"B= not $h
ABresult
1X1
011
000
1018 {
1019 # not really an archive.
1020 0 ▶ unless ($archive =~ m{^\Q$self->{destdir}\E/})
Branch: 1 branch
BranchTrueFalseTotal
if ($archive =~ m[^\Q$self->{'destdir'}\E/]) { } 0 0 0
1021 {
1022 0 ▶ mkpath($destdir) unless $self->{no_op};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"no_op"} 0 0 0
1023 0 my $destdir_in_file;
1024 0 ▶ $destdir_in_file = $1 if "$destdir/$in_file" =~ m{^(.*)$}s; # brute force untaint
Branch: 1 branch
BranchTrueFalseTotal
if ("$destdir/$in_file") =~ /^(.*)$/s 0 0 0
1025  
1026 0 ▶ if (-e "$destdir_in_file")
Branch: 1 branch
BranchTrueFalseTotal
if (-e "$destdir_in_file") 0 0 0
1027 {
1028 0 ▶ print STDERR "unpack copy in: $destdir_in_file already exists, " if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1029 0 $destdir = File::Temp::tempdir($TMPDIR_TEMPL, DIR => $destdir);
1030 0 ▶ $destdir_in_file = $1 if "$destdir/$in_file" =~ m{^(.*)$}s; # brute force untaint
Branch: 1 branch
BranchTrueFalseTotal
if ("$destdir/$in_file") =~ /^(.*)$/s 0 0 0
1031 0 ▶ print STDERR "using $destdir_in_file instead.\n" if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1032 }
1033 0 ▶ $data->{error} = "copy($archive): $!" unless File::Copy::copy($archive, $destdir_in_file);
Branch: 1 branch
BranchTrueFalseTotal
unless File::Copy::copy($archive, $destdir_in_file) 0 0 0
1034 0 $self->logf($destdir_in_file => $data);
1035 }
1036 else
1037 {
1038 0 $self->logf($archive => $data);
1039 }
1040 0 $self->{file_count}++;
1041 }
1042 else
1043 {
1044 # really an archive.
1045 0 ▶ if ($self->{archive_name_as_dir})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"archive_name_as_dir"}) 0 0 0
1046 {
1047 0 ▶ print STDERR "archive_name_as_dir: expanding destdir $destdir\n" if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1048 0 $destdir = _unused_pathname($destdir, $in_file);
1049 0 ▶ print STDERR "archive_name_as_dir: to $destdir\n" if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1050 }
1051 0 ▶ mkpath($destdir) unless $self->{no_op};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"no_op"} 0 0 0
1052 0 ▶ $self->{configdir} = $self->_prep_configdir() unless exists $self->{configdir};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"configdir"} 0 0 0
1053  
1054 ## new_name is a suggestion for the mime_helper only.
1055 0 my $new_name = $in_file;
1056
1057 # Either shorten the name from e.g. foo.txt.bz2 to foo.txt or append
1058 # something: foo.pdf to foo.pdf._;
1059 # Normally a suffix is appended by '.', but we also see '-' or '_' in real life.
1060 0 ▶ unless ($h->{suffix_re} and $new_name =~ s{[\._-]$h->{suffix_re}(?:\._\d*)?$}{}i)
Branch: 1 branch
BranchTrueFalseTotal
unless ($h->{"suffix_re"} and $new_name =~ s/[\._-]$h->{"suffix_re"}(?:\._\d*)?$//i) 0 0 0
Condition0%0/3
$h->{"suffix_re"} and $new_name =~ s/[\._-]$h->{"suffix_re"}(?:\._\d*)?$//i
!ll&&!rl&&r
000
MC/DC0%0/2
$h->{"suffix_re"} and $new_name =~ s/[\._-]$h->{"suffix_re"}(?:\._\d*)?$//i
$h->{"suffix_re"} $new_name =~ s/[\._-]$h->{"suffix_re"}(?:\._\d*)?$//i
Truth table0%0/3
A and B
A= $h->{"suffix_re"}B= $new_name =~ s/[\._-]$h->{"suffix_re"}(?:\._\d*)?$//i
ABresult
0X0
100
111
1061 {
1062 # avoid unary notation of recursion couning. There may be a 256 char limit per
1063 # directory entry. Start counting in decimal, if two or more.
1064 # Hmm, the /e modifier is not mentioned in perlre, but it works. Is it deprecated??
1065 0 $new_name .= "._";
1066 0 $new_name =~ s{\._\._$}{\._2};
1067 0 $new_name =~ s{\._(\d+)\._$}{ "._".($1+1) }e;
1068 }
1069  
1070 ## if consumer of logf wants to do progress indication himself,
1071 ## then tell him what we do before we start. (Our timer tick code may be an alternative...)
1072 #
1073 # if ($archive =~ m{^\Q$self->{destdir}\E})
1074 # {
1075 # $self->logf($archive => { unpacking => $h->{fmt_p} });
1076 # }
1077
1078 my ($unpacked, $diag) =
1079 $self->_run_mime_helper($h, $archive, $new_name, $destdir,
1080 0 $m->[0], $m->[2], $self->{configdir});
1081  
1082 # die Dumper "_run_mime_helper: $archive, $new_name, $destdir", readlink($unpacked), $unpacked;
1083  
1084 0 ▶ unless (ref $unpacked or -e $unpacked)
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $unpacked or -e $unpacked) 0 0 0
Condition0%0/3
ref $unpacked or -e $unpacked
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $unpacked or -e $unpacked
ref $unpacked -e $unpacked
Truth table0%0/3
A or B
A= ref $unpackedB= -e $unpacked
ABresult
1X1
011
000
1085 {
1086 0 warn("archive=$archive, new_name=$new_name\n");
1087 0 die("assert -e '$unpacked'")
1088 }
1089  
1090 0 ▶ return 0 if $self->{no_op};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"no_op"} 0 0 0
1091 0 ▶ if (ref $unpacked)
Branch: 2 branches
BranchTrueFalseTotal
if (ref $unpacked) { } 0 0 0
elsif (readlink $unpacked or '' eq $archive) { } 0 0 0
1092 {
1093 # a ref here means, something went wrong.
1094 0 $data->{failed} = $h->{fmt_p};
1095 0 $data->{error} = $unpacked->{error};
1096 0 ▶ $data->{stderr} = $unpacked->{stderr} if defined $unpacked->{stderr};
Branch: 1 branch
BranchTrueFalseTotal
if defined $unpacked->{"stderr"} 0 0 0
1097 0 $self->logf($archive => $data);
1098 0 $self->{file_count}++;
1099 0 $self->{helper_errors}++;
1100 }
1101 ▶ elsif (readlink($unpacked)||'' eq $archive)
Condition0%0/3
readlink $unpacked or "" eq $archive
l!l&&r!l&&!r
000
MC/DC0%0/2
readlink $unpacked or "" eq $archive
readlink $unpacked "" eq $archive
Truth table0%0/3
A or B
A= readlink $unpackedB= "" eq $archive
ABresult
1X1
011
000
1102 {
1103 # a symlink backwards means, there is nothing to unpack here. take it as is.
1104 0 unlink $unpacked;
1105 0 ▶ rmdir $destdir if $self->{archive_name_as_dir}; # now an empty dir.
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"archive_name_as_dir"} 0 0 0
1106 0 $data->{passed} = $h->{name};
1107 0 $data->{input} = $self->loggable_pathname($archive);
1108 0 $data->{cmd} = $h->{fmt_p};
1109 {
1110 0 local $Data::Dumper::Terse = 1;
1111 0 local $Data::Dumper::Indent = 0;
1112 0 ▶ $data->{diag} = Dumper $diag if $diag;
Branch: 1 branch
BranchTrueFalseTotal
if $diag 0 0 0
1113 }
1114  
1115 0 ▶ if ($archive =~ m{^\Q$self->{destdir}\E})
Branch: 1 branch
BranchTrueFalseTotal
if ($archive =~ /^\Q$self->{'destdir'}\E/) { } 0 0 0
1116 {
1117 # if inside, we just flag it done and log it.
1118 0 $self->{done}{$archive} = $archive;
1119 0 $self->logf($archive => $data);
1120 }
1121 else
1122 {
1123 # if the archive itself was outside destdir,
1124 # we copy it in, flag it done there, and log it here.
1125 0 ▶ if (File::Copy::copy($archive, $unpacked))
Branch: 1 branch
BranchTrueFalseTotal
if (File::Copy::copy($archive, $unpacked)) { } 0 0 0
1126 {
1127 0 $self->{done}{$archive} = $unpacked;
1128 0 $self->logf($unpacked => $data);
1129 }
1130 else
1131 {
1132 0 $data->{error} = "copy($archive, $unpacked): $!";
1133 0 $self->logf($archive => $data);
1134 }
1135 }
1136 0 $self->{file_count}++;
1137 }
1138 else
1139 {
1140 # normal case: mime helper placed all
1141 # in a directory (or file) called $unpacked
1142  
1143  
1144 0 ▶ if ($archive =~ m{^\Q$self->{destdir}\E})
Branch: 1 branch
BranchTrueFalseTotal
if ($archive =~ /^\Q$self->{"destdir"}\E/) 0 0 0
1145 {
1146 # to delete it, we should know if it was created during unpack.
1147 }
1148 0 $self->{done}{$archive} = $unpacked;
1149 0 $data->{cmd} = $h->{fmt_p};
1150 0 $data->{unpacked} = $self->loggable_pathname($unpacked);
1151 0 $self->logf($archive => $data);
1152 0 $self->{file_count}++;
1153 0 $self->{inside_archives}++;
1154  
1155 0 my $newdestdir = $unpacked;
1156 0 ▶ $newdestdir =~ s{/+[^/]+}{} unless -d $newdestdir; # make sure it is a directory
Branch: 1 branch
BranchTrueFalseTotal
unless -d $newdestdir 0 0 0
1157 0 ▶ $newdestdir = $destdir unless $newdestdir =~ m{^\Q$self->{destdir}\E/}; # make sure it does not escape
Branch: 1 branch
BranchTrueFalseTotal
unless $newdestdir =~ m[^\Q$self->{"destdir"}\E/] 0 0 0
1158 0 ▶ if ($self->{one_shot})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'one_shot'}) { } 0 0 0
1159 {
1160 0 local $self->{mime_orcish};
1161 0 local $self->{mime_helper};
1162  
1163 0 $self->unpack($unpacked, $newdestdir);
1164 }
1165 else
1166 {
1167 0 $self->unpack($unpacked, $newdestdir);
1168 }
1169 0 $self->{progress_tstamp} = time;
1170 0 $self->{inside_archives}--;
1171 }
1172 }
1173 }
1174 }
1175 else
1176 {
1177 0 $self->logf($archive => { "skipped" => "special file"});
1178 0 $self->{file_count}++;
1179 }
1180  
1181 10 ▶ if (--$self->{recursion_level} == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (--$self->{"recursion_level"} == 0) 0 10 10
1182 {
1183 0 ▶ if ($self->{log_type} eq 'plain')
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'log_type'} eq 'plain') { } 0 0 0
1184 {
1185 0 for my $m (@missing_unpacker)
1186 {
1187 0 $self->log("# missing unpacker: $m\n");
1188 }
1189 0 for my $s (sort keys %{$self->{skipped}})
1190 {
1191 0 $self->log("# skipped: $s: $self->{skipped}{$s}\n");
1192 }
1193 0 ▶ $self->log("# error: ".join('; ', @{$self->{error}})."\n") if $self->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"error"} 0 0 0
1194 }
1195 else
1196 {
1197 0 my $epilog = {end => scalar localtime, sec => time-$start_time };
1198 0 ▶ $epilog->{skipped} = $self->{skipped} if $self->{skipped};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"skipped"} 0 0 0
1199 0 ▶ $epilog->{error}{msg} = $self->{error} if $self->{error}; # just in case some errors were non-fatal.
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"error"} 0 0 0
1200 0 ▶ $epilog->{error}{helper} = $self->{helper_errors} if $self->{helper_errors}; # counting
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"helper_errors"} 0 0 0
1201 0 ▶ $epilog->{missing_unpacker} = \@missing_unpacker if @missing_unpacker;
Branch: 1 branch
BranchTrueFalseTotal
if @missing_unpacker 0 0 0
1202 0 my $s = $self->{json}->encode($epilog);
1203  
1204 0 $s =~ s@^{@\n},@;
1205 0 $self->log($s . "\n");
1206 }
1207  
1208 0 ▶ if ($self->{lfp} ne $self->{logfile})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"lfp"} ne $self->{"logfile"}) 0 0 0
1209 {
1210 0 ▶ close $self->{lfp} or carp "logfile write ($self->{logfile}) failed: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
close $self->{"lfp"} or carp(qq[logfile write ($self->{"logfile"}) failed: $!\n]) 0 0 0
1211 }
1212 0 delete $self->{lfp};
1213 0 delete $self->{lfp_printed};
1214 }
1215  
1216 # FIXME: should return nonzero if we had any unrecoverable errors.
1217 10 ▶ return $self->{error} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'error'} ? : 0 10 10
1218 }
1219  
1220 # Try a few modes to add to the current permission bits.
1221 # The first mode that succeeds ends the list.
1222 sub _chmod_add
1223 {
1224 5 ▶ my ($self, $file, @modes) = @_;
Subroutine _chmod_add: called CC=4 SCAR=14.3
1225 5 ▶ $file = $1 if $file =~ m{^(.*)$}m;
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /^(.*)$/m 5 0 5
1226 5 my $perm = (stat $file)[2] & 07777;
1227 5 for my $m (@modes)
1228 {
1229 5 ▶ last if chmod($perm|$m, $file); # may or may not succeed. Harmless here.
Branch: 1 branch
BranchTrueFalseTotal
if chmod $perm | $m, $file 5 0 5
1230 }
1231 }
1232  
1233 =head2 run
1234  
1235 $u->run([argv0, ...], @redir, ... { init => sub ..., in, out, err, watch, every, prog, ... })
1236  
1237 A general purpose fork-exec wrapper, based on IPC::Run. STDIN is closed, unless you specify
1238 an C<< in => >> as described in IPC::Run. STDERR and STDOUT are both printed to
1239 STDOUT, prefixed with 'E: ' and 'O: ' respectively, unless you specify C<< out => >>,
1240 C<< err => >>, or C<< out_err => >> ... for both.
1241  
1242 Using redirection operators in @redir takes precedence over the above in/out/err
1243 redirections. See also L<IPC::Run>. If you use the options in/out/err, you should
1244 restrict your redirection operators to the forms '<', '0<', '1>', '2>', or '>&' due
1245 to limitations in the precedence logic. Piping via '|' is properly recognized,
1246 but background execution '&' may confuse the precedence logic.
1247  
1248 This C<run> method is completly independent of the rest of File::Unpack. It works both
1249 as a static function and as a method call.
1250 It is used internally by C<unpack>, but is exported to be of use elsewhere.
1251  
1252 Init is run after construction of redirects. Calling chdir() in init thus has no
1253 effect on redirects with relative paths.
1254  
1255 Return value in scalar context is the first nonzero result code, if any. In list context
1256 all return values are returned.
1257 =cut
1258  
1259 sub run
1260 {
1261 0 ▶ shift if ref $_[0] ne 'ARRAY'; # toss $self object handle.
Subroutine run: not called CC=31 SCAR=69.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[0] ne "ARRAY" 0 0 0
1262 0 my (@cmd) = @_;
1263 0 my $opt;
1264 0 ▶ $opt = pop @cmd if ref $cmd[-1] eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $cmd[-1] eq "HASH" 0 0 0
1265  
1266 0 my $cmdname = $cmd[0][0]; $cmdname =~ s{^.*/}{};
1267  
1268 # run the command with
1269 # - STDIN closed, unless you specify an { in => ... }
1270 # - STDERR and STDOUT printed prefixed with 'E: ', 'O: ' to STDOUT,
1271 # unless you specify out =>, err =>, or out_err => ... for both.
1272 0 ▶ $opt->{in} ||= \undef;
Condition0%0/2
$opt->{"in"} ||= \(undef)
l!l
00
MC/DC0%0/1
$opt->{"in"} ||= \(undef)
$opt->{"in"}
Truth table0%0/2
A
A= $opt->{"in"}
Aresult
11
00
1273 0 ▶ $opt->{out} ||= $opt->{out_err};
Condition0%0/3
$opt->{"out"} ||= $opt->{"out_err"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$opt->{"out"} ||= $opt->{"out_err"}
$opt->{"out"} $opt->{"out_err"}
Truth table0%0/3
A ||= B
A= $opt->{"out"}B= $opt->{"out_err"}
ABresult
1X1
011
000
1274 0 ▶ $opt->{err} ||= $opt->{out_err};
Condition0%0/3
$opt->{"err"} ||= $opt->{"out_err"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$opt->{"err"} ||= $opt->{"out_err"}
$opt->{"err"} $opt->{"out_err"}
Truth table0%0/3
A ||= B
A= $opt->{"err"}B= $opt->{"out_err"}
ABresult
1X1
011
000
1275 0 ▶ $opt->{out} ||= sub { print "O: ($cmdname) @_\n"; };
Subroutine __ANON__: not called CC=1 SCAR=6.9
Condition0%0/3
$opt->{"out"} ||= sub { print "O: ($cmdname) @_\n"; }
l!l&&r!l&&!r
000
MC/DC0%0/2
$opt->{"out"} ||= sub { print "O: ($cmdname) @_\n"; }
$opt->{"out"} sub { print "O: ($cmdname) @_\n"; }
Truth table0%0/3
A ||= B
A= $opt->{"out"}B= sub { print "O: ($cmdname) @_\n"; }
ABresult
1X1
011
000
1276 0 ▶ $opt->{err} ||= sub { print "E: ($cmdname) @_\n"; };
Subroutine __ANON__: not called CC=1 SCAR=6.9
Condition0%0/3
$opt->{"err"} ||= sub { print "E: ($cmdname) @_\n"; }
l!l&&r!l&&!r
000
MC/DC0%0/2
$opt->{"err"} ||= sub { print "E: ($cmdname) @_\n"; }
$opt->{"err"} sub { print "E: ($cmdname) @_\n"; }
Truth table0%0/3
A ||= B
A= $opt->{"err"}B= sub { print "E: ($cmdname) @_\n"; }
ABresult
1X1
011
000
1277  
1278 0 my $has_i_redir = 0;
1279 0 my $has_o_redir = 0;
1280 0 my $has_e_redir = 0;
1281  
1282 ## The ugly truth is, there might be multiple commands with pipes.
1283 ## We need to provide all of them with the proper redirects.
1284 ## A command that pipes somewhere else, has_o_redir outbound through the pipe.
1285 ## A command that is piped into, has_i_redir inbound from the pipe.
1286 0 my @run = ();
1287  
1288  
1289 0 for my $c (@cmd)
1290 {
1291 0 ▶ if (ref $c)
Branch: 1 branch
BranchTrueFalseTotal
if (ref $c) 0 0 0
1292 {
1293 0 push @run, $c;
1294  
1295 # put init early, so that it is run, before any IO redirects access relative paths.
1296 0 ▶ push @run, init => $opt->{init} if $opt->{init};
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{"init"} 0 0 0
1297 0 next; # don't look into argvs, but
1298 }
1299 # look only into redirection operators
1300 0 ▶ $has_i_redir++ if $c =~ m{^0?<};
Branch: 1 branch
BranchTrueFalseTotal
if $c =~ /^0?</ 0 0 0
1301 0 ▶ $has_o_redir++ if $c =~ m{^1?>};
Branch: 1 branch
BranchTrueFalseTotal
if $c =~ /^1?>/ 0 0 0
1302 0 ▶ $has_e_redir++ if $c =~ m{^(?:2>|>&$)};
Branch: 1 branch
BranchTrueFalseTotal
if $c =~ /^(?:2>|>&$)/ 0 0 0
1303 0 ▶ if ($c eq '|')
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq "|") 0 0 0
1304 {
1305 0 ▶ push @run, '0<', $opt->{in} unless $has_i_redir;
Branch: 1 branch
BranchTrueFalseTotal
unless $has_i_redir 0 0 0
1306 0 $has_i_redir = 'piped';
1307 0 ▶ push @run, "2>", $opt->{err} unless $has_e_redir;
Branch: 1 branch
BranchTrueFalseTotal
unless $has_e_redir 0 0 0
1308 0 $has_e_redir = $has_o_redir = 0;
1309 }
1310 0 push @run, $c; # $1 if $c =~ m{^(.*)$}s; # brute force untaint
1311 }
1312  
1313 0 ▶ push @run, '0<', $opt->{in} unless $has_i_redir;
Branch: 1 branch
BranchTrueFalseTotal
unless $has_i_redir 0 0 0
1314 0 ▶ push @run, "1>", $opt->{out} unless $has_o_redir;
Branch: 1 branch
BranchTrueFalseTotal
unless $has_o_redir 0 0 0
1315 0 ▶ push @run, "2>", $opt->{err} unless $has_e_redir;
Branch: 1 branch
BranchTrueFalseTotal
unless $has_e_redir 0 0 0
1316  
1317 # die Dumper \@run if $cmd[0][0] eq '/usr/bin/rpm2cpio';
1318  
1319 0 my $t;
1320 0 ▶ $t = IPC::Run::timer($opt->{every}-0.6) if $opt->{every};
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{"every"} 0 0 0
1321 0 ▶ push @run, $t if $t;
Branch: 1 branch
BranchTrueFalseTotal
if $t 0 0 0
1322  
1323 0 ▶ $run[0][0] = $1 if $run[0][0] =~ m{^(.*)$}s;
Branch: 1 branch
BranchTrueFalseTotal
if $run[0][0] =~ /^(.*)$/s 0 0 0
1324 0 ▶ push @run, debug => $opt->{debug} if $opt->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{"debug"} 0 0 0
1325 0 my $h = eval { IPC::Run::start @run; };
1326 0 ▶ return wantarray ? (undef, $@) : undef unless $h;
Branch: 2 branches
BranchTrueFalseTotal
unless $h 0 0 0
wantarray ? : 0 0 0
1327  
1328 0 ▶ while ($h->pumpable)
Branch: 1 branch
BranchTrueFalseTotal
if ($h->pumpable) 0 0 0
1329 {
1330 # eval {} guards against 'process ended prematurely' errors.
1331 # This happens on very fast commands, despite pumpable().
1332 0 eval { $h->pump };
1333 0 ▶ if ($t && $t->is_expired)
Branch: 1 branch
BranchTrueFalseTotal
if ($t and $t->is_expired) 0 0 0
Condition0%0/3
$t and $t->is_expired
!ll&&!rl&&r
000
MC/DC0%0/2
$t and $t->is_expired
$t $t->is_expired
Truth table0%0/3
A and B
A= $tB= $t->is_expired
ABresult
0X0
100
111
1334 {
1335 0 $t->{has_fired}++;
1336 0 $opt->{prog}->($h, $opt);
1337 0 $t->start($opt->{every});
1338 }
1339 }
1340 0 $h->finish;
1341 0 $opt->{finished} = 1;
1342  
1343 ## call it once more, to get the 100% printout, or somthing else...
1344 0 ▶ $opt->{prog}->($h, $opt) if $t->{has_fired};
Branch: 1 branch
BranchTrueFalseTotal
if $t->{"has_fired"} 0 0 0
1345  
1346 0 ▶ return wantarray ? $h->full_results : $h->result;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
1347 }
1348  
1349 =head2 fmt_run_shellcmd
1350  
1351 File::Unpack::fmt_run_shellcmd( $m->{argvv} )
1352  
1353 Static function to pretty print the return value $m of method find_mime_helper();
1354 It formats a command array used with run() as a properly escaped shell command string.
1355  
1356 =cut
1357  
1358 sub _my_shell_quote
1359 {
1360 406 ▶ my @a = @_;
Subroutine _my_shell_quote: called CC=6 SCAR=18.1
1361 406 my $sub;
1362 406 ▶ if (@a and defined $a[0])
Branch: 1 branch
BranchTrueFalseTotal
if (@a and defined $a[0]) 406 0 406
Condition33%1/3
@a and defined $a[0]
!ll&&!rl&&r
00406
MC/DC0%0/2
@a and defined $a[0]
@a defined $a[0]
Truth table33%1/3
A and B
A= @aB= defined $a[0]
ABresult
0X0
100
111
1363 {
1364 406 ▶ $sub = '\\&_locate_tar' if $a[0] eq \&_locate_tar;
Branch: 1 branch
BranchTrueFalseTotal
if $a[0] eq \&File::Unpack::_locate_tar 35 371 406
1365 406 ▶ $sub = '\\&_locate_cpio_i' if $a[0] eq \&_locate_cpio_i;
Branch: 1 branch
BranchTrueFalseTotal
if $a[0] eq \&File::Unpack::_locate_cpio_i 14 392 406
1366 }
1367  
1368 406 ▶ if ($sub)
Branch: 1 branch
BranchTrueFalseTotal
if ($sub) 49 357 406
1369 {
1370 49 shift @a;
1371 49 return "$sub " . shell_quote(@a);
1372 }
1373 357 return shell_quote(@a);
1374 }
1375  
1376 sub fmt_run_shellcmd
1377 {
1378 182 ▶ my @a = @_;
Subroutine fmt_run_shellcmd: called CC=5 SCAR=16.2
Pod documented
1379 182 ▶ @a = @{$a[0]{argvv}} if ref $a[0] eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $a[0] eq "HASH" 0 182 182
1380 182 my @r = ();
1381 182 for my $a (@a)
1382 {
1383 406 ▶ push @r, ref($a) ? '('._my_shell_quote(@$a).')' : _my_shell_quote($a);
Branch: 1 branch
BranchTrueFalseTotal
ref $a ? : 210 196 406
1384 }
1385 182 my $r = join ' ', @r;
1386 182 ▶ $r =~ s{^\((.*)\)$}{$1} unless $#a; # parenthesis around a single cmd are unneeded.
Branch: 1 branch
BranchTrueFalseTotal
unless $#a 91 91 182
1387 182 return $r;
1388 }
1389  
1390 ## not a method, officially.
1391 #
1392 ## Chdir in and out of a jail is done here, as IPC::Run::run({init}->())
1393 ## has bad timing for our purposes.
1394 #
1395 ## fastjar extracts happily to ../../..
1396 ## this happens in cups-1.2.1/scripting/java/cups.jar
1397 #
1398 ## FIXME:
1399 # "/tmp/xxxx/cups-1.2.4-11.5.1.el5/cups-1.2.4/scripting/java/cups.jar":
1400 # {"cmd":"/usr/bin/unzip -P no_pw -q -o '%(src)s'",
1401 # "unpacked":"/tmp/xxxx/cups-1.2.4-11.5.1.el5/cups-1.2.4/_Knw_"}
1402 # Two issues:
1403 # a) _run_mime_helper in /tmp/xxxx/cups-1.2.4-11.5.1.el5/cups-1.2.4
1404 # should be /tmp/xxxx/cups-1.2.4-11.5.1.el5/cups-1.2.4/scripting/java
1405 # b) _Knw_ should never appear in the end result ...
1406 #
1407  
1408 sub _run_mime_helper
1409 {
1410 0 ▶ my ($self, $h, @argv) = @_;
Subroutine _run_mime_helper: not called CC=62 SCAR=82.7
1411  
1412 0 for my $i (0..$#argv)
1413 {
1414 0 ▶ $argv[$i] = $1 if $argv[$i] =~ m{^(.*)$}s; # brute force untaint
Branch: 1 branch
BranchTrueFalseTotal
if $argv[$i] =~ /^(.*)$/s 0 0 0
1415 }
1416  
1417 0 my $destdir = $argv[2];
1418 0 ▶ my $dot_dot_safeguard = $self->{dot_dot_safeguard}||0;
Condition0%0/2
$self->{'dot_dot_safeguard'} || 0
l!l
00
MC/DC0%0/1
$self->{'dot_dot_safeguard'} || 0
$self->{'dot_dot_safeguard'}
Truth table0%0/2
A
A= $self->{'dot_dot_safeguard'}
Aresult
11
00
1419 0 ▶ $dot_dot_safeguard = 2 if $dot_dot_safeguard < 2;
Branch: 1 branch
BranchTrueFalseTotal
if $dot_dot_safeguard < 2 0 0 0
1420  
1421 0 my $jail_base = '/dev/null';
1422 0 my $jail = $jail_base;
1423 0 ▶ unless ($self->{no_op})
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"no_op"}) 0 0 0
1424 {
1425 0 mkpath($destdir);
1426 0 $jail_base = File::Temp::tempdir($TMPDIR_TEMPL, DIR => $destdir);
1427 0 $jail = $jail_base . ("/_" x $dot_dot_safeguard);
1428 0 mkpath($jail);
1429 }
1430  
1431 0 my $args =
1432 {
1433 src => $argv[0], # abs_path() - but not symlink resolved, so that the unpacker sees 'our' name
1434 destfile => $argv[1], # filename() - a suggested name, simply based on src, in case the unpacker needs it.
1435 destdir => $jail, # abs_path() - for now...
1436 mime => $argv[3],
1437 descr => $argv[4], # mime_descr
1438 configdir => $argv[5] # abs_path()
1439 };
1440 0 $args->{lsrc} = Cwd::realpath($args->{src}); # symlinks resolved; use this with a stupid unpacker like 'upx'
1441 0 ▶ die "src must be an abs_path." unless $args->{src} =~ m{^/};
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"src"} =~ m[^/] 0 0 0
1442
1443 0 my @cmd;
1444 0 for my $a (@{$h->{argvv}})
1445 {
1446 0 ▶ if (ref $a)
Branch: 1 branch
BranchTrueFalseTotal
if (ref $a) { } 0 0 0
1447 {
1448 0 my @c = ();
1449 0 for my $b (@$a)
1450 {
1451 0 push @c, _subst_args($b, $args);
1452 }
1453 0 push @cmd, [@c];
1454 }
1455 else
1456 {
1457 0 push @cmd, _subst_args($a, $args);
1458 }
1459 }
1460  
1461 0 ▶ if ($self->{no_op})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"no_op"}) 0 0 0
1462 {
1463 0 print fmt_run_shellcmd(@cmd) . "\n";
1464 0 return undef;
1465 }
1466  
1467 0 ▶ print STDERR "_run_mime_helper in $destdir: " . fmt_run_shellcmd(@cmd) . "\n" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
1468  
1469 0 ▶ my $cwd = getcwd() or carp "cannot fetch initial working directory, getcwd: $!";
Branch: 1 branch
BranchTrueFalseTotal
my $cwd = getcwd() or carp("cannot fetch initial working directory, getcwd: $!") 0 0 0
1470 0 ▶ $cwd = $1 if $cwd =~ m{^(.*)$}s; # brute force untaint. Whereever you go, there you are.
Branch: 1 branch
BranchTrueFalseTotal
if $cwd =~ /^(.*)$/s 0 0 0
1471 0 ▶ chdir $jail or die "chdir '$jail'";
Branch: 1 branch
BranchTrueFalseTotal
chdir $jail or die "chdir '${jail}'" 0 0 0
1472 0 ▶ chmod 0, $jail_base if $self->{jail_chmod0};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"jail_chmod0"} 0 0 0
1473 # Now have fully initialzed in the parent before forking.
1474 # This is needed, as all redirect operators are executed in the parent before forking.
1475 # init => sub { ... } is no longer needed. sigh, I really wanted to the init sub for the chdir.
1476 # But hey, mkpath() and rmtree() change the cwd so often, and restore it, so why shouldn't we?
1477  
1478  
1479 0 my $run_error = undef; # we capture the first error line for the logfile.
1480 my @r = $self->run(@cmd,
1481 {
1482 debug => ($self->{verbose} > 2) ? $self->{verbose} - 2 : 0,
1483 watch => $args->{src}, every => 5, fu_obj => $self, mime_helper => $h,
1484 0 ▶ err => sub { print "E: @_\n" if $self->{verbose}; $run_error = "@_" unless length $run_error },
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 2 branches
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
unless length $run_error 0 0 0
1485 prog => sub
1486 {
1487 0 ▶ $_[1]{tick}++;
Subroutine __ANON__: not called CC=15 SCAR=54.8
1488 0 my $name = $_[1]{watch}; $name =~ s{.*/}{};
1489 0 ▶ if ($_[1]{finished})
Branch: 2 branches
BranchTrueFalseTotal
if ($_[1]{'finished'}) { } 0 0 0
elsif (my $p = _children_fuser($_[1]{'watch'}, POSIX::getpid())) { } 0 0 0
1490 {
1491 printf "T: %s (%s, done)\n", $name, _unit_bytes(-s $_[1]{watch},1)
1492 0 ▶ if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1493 }
1494 elsif (my $p = _children_fuser($_[1]{watch}, POSIX::getpid()))
1495 {
1496 0 _fuser_offset($p);
1497 # we may get muliple process with multiple filedescriptors.
1498 # select the one that moves fastest.
1499 0 my $largest_diff = -1;
1500 0 for my $pid (keys %$p)
1501 {
1502 0 for my $fd (keys %{$p->{$pid}{fd}})
1503 {
1504 0 ▶ my $diff = ($p->{$pid}{fd}{$fd}{pos}||0) - ($_[1]{fuser}{$pid}{fd}{$fd}{pos}||0);
Condition0%0/4
$p->{$pid}{'fd'}{$fd}{'pos'} || 0
l!l
00
$_[1]{'fuser'}{$pid}{'fd'}{$fd}{'pos'} || 0
l!l
00
MC/DC0%0/1
$p->{$pid}{'fd'}{$fd}{'pos'} || 0
$p->{$pid}{'fd'}{$fd}{'pos'}
MC/DC0%0/1
$_[1]{'fuser'}{$pid}{'fd'}{$fd}{'pos'} || 0
$_[1]{'fuser'}{$pid}{'fd'}{$fd}{'pos'}
Truth table0%0/2
A
A= $p->{$pid}{'fd'}{$fd}{'pos'}
Aresult
11
00
Truth table0%0/2
A
A= $_[1]{'fuser'}{$pid}{'fd'}{$fd}{'pos'}
Aresult
11
00
1505 0 ▶ if ($diff > $largest_diff)
Branch: 1 branch
BranchTrueFalseTotal
if ($diff > $largest_diff) 0 0 0
1506 {
1507 0 $largest_diff = $diff;
1508 0 $p->{fastest_fd} = $p->{$pid}{fd}{$fd};
1509 }
1510 }
1511 }
1512 # Stick with the one we had before, if none moves.
1513 0 ▶ $p->{fastest_fd} = $_[1]{fuser}{fastest_fd} if $largest_diff <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $largest_diff <= 0 0 0 0
1514 0 $_[1]{fuser} = $p;
1515 0 ▶ my $off = $p->{fastest_fd}{pos}||0;
Condition0%0/2
$p->{'fastest_fd'}{'pos'} || 0
l!l
00
MC/DC0%0/1
$p->{'fastest_fd'}{'pos'} || 0
$p->{'fastest_fd'}{'pos'}
Truth table0%0/2
A
A= $p->{'fastest_fd'}{'pos'}
Aresult
11
00
1516 0 ▶ my $tot = $p->{fastest_fd}{size}||(-s $_[1]{watch})||1;
Condition0%0/5
$p->{'fastest_fd'}{'size'} || -s $_[1]{'watch'} || 1
l!l
00
$p->{"fastest_fd"}{"size"} or -s $_[1]{"watch"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$p->{'fastest_fd'}{'size'} || -s $_[1]{'watch'} || 1
$p->{"fastest_fd"}{"size"} -s $_[1]{"watch"}
Truth table0%0/3
A or B
A= $p->{"fastest_fd"}{"size"}B= -s $_[1]{"watch"}
ABresult
1X1
011
000
1517 printf "T: %s (%s, %.1f%%)\n", $name, _unit_bytes($off,1), ($off*100)/$tot
1518 0 ▶ if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1519 }
1520 else
1521 {
1522 print "T: $name tick_tick $_[1]{tick}\n"
1523 0 ▶ if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1524 }
1525 },
1526 0 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
$self->{'verbose'} > 2 ? : 0 0 0
1527
1528 # system("ls -la $jail_base/..; find $jail_base");
1529 # print STDERR Dumper \@r;
1530  
1531 0 ▶ chmod 0700, $jail_base if $self->{jail_chmod0};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"jail_chmod0"} 0 0 0
1532 0 ▶ chdir $cwd or die "cannot chdir back to cwd: chdir($cwd): $!";
Branch: 1 branch
BranchTrueFalseTotal
chdir $cwd or die "cannot chdir back to cwd: chdir($cwd): $!" 0 0 0
1533 0 my @nonzero = grep { $_ } @r;
1534  
1535 # TODO: handle failure
1536 # - remove all,
1537 # - retry with a fallback helper , if any.
1538 printf STDERR "Non-Zero return value: $nonzero[0]: %s\n", fmt_run_shellcmd(@cmd)
1539 0 ▶ if $nonzero[0] and $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $nonzero[0] and $self->{"verbose"} 0 0 0
Condition0%0/3
$nonzero[0] and $self->{"verbose"}
!ll&&!rl&&r
000
MC/DC0%0/2
$nonzero[0] and $self->{"verbose"}
$nonzero[0] $self->{"verbose"}
Truth table0%0/3
A and B
A= $nonzero[0]B= $self->{"verbose"}
ABresult
0X0
100
111
1540  
1541 # FIXME: fallback helper not implemented
1542 # t/data/pdftxt-a.txt is really plain/text altthough it begins with "PDF-1.4..." and
1543 # thus fools the mime-type tests.
1544 # should run other helpers, and finally 'strings -' as a trivial fallback.
1545 0 ▶ if ($nonzero[0])
Branch: 1 branch
BranchTrueFalseTotal
if ($nonzero[0]) 0 0 0
1546 {
1547 0 rmtree($jail_base); # empty or has unusable contents now.
1548 ## FIXME: we should at least copy in the original file as is...
1549 0 return { error => "nonzero retval:\n " . Dumper(\@r), stderr => $run_error };
1550 }
1551  
1552 # loop through all _: if it only contains one item , replace it with this item,
1553 # be it a file or dir. This uses $jail_tmp, an unused pathname.
1554 0 my $jail_tmp = File::Temp::tempdir($TMPDIR_TEMPL, DIR => $destdir);
1555 0 rmdir $jail_tmp;
1556  
1557 # if only one file in $jail, move it up, and return
1558 # the filename instead of the dirname here.
1559 # (We don't search for $args->{destfile}, it is the unpackers choice to use it or not.)
1560 0 my $wanted_name;
1561 0 ▶ for (my $i = 0; $i <= $dot_dot_safeguard; $i++)
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= $dot_dot_safeguard) 0 0 0
1562 {
1563 0 ▶ opendir DIR, $jail_base or last;
Branch: 1 branch
BranchTrueFalseTotal
opendir DIR, $jail_base or last 0 0 0
1564 0 ▶ my @found = grep { $_ ne '.' and $_ ne '..' } readdir DIR;
Branch: 1 branch
BranchTrueFalseTotal
$_ ne "." and $_ ne ".." 0 0 0
1565 0 closedir DIR;
1566 0 my $found0;
1567 0 ▶ $found0 = $1 if defined($found[0]) and $found[0] =~ m{^(.*)$}s; # brute force untaint
Branch: 1 branch
BranchTrueFalseTotal
if defined $found[0] and $found[0] =~ /^(.*)$/s 0 0 0
Condition0%0/3
defined $found[0] and $found[0] =~ /^(.*)$/s
!ll&&!rl&&r
000
MC/DC0%0/2
defined $found[0] and $found[0] =~ /^(.*)$/s
defined $found[0] $found[0] =~ /^(.*)$/s
Truth table0%0/3
A and B
A= defined $found[0]B= $found[0] =~ /^(.*)$/s
ABresult
0X0
100
111
1568 0 ▶ print STDERR "dot_dot_safeguard=$dot_dot_safeguard, i=$i, found=$found0\n" if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
1569 0 ▶ unless (@found)
Branch: 1 branch
BranchTrueFalseTotal
unless (@found) 0 0 0
1570 {
1571 0 rmdir $jail_base;
1572 0 my $name;
1573 0 ▶ $name = $1 if $args->{src} =~ m{/([^/]+)$};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"src"} =~ m[/([^/]+)$] 0 0 0
1574 0 ▶ print STDERR "oops(i=$i): nothing unpacked?? Adding $name as is.\n" if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1575 0 return { error => "nothing unpacked" };
1576 }
1577 0 ▶ last if scalar @found != 1;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @found != 1 0 0 0
1578 0 ▶ $wanted_name = $found0 if $i == $dot_dot_safeguard;
Branch: 1 branch
BranchTrueFalseTotal
if $i == $dot_dot_safeguard 0 0 0
1579 0 ▶ last unless -d $jail_base . "/" . $found0;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $jail_base . '/' . $found0 0 0 0
1580 # assert writable dirs. needed for ksh/ast-base.2012-08-01.tar.bz2/src/cmd/pax/data/ro.dat
1581 0 chmod(0755, $jail_base . "/" . $found0);
1582 0 ▶ rename $jail_base, $jail_tmp or die("4:$i rename($jail_base, $jail_tmp) failed: $!");
Branch: 1 branch
BranchTrueFalseTotal
rename $jail_base, $jail_tmp or die "4:$i rename($jail_base, $jail_tmp) failed: $!" 0 0 0
1583 0 ▶ rename $jail_tmp . "/" . $found0, $jail_base or die("5:$i rename($jail_tmp .'/'. $found0, $jail_base) failed: $!");
Branch: 1 branch
BranchTrueFalseTotal
rename $jail_tmp . '/' . $found0, $jail_base or die "5:$i rename($jail_tmp .'/'. $found0, $jail_base) failed: $!" 0 0 0
1584 0 ▶ rmdir $jail_tmp or last;
Branch: 1 branch
BranchTrueFalseTotal
rmdir $jail_tmp or last 0 0 0
1585 }
1586  
1587 ## this message is broken.
1588 # print STDERR "Hmmm, unpacker did not use destname: $args->{destfile}\n" if $self->{verbose} and !defined $wanted_name;
1589  
1590 # say nothing, if $args->{destfile} is equal to or a prefix of $wanted_name.
1591 print STDERR "Hmmm, unpacker saw destname: $args->{destfile}, but used destname: $wanted_name\n"
1592 0 ▶ if $self->{verbose} > 1 and defined($wanted_name) and $wanted_name !~ m{^\Q$args->{destfile}};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 and defined $wanted_name and not $wanted_name =~ /^\Q$args->{"destfile"}\E/ 0 0 0
Condition0%0/6
$self->{"verbose"} > 1 and defined $wanted_name and not $wanted_name =~ /^\Q$args->{"destfile"}\E/
!ll&&!rl&&r
000
$self->{"verbose"} > 1 and defined $wanted_name
!ll&&!rl&&r
000
MC/DC0%0/3
$self->{"verbose"} > 1 and defined $wanted_name and not $wanted_name =~ /^\Q$args->{"destfile"}\E/
$self->{"verbose"} > 1 defined $wanted_name not $wanted_name =~ /^\Q$args->{"destfile"}\E/
Truth table0%0/4
A and B and not(C)
A= $self->{"verbose"} > 1B= defined $wanted_nameC= not $wanted_name =~ /^\Q$args->{"destfile"}\E/
ABCresult
0XX0
10X0
1100
1111
1593  
1594 0 ▶ $wanted_name = $args->{destfile} unless defined $wanted_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $wanted_name 0 0 0
1595 0 my $wanted_path;
1596 0 ▶ $wanted_path = _unused_pathname($destdir, $wanted_name) if defined $wanted_name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $wanted_name 0 0 0
1597 0 my $unpacked = $jail_base;
1598 0 ▶ if (defined($wanted_name) and !-e $wanted_path)
Branch: 1 branch
BranchTrueFalseTotal
if (defined $wanted_name and not -e $wanted_path) 0 0 0
Condition0%0/3
defined $wanted_name and not -e $wanted_path
!ll&&!rl&&r
000
MC/DC0%0/2
defined $wanted_name and not -e $wanted_path
defined $wanted_name not -e $wanted_path
Truth table0%0/3
A and not(B)
A= defined $wanted_nameB= not -e $wanted_path
ABresult
0X0
100
111
1599 {
1600 0 ▶ if (-d $jail_base)
Branch: 1 branch
BranchTrueFalseTotal
if (-d $jail_base) { } 0 0 0
1601 {
1602 ## find out, if the unpacker created exactly one file or one directory,
1603 ## in this case we can move one level further.
1604 0 opendir DIR, $jail_base;
1605 0 ▶ my @found = grep { $_ ne '.' and $_ ne '..' } readdir DIR;
Branch: 1 branch
BranchTrueFalseTotal
$_ ne "." and $_ ne ".." 0 0 0
1606 0 closedir DIR;
1607 0 my $found0;
1608 0 ▶ $found0 = $1 if defined($found[0]) and $found[0] =~ m{^(.*)$}s; # brute force untaint
Branch: 1 branch
BranchTrueFalseTotal
if defined $found[0] and $found[0] =~ /^(.*)$/s 0 0 0
Condition0%0/3
defined $found[0] and $found[0] =~ /^(.*)$/s
!ll&&!rl&&r
000
MC/DC0%0/2
defined $found[0] and $found[0] =~ /^(.*)$/s
defined $found[0] $found[0] =~ /^(.*)$/s
Truth table0%0/3
A and B
A= defined $found[0]B= $found[0] =~ /^(.*)$/s
ABresult
0X0
100
111
1609  
1610 0 ▶ if ($#found == 0 and $found0 eq $wanted_name)
Branch: 1 branch
BranchTrueFalseTotal
if ($#found == 0 and $found0 eq $wanted_name) { } 0 0 0
Condition0%0/3
$#found == 0 and $found0 eq $wanted_name
!ll&&!rl&&r
000
MC/DC0%0/2
$#found == 0 and $found0 eq $wanted_name
$#found == 0 $found0 eq $wanted_name
Truth table0%0/3
A and B
A= $#found == 0B= $found0 eq $wanted_name
ABresult
0X0
100
111
1611 {
1612 0 ▶ rename "$jail_base/$found0", $wanted_path or die "1 rename($jail_base/$found0, $wanted_path) failed: $!";
Branch: 1 branch
BranchTrueFalseTotal
rename "$jail_base/$found0", $wanted_path or die "1 rename($jail_base/$found0, $wanted_path) failed: $!" 0 0 0
1613 0 rmdir $jail_base;
1614 }
1615 else
1616 {
1617 0 ▶ rename $jail_base, $wanted_path or die "2 rename($jail_base, $wanted_path) failed: $!";
Branch: 1 branch
BranchTrueFalseTotal
rename $jail_base, $wanted_path or die "2 rename($jail_base, $wanted_path) failed: $!" 0 0 0
1618 }
1619 }
1620 else
1621 {
1622 0 ▶ rename $jail_base, $wanted_path or die "3 rename($jail_base, $wanted_path) failed: $!";
Branch: 1 branch
BranchTrueFalseTotal
rename $jail_base, $wanted_path or die "3 rename($jail_base, $wanted_path) failed: $!" 0 0 0
1623 }
1624 0 $unpacked = $wanted_path;
1625 }
1626  
1627 # catch some patholigical cases.
1628 0 ▶ if (-f $unpacked and !-l $unpacked)
Branch: 1 branch
BranchTrueFalseTotal
if (-f $unpacked and not -l $unpacked) 0 0 0
Condition0%0/3
-f $unpacked and not -l $unpacked
!ll&&!rl&&r
000
MC/DC0%0/2
-f $unpacked and not -l $unpacked
-f $unpacked not -l $unpacked
Truth table0%0/3
A and not(B)
A= -f $unpackedB= not -l $unpacked
ABresult
0X0
100
111
1629 {
1630 0 ▶ if (!-s $unpacked)
Branch: 2 branches
BranchTrueFalseTotal
if (not -s $unpacked) { } 0 0 0
elsif (-s $unpacked eq (my $s = -s $args->{'src'})) { } 0 0 0
1631 {
1632 0 ▶ print STDERR "Ooops, only one empty file -> symlink back\n" if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1633 0 unlink $unpacked;
1634 0 symlink $args->{src}, $unpacked;
1635 }
1636 elsif (-s $unpacked eq (my $s = -s $args->{src}))
1637 {
1638 0 ▶ print STDERR "Hmm, same size ($s bytes) after unpacking???\n" if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1639 ## xz -dc -f behaves like cat, if called on an unknown file.
1640 ## Compare the files. If they are identical, stop this:
1641 0 ▶ if (File::Compare::cmp($args->{src}, $unpacked) == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (File::Compare::cmp($args->{"src"}, $unpacked) == 0) 0 0 0
1642 {
1643 0 ▶ print STDERR "Oops, identical -> symlink back\n" if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1644 0 unlink $unpacked;
1645 0 symlink $args->{src}, $unpacked;
1646 }
1647 }
1648 }
1649  
1650 0 my $diag = undef;
1651 0 ▶ $diag->{stderr} = $run_error if defined $run_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $run_error 0 0 0
1652 0 return ($unpacked, $diag);
1653 }
1654  
1655 sub _unused_pathname
1656 {
1657 0 ▶ my ($destdir, $wanted_name) = @_;
Subroutine _unused_pathname: not called CC=5 SCAR=34.0
1658 0 my $wanted_path = $destdir . "/" . $wanted_name;
1659  
1660 0 ▶ if (-e $wanted_path)
Branch: 1 branch
BranchTrueFalseTotal
if (-e $wanted_path) 0 0 0
1661 {
1662 ## try to come up with a very similar name, just different suffix.
1663 ## be compatible with path name shortening in unpack()
1664 0 my $test_path = $wanted_path . '._';
1665 0 for my $i ('', 1..999)
1666 {
1667 # All our mime detectors work on file contents, rather than on suffixes.
1668 # Thus messing with the suffix should be okay here.
1669 0 ▶ unless (-e $test_path.$i)
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $test_path . $i) 0 0 0
1670 {
1671 0 $wanted_path = $test_path.$i;
1672 0 last;
1673 }
1674 }
1675 }
1676 0 ▶ die "_unused_pathname failed: last attempt $wanted_path\n" if -e $wanted_path;
Branch: 1 branch
BranchTrueFalseTotal
if -e $wanted_path 0 0 0
1677 0 return $wanted_path;
1678 }
1679  
1680  
1681 sub _children_fuser
1682 {
1683 0 ▶ my ($file, $ppid) = @_;
Subroutine _children_fuser: not called CC=19 SCAR=59.4
1684 0 ▶ $ppid ||= 1;
Condition0%0/2
$ppid ||= 1
l!l
00
MC/DC0%0/1
$ppid ||= 1
$ppid
Truth table0%0/2
A
A= $ppid
Aresult
11
00
1685 0 $file = Cwd::abs_path($file);
1686  
1687 0 ▶ opendir DIR, "/proc" or die "opendir /proc failed: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
opendir DIR, "/proc" or die "opendir /proc failed: $!\n" 0 0 0
1688 0 my %p = map { $_ => {} } grep { /^\d+$/ } readdir DIR;
1689 0 closedir DIR;
1690  
1691 # get all procs, and their parent pids
1692 0 for my $p (keys %p)
1693 {
1694 0 ▶ if (open IN, "<", "/proc/$p/stat")
Branch: 1 branch
BranchTrueFalseTotal
if (open IN, "<", "/proc/$p/stat") 0 0 0
1695 {
1696 # don't care if open fails. the process may have exited.
1697 0 my $text = join '', <IN>;
1698 0 close IN;
1699 0 ▶ if ($text =~ m{\((.*)\)\s+(\w)\s+(\d+)}s)
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /\((.*)\)\s+(\w)\s+(\d+)/s) 0 0 0
1700 {
1701 0 $p{$p}{cmd} = $1;
1702 0 $p{$p}{state} = $2;
1703 0 $p{$p}{ppid} = $3;
1704 }
1705 }
1706 }
1707  
1708 # Weed out those who are not in our family
1709 0 ▶ if ($ppid > 1)
Branch: 1 branch
BranchTrueFalseTotal
if ($ppid > 1) 0 0 0
1710 {
1711 0 for my $p (keys %p)
1712 {
1713 0 my $family = 0;
1714 0 my $pid = $p;
1715 0 ▶ while ($pid)
Branch: 1 branch
BranchTrueFalseTotal
if ($pid) 0 0 0
1716 {
1717 # Those that have ppid==1 may also belong to our family.
1718 # We never know.
1719 0 ▶ if ($pid == $ppid or $pid == 1)
Branch: 1 branch
BranchTrueFalseTotal
if ($pid == $ppid or $pid == 1) 0 0 0
Condition0%0/3
$pid == $ppid or $pid == 1
l!l&&r!l&&!r
000
MC/DC0%0/2
$pid == $ppid or $pid == 1
$pid == $ppid $pid == 1
Truth table0%0/3
A or B
A= $pid == $ppidB= $pid == 1
ABresult
1X1
011
000
1720 {
1721 0 $family = 1;
1722 0 last;
1723 }
1724 0 ▶ last unless $p{$pid};
Branch: 1 branch
BranchTrueFalseTotal
unless $p{$pid} 0 0 0
1725 0 $pid = $p{$pid}{ppid};
1726 }
1727 0 ▶ delete $p{$p} unless $family;
Branch: 1 branch
BranchTrueFalseTotal
unless $family 0 0 0
1728 }
1729 }
1730  
1731 0 my %o; # matching open files are recorded here
1732  
1733 # see what files they have open
1734 0 for my $p (keys %p)
1735 {
1736 0 ▶ if (opendir DIR, "/proc/$p/fd")
Branch: 1 branch
BranchTrueFalseTotal
if (opendir DIR, "/proc/$p/fd") 0 0 0
1737 {
1738 0 my @l = grep { /^\d+$/ } readdir DIR;
1739 0 closedir DIR;
1740 0 for my $l (@l)
1741 {
1742 0 my $r = readlink("/proc/$p/fd/$l");
1743 0 ▶ next unless defined $r;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 0 0 0
1744 # warn "$p, $l, $r\n";
1745 0 ▶ if ($r eq $file)
Branch: 1 branch
BranchTrueFalseTotal
if ($r eq $file) 0 0 0
1746 {
1747 0 ▶ $o{$p}{cmd} ||= $p{$p}{cmd};
Condition0%0/3
$o{$p}{"cmd"} ||= $p{$p}{"cmd"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$o{$p}{"cmd"} ||= $p{$p}{"cmd"}
$o{$p}{"cmd"} $p{$p}{"cmd"}
Truth table0%0/3
A ||= B
A= $o{$p}{"cmd"}B= $p{$p}{"cmd"}
ABresult
1X1
011
000
1748 0 $o{$p}{fd}{$l} = { file => $file };
1749 }
1750 }
1751 }
1752 }
1753 0 return \%o;
1754 }
1755  
1756 # see if we can read the file offset of a file descriptor, and the size of its file.
1757 sub _fuser_offset
1758 {
1759 0 ▶ my ($p) = @_;
Subroutine _fuser_offset: not called CC=6 SCAR=37.4
1760 0 for my $pid (keys %$p)
1761 {
1762 0 for my $fd (keys %{$p->{$pid}{fd}})
1763 {
1764 0 ▶ if (open IN, "/proc/$pid/fdinfo/$fd")
Branch: 1 branch
BranchTrueFalseTotal
if (open IN, "/proc/$pid/fdinfo/$fd") 0 0 0
1765 {
1766 0 ▶ while (defined (my $line = <IN>))
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline IN)) 0 0 0
1767 {
1768 0 chomp $line;
1769 0 ▶ $p->{$pid}{fd}{$fd}{$1} = $2 if $line =~ m{^(\w+):\s+(.*)\b};
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^(\w+):\s+(.*)\b/ 0 0 0
1770 }
1771 }
1772 0 close IN;
1773 0 $p->{$pid}{fd}{$fd}{size} = -s $p->{$pid}{fd}{$fd}{file};
1774 }
1775 }
1776 }
1777  
1778  
1779 sub _prep_configdir
1780 {
1781 0 ▶ my ($self) = @_;
Subroutine _prep_configdir: not called CC=7 SCAR=40.3
1782 0 my $dir = "/tmp/file_unpack_$$/";
1783 0 mkpath($dir);
1784 0 my $j = $self->{json}->allow_nonref();
1785  
1786 0 open my $SH, ">", "$dir/config.sh";
1787 0 open my $JS, ">", "$dir/config.js";
1788  
1789 0 print $JS "{\n";
1790  
1791 0 for my $group ('', 'minfree', 'exclude')
1792 {
1793 0 ▶ my $h_ref = ($group eq '') ? $self : $self->{$group};
Branch: 1 branch
BranchTrueFalseTotal
$group eq '' ? : 0 0 0
1794 0 for my $k (sort keys %$h_ref)
1795 {
1796 0 my $val = $h_ref->{$k};
1797 0 ▶ next if $k eq 'recursion_level';
Branch: 1 branch
BranchTrueFalseTotal
if $k eq "recursion_level" 0 0 0
1798 0 ▶ next if ref $val; # we only take scalars.
Branch: 1 branch
BranchTrueFalseTotal
if ref $val 0 0 0
1799 0 ▶ my $name = ($group eq '') ? $k : "${group}_$k";
Branch: 1 branch
BranchTrueFalseTotal
$group eq '' ? : 0 0 0
1800 0 printf $SH "%s=%s\n", shell_quote(uc "fu_$name"), shell_quote($val);
1801 0 printf $JS "%s:%s,\n", $j->encode($name), $j->encode($val);
1802 }
1803 }
1804  
1805 0 print $SH "FU_VERSION=$VERSION\n";
1806 0 print $JS qq["fu_version":"$VERSION"\n}\n];
1807  
1808 0 close $SH;
1809 0 close $JS;
1810 0 return $dir;
1811 }
1812  
1813  
1814 =head2 mime_helper_dir mime_helper
1815  
1816 $u->mime_helper_dir($dir, ...)
1817 $u->mime_helper($mime_name, $suffix_regexp, \@argv, @redir, ...)
1818  
1819 Registers one or more directories where external MIME helper programs are found.
1820 Helpers plugins are shellscripts that server as specialized MIME type handlers for unpacking.
1821 A list of helpers comes builtin interfacing most well-known archivers. This list can be appended to using the mime_helper_dir() or mime_helper() methods.
1822 Multiple directories can be registered, They are searched in reverse order, i.e.
1823 last added takes precedence. Any external MIME helper takes precedence over built-in code.
1824  
1825 The suffix_regexp is used to derive the destination name from the source name.
1826 It is not used for selecting helpers.
1827  
1828 When collecting external helper scripts via C<mime_helper_dir()>, there is no C<suffix_regexp>. Instead,
1829 external helper scripts can explicitly create a toplevel directory with the desired name.
1830  
1831 Helpers are mapped to MIME types by their mime_name. The name can be constructed
1832 from the MIME type by replacing the '/' with a '=' character, and by using the
1833 word 'ANY' as a wildcard component. The '=' character is interpreted as an
1834 implicit '=ANY+' if needed.
1835  
1836 Examples:
1837  
1838 Mimetype helper names tried from top to bottom
1839 -----------------------------------------------------------------
1840 image/png image=png
1841 image=ANY
1842 image
1843 ANY=png
1844 ANY=ANY
1845 ANY
1846  
1847 application/vnd.oasis+zip application=vnd.oasis+zip
1848 application=ANY+zip
1849 application=ANYzip
1850 application=zip
1851 application=ANY
1852 ...
1853
1854 A trailing '=ANY' is implicit, as shown by these examples.
1855 The rules for precedence are this:
1856  
1857 =over
1858  
1859 =item *
1860  
1861 Search in the latest directory is exhaused first, then the previously added directory is considered in turn,
1862 up to all directories have been traversed, or until a matching helper is found.
1863
1864 =item *
1865  
1866 A matching name with wildcards has lower precedence than a matching name without.
1867  
1868 =item *
1869  
1870 A wildcard before the '=' sign lowers precedence more than one after it.
1871  
1872 =back
1873  
1874 The mapping takes place when C<mime_helper_dir> is called. Adding helper scripts to a directory
1875 afterwards has no effect. C<mime_helper> does not do any implicit expansions. Call it
1876 multiple times with the same helper command and different names if needed.
1877 The default argument list is "%(src)s %(destfile)s %(destdir)s %(mime)s %(descr)s %(configdir)s" --
1878 this is applied, if no args are given and no redirections are given. See also C<unpack> for more semantics and how a helper should behave.
1879  
1880 Both methods return an ARRAY-ref of HASHes describing all known (old and newly added) mime helpers.
1881  
1882 =cut
1883 9 my @def_mime_helper_fmt = qw(%(src)s %(destfile)s %(destdir)s %(mime)s %(descr)s %(configdir)s);
1884  
1885 sub _subst_args
1886 {
1887 0 ▶ my $f = Text::Sprintf::Named->new({fmt => $_[0]});
Subroutine _subst_args: not called CC=1 SCAR=6.9
1888 0 return $f->format({args => $_[1]});
1889 }
1890  
1891 sub mime_helper
1892 {
1893 182 ▶ my ($self, $name, $suffix_re, @args) = @_;
Subroutine mime_helper: called CC=7 SCAR=21.2
Pod documented
1894 182 ▶ @args = ($name) unless @args;
Branch: 1 branch
BranchTrueFalseTotal
unless @args 0 182 182
1895 182 ▶ @args = ([@args]) unless ref $args[0];
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args[0] 0 182 182
1896 182 ▶ push @{$args[0]}, @def_mime_helper_fmt unless $#{$args[0]} or defined $args[1];
Branch: 1 branch
BranchTrueFalseTotal
unless $#{$args[0];} or defined $args[1] 0 182 182
Condition66%2/3
$#{$args[0];} or defined $args[1]
l!l&&r!l&&!r
154280
MC/DC0%0/2
$#{$args[0];} or defined $args[1]
$#{$args[0];} defined $args[1]
Truth table66%2/3
A or B
A= $#{$args[0];}B= defined $args[1]
ABresult
1X1
011
000
1897  
1898 # cut away the path prefix from name. And use / instead of = in the mime name.
1899 182 $name =~ s{(.*/)?(.*?)=(.*?)$}{$2=$3};
1900  
1901 182 ▶ unless ($name =~ m{[/=]})
Branch: 1 branch
BranchTrueFalseTotal
unless ($name =~ m[[/=]]) 0 182 182
1902 {
1903 0 ▶ print STDERR "mime_helper '$name' needs a '=' or '/'.\n" if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1904 0 return $self->{mime_helper};
1905 }
1906  
1907 182 my $pat = "^\Q$name\E\$";
1908 182 $pat =~ s{\\=}{/(?:x-|ANY\\+)?};
1909 182 $pat =~ s{\\%}{ANY}g;
1910 182 $pat =~ s{^\^ANY}{};
1911 182 $pat =~ s{ANY\$$}{};
1912 182 $pat =~ s{ANY}{\\b\[\^\/\]+\\b}g;
1913 182 unshift @{$self->{mime_helper}},
1914 {
1915 name => $name, pat => $pat, suffix_re => $suffix_re,
1916 fmt_p => fmt_run_shellcmd(@args), argvv => \@args
1917 };
1918  
1919 182 delete $self->{mime_orcish}; # to be rebuilt in find_mime_helper()
1920  
1921 182 return $self->{mime_helper};
1922 }
1923  
1924 =head2 list
1925  
1926 Returns an ARRAY of preformatted patterns and MIME helpers.
1927  
1928 Example:
1929  
1930 printf @$_ for $u->list();
1931  
1932 =cut
1933  
1934 sub list
1935 {
1936 1 ▶ my ($self) = @_;
Subroutine list: called CC=4 SCAR=13.9
Pod documented
1937  
1938 1 my $width = 10;
1939 1 for my $m (@{$self->{mime_helper}})
1940 {
1941 26 ▶ $width = length($m->{pat}) if length($m->{pat}) > $width;
Branch: 1 branch
BranchTrueFalseTotal
if length $m->{"pat"} > $width 5 21 26
1942 }
1943  
1944 1 my @r;
1945 1 for my $m (@{$self->{mime_helper}})
1946 {
1947 26 push @r, [ "%-${width}s %s\n", $m->{pat}, $m->{fmt_p} ];
1948 }
1949 1 return @r;
1950 }
1951  
1952 sub mime_helper_dir
1953 {
1954 0 ▶ my ($self, @dirs) = @_;
Subroutine mime_helper_dir: not called CC=10 SCAR=47.0
Pod documented
1955  
1956 0 for my $d (@dirs)
1957 {
1958 0 my %h;
1959 0 ▶ if (opendir DIR, $d)
Branch: 1 branch
BranchTrueFalseTotal
if (opendir DIR, $d) { } 0 0 0
1960 {
1961 0 %h = map { $_ => { a => "$d/$_" } } grep { -f "$d/$_" } readdir DIR;
1962 0 closedir DIR;
1963 }
1964 else
1965 {
1966 0 carp "Cannot opendir $d: $!, skipped\n";
1967 }
1968  
1969 # add =ANY suffix, if missing
1970 0 for my $h (keys %h)
1971 {
1972 0 ▶ if ($h !~ m{[/=]})
Branch: 1 branch
BranchTrueFalseTotal
unless ($h =~ m[[/=]]) 0 0 0
1973 {
1974 0 my $h2 = $h . "=ANY";
1975 0 ▶ $h{$h2} = { %{$h{$h}} } unless defined $h{$h2};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $h{$h2} 0 0 0
1976 }
1977 }
1978  
1979 # not needed, this is implicit in mime_helper()/$pat
1980 #
1981 # # add expansion of = to =ANY+, if missing
1982 # for my $h (keys %h)
1983 # {
1984 # next if $h =~ m{=ANY+};
1985 # my $h2 = $h; $h2 =~ s{=}{=ANY+};
1986 # $h{$h2} = $h{$h} unless defined $h{$h2};
1987 # }
1988  
1989 # calculate priorities
1990 0 for my $h (keys %h)
1991 {
1992 0 my $n = 1000000;
1993 0 my $p = 1000;
1994 0 ▶ while ($h =~ m{(ANY|=)}g)
Branch: 1 branch
BranchTrueFalseTotal
if ($h =~ /(ANY|=)/g) 0 0 0
1995 {
1996 0 ▶ if ($1 eq '=')
Branch: 1 branch
BranchTrueFalseTotal
if ($1 eq '=') { } 0 0 0
1997 {
1998 0 $n = 1000;
1999 }
2000 else
2001 {
2002 0 $p += $n;
2003 }
2004 }
2005 # longer length has prio over shorter length. Hmm, this is ineffective, isnt it?
2006 0 $h{$h}{p} = $p - length($h);
2007 }
2008  
2009 # Now push them, sorted by prio.
2010 # Smaller prio_number is better. Later addition is prefered.
2011 0 for my $h (sort { $h{$b}{p} <=> $h{$a}{p} } keys %h)
2012 {
2013 # do not ruin the original name by resolving symlinks and such.
2014 0 $self->mime_helper($h, undef, [Cwd::fast_abs_path($h{$h}{a})]);
2015 }
2016 }
2017 0 return $self->{mime_helper};
2018 }
2019  
2020 =head2 find_mime_helper
2021  
2022 $u->find_mime_helper($mimetype)
2023  
2024 Returns a MIME helper suitable for unpacking the given $mimetype.
2025 If called in list context, a second return value indicates which
2026 mime helpers would be suitable, but could not be found in the system.
2027  
2028 =cut
2029  
2030 sub find_mime_helper
2031 {
2032 0 ▶ my ($self, $mimetype) = @_;
Subroutine find_mime_helper: not called CC=9 SCAR=45.0
Pod documented
2033 0 ▶ $mimetype = $mimetype->[0] if ref $mimetype eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $mimetype eq "ARRAY" 0 0 0
2034  
2035 return $self->{mime_orcish}{$mimetype}
2036 if defined $self->{mime_orcish}{$mimetype} and
2037 0 ▶ -f $self->{mime_orcish}{$mimetype}{argvv}[0][0];
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"mime_orcish"}{$mimetype} and -f $self->{"mime_orcish"}{$mimetype}{"argvv"}[0][0] 0 0 0
Condition0%0/3
defined $self->{"mime_orcish"}{$mimetype} and -f $self->{"mime_orcish"}{$mimetype}{"argvv"}[0][0]
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"mime_orcish"}{$mimetype} and -f $self->{"mime_orcish"}{$mimetype}{"argvv"}[0][0]
defined $self->{"mime_orcish"}{$mimetype} -f $self->{"mime_orcish"}{$mimetype}{"argvv"}[0][0]
Truth table0%0/3
A and B
A= defined $self->{"mime_orcish"}{$mimetype}B= -f $self->{"mime_orcish"}{$mimetype}{"argvv"}[0][0]
ABresult
0X0
100
111
2038
2039 0 my $r = undef;
2040 0 for my $h (@{$self->{mime_helper}})
2041 {
2042 0 ▶ if ($mimetype =~ m{$h->{pat}})
Branch: 1 branch
BranchTrueFalseTotal
if ($mimetype =~ /$h->{"pat"}/) 0 0 0
2043 {
2044 0 $self->_finalize_argvv($h);
2045 0 ▶ unless (-f $h->{argvv}[0][0])
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $h->{"argvv"}[0][0]) 0 0 0
2046 {
2047 0 push @{$r->{missing}}, $h->{argvv}[0][0];
2048 0 next;
2049 }
2050 0 $self->{mime_orcish}{$mimetype} = $h;
2051 0 ▶ return wantarray ? ($h, $r) : $h;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
2052 }
2053 }
2054 0 ▶ return wantarray ? (undef, $r) : undef;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
2055 }
2056  
2057 #
2058 # _finalize_argvv() executes a sub in 3 places:
2059 # The argvv ptr itself can be a sub:
2060 # this should return an array, where the
2061 # first element is the command (as an array-ref) and subsequent elements are
2062 # redirects. See run() for details.
2063 # One of the argvv elements is a sub:
2064 # this should return the command as an array-ref, if it is argvv[0],
2065 # or return one or more redirects.
2066 # One element of argvv[0] is a sub:
2067 # this should return one or more command names, options, arguments,
2068 #
2069 # Tricky part of the implementation is the in-place array expansion while iterating.
2070 #
2071 sub _finalize_argvv
2072 {
2073 0 ▶ my ($self, $h) = @_;
Subroutine _finalize_argvv: not called CC=9 SCAR=45.0
2074  
2075 0 my $update_fmt_p = 0;
2076 0 ▶ if (ref $h->{argvv} eq 'CODE')
Branch: 1 branch
BranchTrueFalseTotal
if (ref $h->{"argvv"} eq "CODE") 0 0 0
2077 {
2078 0 $h->{argvv} = [ $h->{argvv}->($self) ];
2079 0 $update_fmt_p++;
2080 }
2081  
2082 # If any part of LIST is an array, "foreach" will get very confused if you add or
2083 # remove elements within the loop body, for example with "splice". So don't do
2084 # that.
2085 # Sigh, we want do do exactly that, a sub may replace itself by any number of elements. Use booring C-style loop.
2086 0 my $last = $#{$h->{argvv}};
2087 0 ▶ for (my $idx = 0; $idx <= $last; $idx++)
Branch: 1 branch
BranchTrueFalseTotal
if ($idx <= $last) 0 0 0
2088 {
2089 0 ▶ if (ref $h->{argvv}[$idx] eq 'CODE')
Branch: 1 branch
BranchTrueFalseTotal
if (ref $h->{"argvv"}[$idx] eq "CODE") 0 0 0
2090 {
2091 0 my @r = $h->{argvv}[$idx]($self);
2092 0 splice @{$h->{argvv}}, $idx, 1, @r;
2093 0 $idx += $#r;
2094 0 $last +=$#r;
2095 0 $update_fmt_p++;
2096 }
2097 }
2098 0 $last = $#{$h->{argvv}};
2099 0 ▶ for (my $idx = 0; $idx <= $last; $idx++)
Branch: 1 branch
BranchTrueFalseTotal
if ($idx <= $last) 0 0 0
2100 {
2101 0 ▶ next unless ref $h->{argvv}[$idx] eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $h->{"argvv"}[$idx] eq "ARRAY" 0 0 0
2102 0 my $last1 = $#{$h->{argvv}[$idx]};
2103 0 ▶ for (my $idx1 = 0; $idx1 <= $last1; $idx1++)
Branch: 1 branch
BranchTrueFalseTotal
if ($idx1 <= $last1) 0 0 0
2104 {
2105 0 ▶ if (ref $h->{argvv}[$idx][$idx1] eq 'CODE')
Branch: 1 branch
BranchTrueFalseTotal
if (ref $h->{"argvv"}[$idx][$idx1] eq "CODE") 0 0 0
2106 {
2107 0 my @r = $h->{argvv}[$idx][$idx1]->($self);
2108 0 splice @{$h->{argvv}[$idx]}, $idx1, 1, @r;
2109 0 $idx1 += $#r;
2110 0 $last1 +=$#r;
2111 0 $update_fmt_p++;
2112 }
2113 }
2114 }
2115  
2116 0 ▶ $h->{fmt_p} = fmt_run_shellcmd($h) if $update_fmt_p;
Branch: 1 branch
BranchTrueFalseTotal
if $update_fmt_p 0 0 0
2117 }
2118  
2119 =head2 minfree
2120  
2121 $u->minfree(factor => 10, bytes => '100M', percent => '3%', warning => sub { .. })
2122  
2123 THESE TESTS ARE TO BE IMPLEMENTED.
2124  
2125 Guard the filesystem (destdir) against becoming full during C<unpack>.
2126 Before unpacking each source archive, the free space is measured and compared against three conditions:
2127  
2128 =over
2129  
2130 =item *
2131  
2132 The archive size multiplied with the given factor must fit into the filesystem.
2133  
2134 =item *
2135  
2136 The given number of bytes (in optional K, M, G, or T units) must be free.
2137  
2138 =item *
2139  
2140 The filesystem must have at least the given free percentage. The '%' character is optional.
2141
2142 =back
2143  
2144 The warning method is called if any of the above conditions fail. Its signature is:
2145 &warning->($pathname, $full_percentage, $free_bytes, $free_inodes);
2146 It is expected to print an appropriate warning message, and delay a few seconds.
2147 It should return 0 to cause a retry. It should return nonzero to continue unpacking.
2148 The default warning method prints a message to STDERR, waits 30 seconds, and returns 0.
2149  
2150 The filesystem may still become full and unpacking may fail, if e.g. factor was chosen lower than
2151 the average compression ratio of the archives.
2152  
2153 =cut
2154  
2155 sub _bytes_unit
2156 {
2157 14 ▶ my ($text) = @_;
Subroutine _bytes_unit: called CC=5 SCAR=19.4
2158 14 ▶ return int($1*1024) if $text =~ m{([\d\.]+)k}i;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /([\d\.]+)k/i 0 14 14
2159 14 ▶ return int($1*1024*1024) if $text =~ m{([\d\.]+)m}i;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /([\d\.]+)m/i 7 7 14
2160 7 ▶ return int($1*1024*1024*1024) if $text =~ m{([\d\.]+)g}i;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /([\d\.]+)g/i 7 0 7
2161 0 ▶ return int($1*1024*1024*1024*1024) if $text =~ m{([\d\.]+)t}i;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /([\d\.]+)t/i 0 0 0
2162 0 return int($text);
2163 }
2164  
2165 sub _unit_bytes
2166 {
2167 0 ▶ my ($number, $dec_places) = @_;
Subroutine _unit_bytes: not called CC=7 SCAR=40.3
2168 0 ▶ $dec_places = 2 unless defined $dec_places;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dec_places 0 0 0
2169 0 my $div = 1;
2170 0 my $unit = '';
2171 0 my $neg = '';
2172 0 ▶ if ($number < 0)
Branch: 1 branch
BranchTrueFalseTotal
if ($number < 0) 0 0 0
2173 {
2174 0 $neg = '-'; $number = -$number;
2175 }
2176 0 ▶ if ($number > $div * 1024)
Branch: 1 branch
BranchTrueFalseTotal
if ($number > $div * 1024) 0 0 0
2177 {
2178 0 $div *= 1024; $unit = 'k';
2179 0 ▶ if ($number > $div * 1024)
Branch: 1 branch
BranchTrueFalseTotal
if ($number > $div * 1024) 0 0 0
2180 {
2181 0 $div *= 1024; $unit = 'm';
2182 0 ▶ if ($number > $div * 1024)
Branch: 1 branch
BranchTrueFalseTotal
if ($number > $div * 1024) 0 0 0
2183 {
2184 0 $div *= 1024; $unit = 'g';
2185 0 ▶ if ($number > $div * 1024)
Branch: 1 branch
BranchTrueFalseTotal
if ($number > $div * 1024) 0 0 0
2186 {
2187 0 $div *= 1024; $unit = 't';
2188 }
2189 }
2190 }
2191 }
2192 0 return sprintf "%s%.*f%s", $neg, $dec_places, ($number / $div), $unit;
2193 }
2194  
2195 # see fs.pm/check_fs_health()
2196  
2197 sub minfree
2198 {
2199 7 ▶ my $self = shift;
Subroutine minfree: called CC=5 SCAR=16.6
Pod documented
2200 7 my %opt = @_;
2201  
2202 7 for my $i (qw(factor bytes percent))
2203 {
2204 21 ▶ $self->{minfree}{$i} = $opt{$i} if defined $opt{$i};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{$i} 0 21 21
2205 21 ▶ $self->{minfree}{$i} ||= 0;
Condition50%1/2
$self->{"minfree"}{$i} ||= 0
l!l
210
MC/DC0%0/1
$self->{"minfree"}{$i} ||= 0
$self->{"minfree"}{$i}
Truth table50%1/2
A
A= $self->{"minfree"}{$i}
Aresult
11
00
2206 }
2207 7 $self->{minfree}{bytes} = _bytes_unit($self->{minfree}{bytes});
2208 7 $self->{minfree}{percent} =~ s{%$}{};
2209 7 ▶ $self->{fs_warn} = $opt{warning} if ref $opt{warning};
Branch: 1 branch
BranchTrueFalseTotal
if ref $opt{"warning"} 7 0 7
2210 }
2211  
2212 =head2 mime
2213  
2214 $u->mime($filename)
2215  
2216 $u->mime(file => $filename)
2217  
2218 $u->mime(buf => "#!/bin ...", file => "what-was-read")
2219  
2220 $u->mime(fd => \*STDIN, file => "what-was-opened")
2221  
2222 Determines the MIME type (and optionally additional information) of a file.
2223 The file can be specified by filename, by a provided buffer or an opened file descriptor.
2224 For the latter two cases, specifying a filename is optional, and used only for diagnostics.
2225  
2226 C<mime> uses libmagic by Christos Zoulas exposed via File::LibMagic and also uses
2227 the shared-mime-info database from freedesktop.org exposed via
2228 File::MimeInfo::Magic, if available. Either one is sufficient, but having both
2229 is better. LibMagic sometimes says 'text/x-pascal', although we have a F<.desktop>
2230 file, or says 'text/plain', but has contradicting details in its description.
2231  
2232 C<File::MimeInfo::Magic::magic> is consulted where the libmagic output is dubious. E.g. when
2233 the desciption says something interesting like 'Debian binary package (format 2.0)' but the
2234 mimetype says 'application/octet-stream'. The combination of both libraries gives us
2235 excellent reliability in the critical field of MIME type recognition.
2236  
2237 This implementation also features multi-level MIME type recognition for efficient unpacking.
2238 When e.g. unpacking a large bzipped tar archive, this saves us from creating a
2239 huge temporary tar-file which C<unpack> would extract in a second step. The multi-level recognition
2240 returns 'application/x-tar+bzip2' in this case, and allows for a MIME helper
2241 to e.g. pipe the bzip2 contents into tar (which is exactly what 'tar jxvf'
2242 does, making a very simple and efficient MIME helper).
2243  
2244 C<mime> returns a 3 or 4 element arrayref with mimetype, charset, description, diff;
2245 where diff is only present when the libfile and shared-mime-info methods disagree.
2246  
2247 In case of 'text/plain', an additional rule based on file name suffix is used to allow
2248 recognition of well known plain text pack formats.
2249 We return 'text/x-suffix-XX+plain', where XX is one of the recognized suffixes
2250 (in all lower case and without the dot). E.g. a plain mmencoded file has no
2251 header and looks like 'plain/text' to all the known magic libraries. We
2252 recognize the suffixes .mm, .b64, and .base64 for this (case insignificant).
2253 A similar rule exitst for 'application/octect-stream'. It may trigger e.g. for
2254 LZMA compressed files which fail to provide a magic number.
2255  
2256 Examples:
2257
2258 [ 'text/x-perl', 'us-ascii', 'a /usr/bin/perl -w script text']
2259  
2260 [ 'text/x-mpegurl', 'utf-8', 'M3U playlist text',
2261 [ 'text/plain', 'application/x-mpegurl']]
2262  
2263 [ 'application/x-tar+bzip2, 'binary',
2264 "bzip2 compressed data, block size = 900k\nPOSIX tar archive (GNU)", ...]
2265  
2266 =cut
2267  
2268 sub mime
2269 {
2270 4 ▶ my ($self, @in) = @_;
Subroutine mime: called CC=92 SCAR=88.9
Pod documented
2271  
2272 4 my %in;
2273 4 ▶ %in = %{$in[0]} if !$#in and ref $in[0] eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if not $#in and ref $in[0] eq "HASH" 0 4 4
Condition66%2/3
not $#in and ref $in[0] eq "HASH"
!ll&&!rl&&r
130
MC/DC0%0/2
not $#in and ref $in[0] eq "HASH"
not $#in ref $in[0] eq "HASH"
Truth table66%2/3
not(A) and B
A= not $#inB= ref $in[0] eq "HASH"
ABresult
0X0
100
111
2274 4 ▶ unshift @in, 'file' if !$#in and !ref $in[0];
Branch: 1 branch
BranchTrueFalseTotal
unless $#in or ref $in[0] 3 1 4
Condition66%2/3
$#in or ref $in[0]
l!l&&r!l&&!r
103
MC/DC50%1/2
$#in or ref $in[0]
$#in ref $in[0]
Truth table66%2/3
A or B
A= $#inB= ref $in[0]
ABresult
1X1
011
000
2275 4 ▶ %in = @in if $#in > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $#in > 0 4 0 4
2276  
2277 4 ▶ my $flm = $self->{flm} ||= File::LibMagic->new();
Condition33%1/3
$self->{"flm"} ||= "File::LibMagic"->new
l!l&&r!l&&!r
004
MC/DC0%0/2
$self->{"flm"} ||= "File::LibMagic"->new
$self->{"flm"} "File::LibMagic"->new
Truth table33%1/3
A ||= B
A= $self->{"flm"}B= "File::LibMagic"->new
ABresult
1X1
011
000
2278  
2279 0 ▶ unless (defined $in{buf})
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $in{"buf"}) 0 0 0
2280 {
2281 0 my $fd = $in{fd};
2282 0 ▶ unless ($fd)
Branch: 1 branch
BranchTrueFalseTotal
unless ($fd) 0 0 0
2283 {
2284 open $fd, "<", $in{file} or
2285 0 ▶ return [ 'x-system/x-error', undef, "cannot open '$in{file}': $!" ];
Branch: 1 branch
BranchTrueFalseTotal
open $fd, "<", $in{"file"} or return ["x-system/x-error", undef, qq[cannot open '$in{"file"}': $!]] 0 0 0
2286 }
2287  
2288 0 ▶ my $f = $in{file}||'-';
Condition0%0/2
$in{'file'} || '-'
l!l
00
MC/DC0%0/1
$in{'file'} || '-'
$in{'file'}
Truth table0%0/2
A
A= $in{'file'}
Aresult
11
00
2289 0 $in{buf} = '';
2290 0 my $pos = tell $fd;
2291 ##bzip2 below needs a long buffer, or it returns 0.
2292 0 my $len = read $fd, $in{buf}, $UNCOMP_BUFSZ;
2293 0 ▶ return [ 'x-system/x-error', undef, "read '$f' failed: $!" ] unless defined $len;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $len 0 0 0
2294 0 ▶ return [ 'x-system/x-error', undef, "read '$f' failed: $len: $!" ] if $len < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $len < 0 0 0 0
2295 0 ▶ return [ 'text/x-empty', undef, 'empty' ] if $len == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $len == 0 0 0 0
2296 0 seek $fd, $pos, 0;
2297  
2298 0 ▶ close $fd unless $in{fd};
Branch: 1 branch
BranchTrueFalseTotal
unless $in{"fd"} 0 0 0
2299 }
2300  
2301  
2302 ## flm can say 'cannot open \'IP\' (No such file or directory)'
2303 ## flm can say 'CDF V2 Document, corrupt: Can\'t read SAT' (application/vnd.ms-excel)
2304 0 my $mime1 = $flm->checktype_contents($in{buf});
2305 0 ▶ if ($mime1 =~ m{, corrupt: } or $mime1 =~ m{^application/octet-stream\b})
Branch: 1 branch
BranchTrueFalseTotal
if ($mime1 =~ /, corrupt: / or $mime1 =~ m[^application/octet-stream\b]) 0 0 0
Condition0%0/3
$mime1 =~ /, corrupt: / or $mime1 =~ m[^application/octet-stream\b]
l!l&&r!l&&!r
000
MC/DC0%0/2
$mime1 =~ /, corrupt: / or $mime1 =~ m[^application/octet-stream\b]
$mime1 =~ /, corrupt: / $mime1 =~ m[^application/octet-stream\b]
Truth table0%0/3
A or B
A= $mime1 =~ /, corrupt: /B= $mime1 =~ m[^application/octet-stream\b]
ABresult
1X1
011
000
2306 {
2307 # application/x-iso9660-image is reported as application/octet-stream if the buffer is short.
2308 # iso images usually start with 0x8000 bytes of all '\0'.
2309 0 ▶ print STDERR "mime: readahead buffer $UNCOMP_BUFSZ too short\n" if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
2310 0 ▶ if (defined $in{file} and -f $in{file})
Branch: 1 branch
BranchTrueFalseTotal
if (defined $in{"file"} and -f $in{"file"}) 0 0 0
Condition0%0/3
defined $in{"file"} and -f $in{"file"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $in{"file"} and -f $in{"file"}
defined $in{"file"} -f $in{"file"}
Truth table0%0/3
A and B
A= defined $in{"file"}B= -f $in{"file"}
ABresult
0X0
100
111
2311 {
2312 0 ▶ print STDERR "mime: reopening $in{file}\n" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
2313 0 $mime1 = $flm->checktype_filename($in{file});
2314 }
2315 }
2316 0 ▶ print STDERR "flm->checktype_contents: $mime1\n" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
2317 0 ▶ $in{file} = '-' unless defined $in{file};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $in{"file"} 0 0 0
2318
2319 0 ▶ return [ 'x-system/x-error', undef, $mime1 ] if $mime1 =~ m{^cannot open};
Branch: 1 branch
BranchTrueFalseTotal
if $mime1 =~ /^cannot open/ 0 0 0
2320  
2321 # in SLES11 we get 'text/plain charset=utf-8' without semicolon.
2322 0 ▶ my $enc; ($mime1, $enc) = ($1,$2) if $mime1 =~ m{^(.*?);\s*(.*)$} or
Branch: 1 branch
BranchTrueFalseTotal
if $mime1 =~ /^(.*?);\s*(.*)$/ or $mime1 =~ /^(.*?)\s+(.*)$/ 0 0 0
Condition0%0/3
$mime1 =~ /^(.*?);\s*(.*)$/ or $mime1 =~ /^(.*?)\s+(.*)$/
l!l&&r!l&&!r
000
MC/DC0%0/2
$mime1 =~ /^(.*?);\s*(.*)$/ or $mime1 =~ /^(.*?)\s+(.*)$/
$mime1 =~ /^(.*?);\s*(.*)$/ $mime1 =~ /^(.*?)\s+(.*)$/
Truth table0%0/3
A or B
A= $mime1 =~ /^(.*?);\s*(.*)$/B= $mime1 =~ /^(.*?)\s+(.*)$/
ABresult
1X1
011
000
2323 $mime1 =~ m{^(.*?)\s+(.*)$};
2324 0 ▶ $enc =~ s{^charset=}{} if defined $enc;
Branch: 1 branch
BranchTrueFalseTotal
if defined $enc 0 0 0
2325 0 my @r = ($mime1, $enc, $flm->describe_contents($in{buf}) );
2326 0 my $mime2;
2327  
2328
2329 0 ▶ if ($mime1 =~ m{^application/xml})
Branch: 1 branch
BranchTrueFalseTotal
if ($mime1 =~ m[^application/xml]) 0 0 0
2330 {
2331 # This is horrible from a greedy text cruncher perspective:
2332 # although xml is a plain text syntax, it is reported by flm to be
2333 # outside text/*
2334 0 $r[0] = "text/x-application-xml";
2335 }
2336  
2337 0 ▶ if ($mime1 =~ m{^text/x-(?:pascal|fortran)$})
Branch: 2 branches
BranchTrueFalseTotal
if ($mime1 =~ m[^text/x-(?:pascal|fortran)$]) { } 0 0 0
elsif ($mime1 eq 'text/plain' and $r[2] =~ /(?:PostScript|font)/i or $mime1 eq 'application/postscript') { } 0 0 0
2338 {
2339 # xterm.desktop
2340 # ['text/x-pascal; charset=utf-8','UTF-8 Unicode Pascal program text']
2341 # 'application/x-desktop'
2342 #
2343 # Times-Roman.afm
2344 # ['text/x-fortran; charset=us-ascii','ASCII font metrics']
2345 # 'application/x-font-afm'
2346 #
2347 # debian/rules
2348 # ['text/x-pascal; charset=us-ascii','a /usr/bin/make -f script text']
2349 # 'text/x-makefile'
2350 0 ▶ if ($mime2 ||= eval { open my $fd,'<',\$in{buf}; File::MimeInfo::Magic::magic($fd); })
Branch: 1 branch
BranchTrueFalseTotal
if ($mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }) 0 0 0
Condition0%0/3
$mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
$mime2 eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
Truth table0%0/3
A ||= B
A= $mime2B= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
ABresult
1X1
011
000
2351 {
2352 0 ▶ $r[0] = "text/$1" if $mime2 =~ m{/(\S+)};
Branch: 1 branch
BranchTrueFalseTotal
if $mime2 =~ m[/(\S+)] 0 0 0
2353 }
2354 }
2355 ▶ elsif (($mime1 eq 'text/plain' and $r[2] =~ m{(?:PostScript|font)}i)
Condition0%0/6
$mime1 eq "text/plain" and $r[2] =~ /(?:PostScript|font)/i or $mime1 eq "application/postscript"
l!l&&r!l&&!r
000
$mime1 eq "text/plain" and $r[2] =~ /(?:PostScript|font)/i
!ll&&!rl&&r
000
MC/DC0%0/3
$mime1 eq "text/plain" and $r[2] =~ /(?:PostScript|font)/i or $mime1 eq "application/postscript"
$mime1 eq "text/plain" $r[2] =~ /(?:PostScript|font)/i $mime1 eq "application/postscript"
Truth table0%0/5
A and B or C
A= $mime1 eq "text/plain"B= $r[2] =~ /(?:PostScript|font)/iC= $mime1 eq "application/postscript"
ABCresult
11X1
0X11
1011
0X00
1000
2356 or ($mime1 eq 'application/postscript'))
2357 {
2358 # 11.3 says:
2359 # IPA.pfa
2360 # ['text/plain; charset=us-ascii','PostScript Type 1 font text (OmegaSerifIPA 001.000)']
2361 # sles11 says:
2362 # IPA.pfa
2363 # ['application/postscript', undef, 'PostScript document text']
2364 #
2365 # mime2 = 'application/x-font-type1'
2366 # $mime2 = eval { File::MimeInfo::Magic::mimetype($in{file}); };
2367 0 ▶ $mime2 ||= eval { open my $fd,'<',\$in{buf}; File::MimeInfo::Magic::magic($fd); };
Condition0%0/3
$mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
$mime2 eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
Truth table0%0/3
A ||= B
A= $mime2B= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
ABresult
1X1
011
000
2368 0 ▶ if ($mime2 and $mime2 =~ m{^(.*)/(.*)$})
Branch: 1 branch
BranchTrueFalseTotal
if ($mime2 and $mime2 =~ m[^(.*)/(.*)$]) 0 0 0
Condition0%0/3
$mime2 and $mime2 =~ m[^(.*)/(.*)$]
!ll&&!rl&&r
000
MC/DC0%0/2
$mime2 and $mime2 =~ m[^(.*)/(.*)$]
$mime2 $mime2 =~ m[^(.*)/(.*)$]
Truth table0%0/3
A and B
A= $mime2B= $mime2 =~ m[^(.*)/(.*)$]
ABresult
0X0
100
111
2369 {
2370 0 my ($a,$b) = ($1,$2);
2371 0 ▶ $a = 'text' if $r[2] =~ m{\btext\b}i;
Branch: 1 branch
BranchTrueFalseTotal
if $r[2] =~ /\btext\b/i 0 0 0
2372 0 $r[0] = "$a/$b";
2373 }
2374 }
2375  
2376 0 ▶ if ($r[0] eq 'text/plain' or
Branch: 1 branch
BranchTrueFalseTotal
if ($r[0] eq "text/plain" or $r[0] eq "application/octet-stream") 0 0 0
Condition0%0/3
$r[0] eq "text/plain" or $r[0] eq "application/octet-stream"
l!l&&r!l&&!r
000
MC/DC0%0/2
$r[0] eq "text/plain" or $r[0] eq "application/octet-stream"
$r[0] eq "text/plain" $r[0] eq "application/octet-stream"
Truth table0%0/3
A or B
A= $r[0] eq "text/plain"B= $r[0] eq "application/octet-stream"
ABresult
1X1
011
000
2377 $r[0] eq 'application/octet-stream')
2378 {
2379 # hmm, are we sure? No, if the description contradicts:
2380 #
2381 0 ▶ $r[0] = "text/x-uuencode" if $r[2] eq 'uuencoded or xxencoded text';
Branch: 1 branch
BranchTrueFalseTotal
if $r[2] eq "uuencoded or xxencoded text" 0 0 0
2382  
2383 # bin/floor
2384 # ['text/x-pascal; charset=us-ascii','a /usr/bin/tclsh script text']
2385 # 'text/plain'
2386 0 ▶ $r[0] = "text/x-$2" if $r[2] =~ m{^a (\S*/)?([^/\s]+) .*script text$}i;
Branch: 1 branch
BranchTrueFalseTotal
if $r[2] =~ m[^a (\S*/)?([^/\s]+) .*script text$]i 0 0 0
2387 0 ▶ if ($r[2] =~ m{\bimage\b})
Branch: 1 branch
BranchTrueFalseTotal
if ($r[2] =~ /\bimage\b/) 0 0 0
2388 {
2389 # ./opengl/test.tga
2390 # ['application/octet-stream; charset=binary','Targa image data - RGB 128 x 128']
2391 # 'image/x-tga'
2392 0 ▶ $mime2 ||= eval { open my $fd,'<',\$in{buf}; File::MimeInfo::Magic::magic($fd); };
Condition0%0/3
$mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
$mime2 eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
Truth table0%0/3
A ||= B
A= $mime2B= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
ABresult
1X1
011
000
2393 0 ▶ $r[0] = $mime2 if $mime2 and $mime2 =~ m{^image/};
Branch: 1 branch
BranchTrueFalseTotal
if $mime2 and $mime2 =~ m[^image/] 0 0 0
Condition0%0/3
$mime2 and $mime2 =~ m[^image/]
!ll&&!rl&&r
000
MC/DC0%0/2
$mime2 and $mime2 =~ m[^image/]
$mime2 $mime2 =~ m[^image/]
Truth table0%0/3
A and B
A= $mime2B= $mime2 =~ m[^image/]
ABresult
0X0
100
111
2394 }
2395 }
2396  
2397 0 ▶ if ($r[0] eq 'application/octet-stream')
Branch: 1 branch
BranchTrueFalseTotal
if ($r[0] eq "application/octet-stream") 0 0 0
2398 {
2399 # it can't get much worse, can it?
2400 ##
2401 # dotdot.tar.lzma
2402 # {'File::MimeInfo::Magic' => 'application/x-lzma-compressed-tar'} -- no, that was suffix based!
2403 # {'File::LibMagic' => ['application/octet-stream; charset=binary','data']}
2404 0 ▶ $mime2 ||= eval { open my $fd,'<',\$in{buf}; File::MimeInfo::Magic::magic($fd); };
Condition0%0/3
$mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
$mime2 eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
Truth table0%0/3
A ||= B
A= $mime2B= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
ABresult
1X1
011
000
2405 #
2406 # File::LibMagic misreads monotone-0.99.1/monotone.info-1 as app/bin
2407 # File::MimeInfo::Magic::magic() returns undef for that one.
2408 # But perl itself does not agree:
2409 0 ▶ $mime2 ||= 'application/x-text-mixed' if -T $in{file};
Branch: 1 branch
BranchTrueFalseTotal
if -T $in{"file"} 0 0 0
Condition0%0/2
$mime2 ||= "application/x-text-mixed"
l!l
00
MC/DC0%0/1
$mime2 ||= "application/x-text-mixed"
$mime2
Truth table0%0/2
A
A= $mime2
Aresult
11
00
2410  
2411 0 ▶ $r[0] = $mime2 if $mime2;
Branch: 1 branch
BranchTrueFalseTotal
if $mime2 0 0 0
2412 }
2413  
2414 0 ▶ if ($r[0] eq 'application/octet-stream')
Branch: 1 branch
BranchTrueFalseTotal
if ($r[0] eq "application/octet-stream") 0 0 0
2415 {
2416 0 ▶ if ($r[2] =~ m{\bcpio\s+archive\b}i)
Branch: 1 branch
BranchTrueFalseTotal
if ($r[2] =~ /\bcpio\s+archive\b/i) 0 0 0
2417 {
2418 # Mac pax files are gzipped cpio: 'ASCII cpio archive (pre-SVR4 or odc)'
2419 0 $r[0] = 'application/x-cpio';
2420 }
2421 }
2422  
2423 0 my $uncomp_buf = '';
2424  
2425 0 ▶ if ($r[0] eq 'application/octet-stream')
Branch: 1 branch
BranchTrueFalseTotal
if ($r[0] eq "application/octet-stream") 0 0 0
2426 {
2427 ## lzma is an extremly bad format. It has no magic.
2428 #
2429 # WARNING from Compress::unLZMA
2430 # "This version only implements in-memory decompression (patches are welcomed).
2431 # There is no way to recognize a valid LZMA encoded file with the SDK.
2432 # So, in some cases, you can crash your script if you try to uncompress a
2433 # non valid LZMA encoded file."
2434 # Does this also apply to us?
2435 #
2436 # -- hmm, maybe we better leave it at calling lzcat.
2437 # Trade in "always a bit expensive" versus "sometimes crashing"...
2438 #
2439 # my $lztest = `sh -c "/usr/bin/lzcat < $in{file} | head -c 1k > /dev/null" 2>&1`;
2440 # # -> /usr/bin/lzcat: (stdin): File format not recognized
2441 # if ($lztest !~ m{(not recognized|error)}i)
2442 # {
2443 # $r[0] = 'application/x-lzma';
2444 # }
2445  
2446 0 ▶ if (10 < length $in{buf})
Branch: 1 branch
BranchTrueFalseTotal
if (10 < length $in{"buf"}) 0 0 0
2447 {
2448 9 ▶ no strict 'subs'; # Compress::Raw::Lzma::AloneDecoder, LZMA_OK, LZMA_STREAM_END
Subroutine BEGIN: called CC=1 SCAR=0.0
2449  
2450 0 my $saved_input = $in{buf};
2451 0 my ($lz, $stat) = eval { Compress::Raw::Lzma::AloneDecoder->new(-Bufsize => $UNCOMP_BUFSZ, -LimitOutput => 1); };
2452 0 ▶ if ($lz)
Branch: 1 branch
BranchTrueFalseTotal
if ($lz) 0 0 0
2453 {
2454 0 $stat = $lz->code($in{buf}, $uncomp_buf);
2455 0 ▶ if (($stat == LZMA_OK or $stat == LZMA_STREAM_END)
Branch: 1 branch
BranchTrueFalseTotal
if ($stat == "LZMA_OK" || $stat == "LZMA_STREAM_END" and length $uncomp_buf > length $saved_input) 0 0 0
Condition0%0/6
$stat == "LZMA_OK" || $stat == "LZMA_STREAM_END" and length $uncomp_buf > length $saved_input
!ll&&!rl&&r
000
$stat == "LZMA_OK" or $stat == "LZMA_STREAM_END"
l!l&&r!l&&!r
000
MC/DC0%0/3
$stat == "LZMA_OK" || $stat == "LZMA_STREAM_END" and length $uncomp_buf > length $saved_input
$stat == "LZMA_OK" $stat == "LZMA_STREAM_END" length $uncomp_buf > length $saved_input
Truth table0%0/5
A or B and C
A= $stat == "LZMA_OK"B= $stat == "LZMA_STREAM_END"C= length $uncomp_buf > length $saved_input
ABCresult
00X0
1X00
0100
1X11
0111
2456 and
2457 (length($uncomp_buf) > length($saved_input)))
2458 {
2459 0 $r[0] = "application/x-lzma";
2460 0 $r[2] = "LZMA compressed data, no magic";
2461 }
2462 # This decompressor consumes the input.
2463 0 $in{buf} = $saved_input;
2464 }
2465 }
2466 }
2467 # printf STDERR "in-buf = %d bytes\n", length($in{buf});
2468  
2469 0 ▶ if ($r[0] =~ m{^application/(?:x-)?gzip$})
Branch: 1 branch
BranchTrueFalseTotal
if ($r[0] =~ m[^application/(?:x-)?gzip$]) 0 0 0
2470 {
2471 0 my ($gz, $stat) = eval { new Compress::Raw::Zlib::Inflate( -WindowBits => WANT_GZIP() ); };
2472 0 ▶ if ($gz)
Branch: 1 branch
BranchTrueFalseTotal
if ($gz) 0 0 0
2473 {
2474 0 my $stat = $gz->inflate($in{buf}, $uncomp_buf);
2475 # printf STDERR "stat=%s, uncomp=%d bytes \n", $stat, length($uncomp_buf);
2476 }
2477 }
2478  
2479 ## bzip2 is not nice for stacked mime checking.
2480 ## It needs a huge input buffer that we do not normally provide.
2481 ## We only support it at the top of a stack, where we acquire enough additional
2482 ## input until bzip2 is happy.
2483 0 ▶ if ($r[0] =~ m{^application/(?:x-)?bzip2$} && !$in{recursion})
Branch: 1 branch
BranchTrueFalseTotal
if ($r[0] =~ m[^application/(?:x-)?bzip2$] and not $in{"recursion"}) 0 0 0
Condition0%0/3
$r[0] =~ m[^application/(?:x-)?bzip2$] and not $in{"recursion"}
!ll&&!rl&&r
000
MC/DC0%0/2
$r[0] =~ m[^application/(?:x-)?bzip2$] and not $in{"recursion"}
$r[0] =~ m[^application/(?:x-)?bzip2$] not $in{"recursion"}
Truth table0%0/3
A and not(B)
A= $r[0] =~ m[^application/(?:x-)?bzip2$]B= not $in{"recursion"}
ABresult
0X0
100
111
2484 {
2485 0 my $limitOutput = 1;
2486 0 my ($bz, $stat) = eval { new Compress::Raw::Bunzip2 0, 0, 0, 0, $limitOutput; };
2487 0 ▶ if ($bz)
Branch: 1 branch
BranchTrueFalseTotal
if ($bz) 0 0 0
2488 {
2489 ## this only works if this is a first level call.
2490 0 ▶ open my $IN, "<", $in{file} unless $in{file} eq '-';
Branch: 1 branch
BranchTrueFalseTotal
unless $in{"file"} eq "-" 0 0 0
2491 0 seek $IN, length($in{buf}), 0;
2492 0 ▶ while (!length $uncomp_buf)
Branch: 1 branch
BranchTrueFalseTotal
unless (length $uncomp_buf) 0 0 0
2493 {
2494 0 my $stat = $bz->bzinflate($in{buf}, $uncomp_buf);
2495 # $bz->bzflush($uncomp_buf); # wishful thinking....
2496 0 ▶ last if length($in{buf}); # did not consume, strange.
Branch: 1 branch
BranchTrueFalseTotal
if length $in{"buf"} 0 0 0
2497 0 ▶ last if length $stat; # something wrong, or file ends.
Branch: 1 branch
BranchTrueFalseTotal
if length $stat 0 0 0
2498 0 ▶ last unless read $IN, $in{buf}, 10*1024, length($in{buf}); # try to get more data
Branch: 1 branch
BranchTrueFalseTotal
unless read $IN, $in{"buf"}, 10240, length $in{"buf"} 0 0 0
2499 }
2500 0 my $slurped = tell $IN; # likely to get ca. 800k yacc!
2501 0 close $IN;
2502 # use Data::Dumper; warn Dumper $stat, length($in{buf}), length($uncomp_buf), "slurped=$slurped";
2503 }
2504 }
2505  
2506 ## try to get at the second level mime type, for some well known linear compressors.
2507 0 ▶ while (length $uncomp_buf && $r[0] =~ m{^application/(x-)?([+\w]+)$})
Branch: 1 branch
BranchTrueFalseTotal
if (length $uncomp_buf and $r[0] =~ m[^application/(x-)?([+\w]+)$]) 0 0 0
Condition0%0/3
length $uncomp_buf and $r[0] =~ m[^application/(x-)?([+\w]+)$]
!ll&&!rl&&r
000
MC/DC0%0/2
length $uncomp_buf and $r[0] =~ m[^application/(x-)?([+\w]+)$]
length $uncomp_buf $r[0] =~ m[^application/(x-)?([+\w]+)$]
Truth table0%0/3
A and B
A= length $uncomp_bufB= $r[0] =~ m[^application/(x-)?([+\w]+)$]
ABresult
0X0
100
111
2508 {
2509 0 my $compname = $2;
2510 0 my $next_uncomp_buf = '';
2511  
2512 # use Data::Dumper; printf STDERR "calling mime with buf=%d bytes, compname=$compname\n", length($uncomp_buf);
2513  
2514 #########
2515 ## FIXME: adding +$compname to the filename prevents reopening in mime, if needed.
2516 ## Why did I do this in the first place?
2517 # my $m2 = $self->mime(buf => $uncomp_buf, file => "$in{file}+$compname", uncomp => \$next_uncomp_buf, recursion => 1);
2518 #########
2519  
2520 0 my $m2 = $self->mime(buf => $uncomp_buf, file => $in{file}, uncomp => \$next_uncomp_buf, recursion => 1);
2521 0 my ($a,$xminus,$b) = ($m2->[0] =~ m{^(.*)/(x-)?(.*)$});
2522 0 ▶ if ($a eq 'application')
Branch: 1 branch
BranchTrueFalseTotal
if ($a eq 'application') { } 0 0 0
2523 {
2524 0 $r[0] = "application/x-$b+$compname"
2525 }
2526 else
2527 {
2528 0 $r[0] = "application/x-$a-$b+$compname"
2529 }
2530 0 $r[2] .= "\n" . $m2->[2];
2531 0 $uncomp_buf = $next_uncomp_buf;
2532 # print Dumper "new: ", \@r, $m2, $compname, length($uncomp_buf);
2533 }
2534  
2535 # use Data::Dumper;
2536 # die Dumper \@r, "--------------------";
2537  
2538 0 ▶ if ($r[0] eq 'application/unknown+zip' and $r[2] =~ m{\btext\b}i)
Branch: 1 branch
BranchTrueFalseTotal
if ($r[0] eq "application/unknown+zip" and $r[2] =~ /\btext\b/i) 0 0 0
Condition0%0/3
$r[0] eq "application/unknown+zip" and $r[2] =~ /\btext\b/i
!ll&&!rl&&r
000
MC/DC0%0/2
$r[0] eq "application/unknown+zip" and $r[2] =~ /\btext\b/i
$r[0] eq "application/unknown+zip" $r[2] =~ /\btext\b/i
Truth table0%0/3
A and B
A= $r[0] eq "application/unknown+zip"B= $r[2] =~ /\btext\b/i
ABresult
0X0
100
111
2539 {
2540 # empty.odt
2541 # ['application/unknown+zip; charset=binary','Zip archive data, at least v2.0 to extract, mime type application/vnd OpenDocument Text']
2542 # application/vnd.oasis.opendocument.text
2543 0 ▶ if ($mime2 ||= eval { open my $fd,'<',\$in{buf}; File::MimeInfo::Magic::magic($fd); })
Branch: 1 branch
BranchTrueFalseTotal
if ($mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }) 0 0 0
Condition0%0/3
$mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$mime2 ||= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
$mime2 eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
Truth table0%0/3
A ||= B
A= $mime2B= eval { do { open my $fd, "<", \$in{"buf"}; File::MimeInfo::Magic::magic($fd) } }
ABresult
1X1
011
000
2544 {
2545 0 ▶ $mime2 .= '+zip' unless $mime2 =~ m{\+zip}i;
Branch: 1 branch
BranchTrueFalseTotal
unless $mime2 =~ /\+zip/i 0 0 0
2546 0 ▶ $r[0] = $mime2 if $mime2 =~ m{^application/};
Branch: 1 branch
BranchTrueFalseTotal
if $mime2 =~ m[^application/] 0 0 0
2547 }
2548 }
2549 0 ▶ $r[0] .= '+zip' if $r[0] =~ m{^application/vnd\.oasis\.opendocument\.text$};
Branch: 1 branch
BranchTrueFalseTotal
if $r[0] =~ m[^application/vnd\.oasis\.opendocument\.text$] 0 0 0
2550  
2551 0 ▶ if ($r[0] eq 'text/plain' and $in{file} =~ m{\.(mm|b64|base64)$}i)
Branch: 1 branch
BranchTrueFalseTotal
if ($r[0] eq "text/plain" and $in{"file"} =~ /\.(mm|b64|base64)$/i) 0 0 0
Condition0%0/3
$r[0] eq "text/plain" and $in{"file"} =~ /\.(mm|b64|base64)$/i
!ll&&!rl&&r
000
MC/DC0%0/2
$r[0] eq "text/plain" and $in{"file"} =~ /\.(mm|b64|base64)$/i
$r[0] eq "text/plain" $in{"file"} =~ /\.(mm|b64|base64)$/i
Truth table0%0/3
A and B
A= $r[0] eq "text/plain"B= $in{"file"} =~ /\.(mm|b64|base64)$/i
ABresult
0X0
100
111
2552 {
2553 0 my $suf = lc $1;
2554 0 $r[0] = "text/x-suffix-$suf+plain";
2555 }
2556  
2557 0 ▶ if ($r[0] eq 'application/octet-stream' and $in{file} =~ m{\.(lzma|zx|lz)$}i)
Branch: 1 branch
BranchTrueFalseTotal
if ($r[0] eq "application/octet-stream" and $in{"file"} =~ /\.(lzma|zx|lz)$/i) 0 0 0
Condition0%0/3
$r[0] eq "application/octet-stream" and $in{"file"} =~ /\.(lzma|zx|lz)$/i
!ll&&!rl&&r
000
MC/DC0%0/2
$r[0] eq "application/octet-stream" and $in{"file"} =~ /\.(lzma|zx|lz)$/i
$r[0] eq "application/octet-stream" $in{"file"} =~ /\.(lzma|zx|lz)$/i
Truth table0%0/3
A and B
A= $r[0] eq "application/octet-stream"B= $in{"file"} =~ /\.(lzma|zx|lz)$/i
ABresult
0X0
100
111
2558 {
2559 0 my $suf = lc $1;
2560 0 $r[0] = "application/x-suffix-$suf+octet-stream";
2561 }
2562  
2563 0 ▶ if ($r[0] =~ m{^application/x-(ms-dos-|)executable$})
Branch: 1 branch
BranchTrueFalseTotal
if ($r[0] =~ m[^application/x-(ms-dos-|)executable$]) 0 0 0
2564 {
2565 0 ▶ if (-x '/usr/bin/upx')
Branch: 1 branch
BranchTrueFalseTotal
if (-x "/usr/bin/upx") 0 0 0
2566 {
2567 # upx refuses to read symlinks. Work around this.
2568 0 my $in_file = $in{file};
2569 0 ▶ $in_file = readlink($in{file}) if -l $in{file};
Branch: 1 branch
BranchTrueFalseTotal
if -l $in{"file"} 0 0 0
2570 0 ▶ $r[0] .= '+upx' unless run(['/usr/bin/upx', '-q', '-q', '-t', $in_file]);
Branch: 1 branch
BranchTrueFalseTotal
unless run(["/usr/bin/upx", "-q", "-q", "-t", $in_file]) 0 0 0
2571 }
2572 }
2573  
2574 0 ▶ ${$in{uncomp}} = $uncomp_buf if ref $in{uncomp} eq 'SCALAR';
Branch: 1 branch
BranchTrueFalseTotal
if ref $in{"uncomp"} eq "SCALAR" 0 0 0
2575 0 ▶ $r[3] = [ $mime1, $mime2 ] if $mime1 ne $r[0] or ($mime2 and $mime2 ne $mime1);
Branch: 1 branch
BranchTrueFalseTotal
if $mime1 ne $r[0] or $mime2 and $mime2 ne $mime1 0 0 0
Condition0%0/6
$mime1 ne $r[0] or $mime2 and $mime2 ne $mime1
l!l&&r!l&&!r
000
$mime2 and $mime2 ne $mime1
!ll&&!rl&&r
000
MC/DC0%0/3
$mime1 ne $r[0] or $mime2 and $mime2 ne $mime1
$mime1 ne $r[0] $mime2 $mime2 ne $mime1
Truth table0%0/4
A or B and C
A= $mime1 ne $r[0]B= $mime2C= $mime2 ne $mime1
ABCresult
1XX1
0111
00X0
0100
2576  
2577 0 return \@r;
2578 }
2579  
2580 =head1 AUTHOR
2581  
2582 Juergen Weigert, C<< <jnw at cpan.org> >>
2583  
2584 =head1 BUGS
2585  
2586 The implementation of C<mime> is an ugly hack. We suffer from the existence of
2587 multiple file magic databases, and multiple conflicting implementations. With
2588 Perl we have at least 5 modules for this; here we use two.
2589  
2590 The builtin list of MIME helpers is incomplete. Please submit your handler code.
2591  
2592 Please report any bugs or feature requests to C<bug-file-unpack at rt.cpan.org>, or through
2593 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=File-Unpack>. I will be notified, and then you'll
2594 automatically be notified of progress on your bug as I make changes.
2595  
2596  
2597 =head1 RELATED MODULES
2598  
2599 While designing File::Unpack, a range of other perl modules were examined. Many modules provide valuable service to File::Unpack and became dependencies or are recommended.
2600 Others exposed drawbacks during closer examination and may find some of their
2601 wheels re-invented here.
2602  
2603 =head2 Used Modules
2604  
2605 =over
2606  
2607 =item File::LibMagic
2608  
2609 This is the prefered mimetype engine. It disregards the suffix, recognizes more
2610 types than any of the alternatives, and uses exactly the same engine as
2611 /usr/bin/file in openSUSE systems. It also returns charset and description
2612 information. We crossreference the description with the mimetype to detect
2613 weaknesses, and consult File::MimeInfo::Magic and some own logic, for e.g.
2614 detecting LZMA compression which fails to provide any recognizable magic.
2615 Required if you use C<mime>; otherwise not a hard requirement.
2616  
2617 =item File::MimeInfo::Magic
2618  
2619 Uses both magic information and file suffixes to determine the mimetype. Its
2620 magic() function is used in a few cases, where File::LibMagic fails. E.g. as
2621 of June 2010, libmagic does not recognize 'image/x-targa'.
2622 File::MimeInfo::Magic may be slower, but it features the shared-mime-info
2623 database from freedesktop.org . Recommended if you use C<mime>.
2624  
2625 =item String::ShellQuote
2626  
2627 Used to call external MIME helpers. Required.
2628  
2629 =item BSD::Resource
2630  
2631 Used to reliably restrict the maximum file size. Recommended.
2632  
2633 =item File::Path
2634  
2635 mkpath(). Required.
2636  
2637 =item Cwd
2638  
2639 fast_abs_path(). Required.
2640  
2641 =item JSON
2642  
2643 Used for formatting the logfile. Required.
2644  
2645 =back
2646  
2647 =head2 Modules Not Used
2648  
2649 =over
2650  
2651 =item Archive::Extract
2652  
2653 Archive::Extract tries first to determine what type of archive you are passing
2654 it, by inspecting its suffix. 'Maybe this module should use something like
2655 "File::Type" to determine the type, rather than blindly trust the suffix'.
2656 [quoted from perldoc]
2657  
2658 Set $Archive::Extract::PREFER_BIN to 1, which will prefer the use of command
2659 line programs and won't consume so much memory. Default: use "Archive::Tar".
2660  
2661 =item Archive::Zip
2662  
2663 If you are just going to be extracting zips (and/or other archives) you are
2664 recommended to look at using Archive::Extract . [quoted from perldoc]
2665 It is pure perl, so it's a lot slower then your '/usr/bin/zip'.
2666  
2667 =item Archive::Tar
2668  
2669 It is pure Perl, so it's a lot slower then your "/bin/tar".
2670 It is heavy on memory, all will be read into memory. [quoted from perldoc]
2671  
2672 =item File::MMagic, File::MMagic::XS, File::Type
2673  
2674 Compared to File::LibMagic and File::MimeInfo::Magic, these three are inferior.
2675 They often say 'text/plain' or 'application/octet-stream' where the latter two report
2676 useful mimetypes.
2677  
2678 =back
2679  
2680 =head1 SUPPORT
2681  
2682 You can find documentation for this module with the perldoc command.
2683  
2684 perldoc File::Unpack
2685  
2686  
2687 You can also look for information at:
2688  
2689 =over 4
2690  
2691 =item * RT: CPAN's request tracker
2692  
2693 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Unpack>
2694  
2695 =item * AnnoCPAN: Annotated CPAN documentation
2696  
2697 L<http://annocpan.org/dist/File-Unpack>
2698  
2699 =item * CPAN Ratings
2700  
2701 L<http://cpanratings.perl.org/d/File-Unpack>
2702  
2703 =item * Search CPAN
2704  
2705 L<http://search.cpan.org/dist/File-Unpack/>
2706  
2707 =back
2708  
2709 =head1 SOURCE REPOSITORY
2710  
2711 L<http://search.cpan.org/search?query=File%3A%3AUnpack>
2712  
2713 L<http://github.com/jnweiger/perl-File-Unpack>
2714  
2715 git clone L<https://github.com/jnweiger/perl-File-Unpack.git>
2716  
2717  
2718 =head1 ACKNOWLEDGEMENTS
2719  
2720 MIME type recognition relies heavily on libmagic by Christos Zoulas. I had long
2721 hesitated implementing File::Unpack, but set to work, when I dicovered
2722 that File::LibMagic brings your library to perl. Thanks Christos. And thanks
2723 for tcsh too.
2724  
2725 =head1 LICENSE AND COPYRIGHT
2726  
2727 Copyright 2010,2011,2012,2013 Juergen Weigert.
2728  
2729 This program is free software; you can redistribute it and/or modify it
2730 under the terms of either: the GNU General Public License as published
2731 by the Free Software Foundation; or the Artistic License.
2732  
2733 See http://dev.perl.org/licenses/ for more information.
2734  
2735  
2736 =cut
2737  
2738 9 1; # End of File::Unpack
↑ Summary children_fuser.pl »