-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathUnpack.pm
2738 lines (2285 loc) · 91.3 KB
/
Unpack.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# (C) 2010-2014, [email protected], all rights reserved.
# Distribute under the same license as Perl itself.
#
#
# sudo zypper -v in perl-Compress-Raw-Zlib
# -> 'nothing to do'
# sudo zypper -v in 'perl-Compress-Raw-Zlib >= 2.027'
# -> 'perl' providing 'perl-Compress-Raw-Zlib >= 2.027' is already installed.
# sudo zypper -v in --force perl-Compress-Raw-Zlib
# -> works,
# sudo zypper -v in --from 12 perl-Compress-Raw-Zlib
# -> works, if d.l.p is repo #12.
#
# TODO:
# * evaluate File::Extract - Extract Text From Arbitrary File Types
# (HTML, PDF, Plain, RTF, Excel)
#
# * make taint checks really check things, instead of $1 if m{^(.*)$};
#
# * Implement disk space monitoring.
#
# * formats:
# - use lzmadec/xzdec as fallback to lzcat.
# - glest has bzipped tar files named glest-1.0.10-data.tar.bz2.tar;
# - Not all suffixes are appended by . e.g. openh323-v1_15_2-src-tar.bz2 is different.
# - gzip -dc can unpack old compress .Z, add its mime-type
# - java-1_5_0-sun hides zip-files in shell scripts with suffix .bin
# - cpio fails on \.delta\.rpm
# - rpm files should extract all header info in readable format.
# - do we rely on rpm2cpio to handle them all:
# rpm -qp --nodigest --nosignature --qf "%{PAYLOADCOMPRESSOR}" $f
# - m{\.(otf|ttf|ps|eps)$}i
# - application/x-frame # xorg-modular/doc/xorg-docs/specs/XPRINT/xp_libraryTOC.doc
#
# * blacklisting?
# # th_en_US.dat is an 11MB thesaurus in OOo
# 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))$}
#
# * use LWP::Simple::getstore() if $archive =~ m{^\w+://}
# * application/x-debian-package is a 'application/x-archive' -> (ar xv /dev/stdin) < $qufrom";
# * application/x-iso9660 -> "isoinfo -d -i %(src)s"
# * PDF improvement: okular says: 'this document contains embedded files.' How can we grab those?
use warnings;
use strict;
package File::Unpack;
BEGIN
{
# Requires: shared-mime-info
eval 'use File::LibMagic;'; # only needed in mime(); mime() dies, if missing
eval 'use File::MimeInfo::Magic;'; # only needed in mime(); okay, if missing.
# unless builtin!
eval 'use Compress::Raw::Lzma;'; # only needed in mime(); for finding lzma.
eval 'use Compress::Raw::Bzip2;'; # only needed in mime(); for finding second level types
eval 'use Compress::Raw::Zlib;'; # only needed in mime(); for finding second level types
eval 'use BSD::Resource;'; # setrlimit
eval 'use Filesys::Statvfs;'; # statvfs();
}
use Carp;
use File::Path;
use File::Temp (); # tempdir() in _run_mime_helper.
use File::Copy ();
use File::Compare ();
use JSON;
use String::ShellQuote; # used in _prep_configdir
use IPC::Run; # implements File::Unpack::run()
use Text::Sprintf::Named; # used to parse @builtin_mime_helpers
use Cwd 'getcwd'; # run(), moves us there and back.
use Data::Dumper;
use POSIX ();
=head1 NAME
File::Unpack - A strong bz2/gz/zip/tar/cpio/rpm/deb/cab/lzma/7z/rar/... archive unpacker, based on mime-types
=head1 VERSION
Version 0.69
=cut
# We'll have 1.x versions only after minfree() has a baseline implementation.
# Please run perl Makefile.PL after changing the version here.
our $VERSION = '0.69';
POSIX::setlocale(&POSIX::LC_ALL, 'C');
$ENV{PATH} = '/usr/bin:/bin';
$ENV{SHELL} = '/bin/sh';
delete $ENV{ENV};
# what we name the temporary directories, while helpers are working.
my $TMPDIR_TEMPL = '_fu_XXXXX';
# no longer used by the tick-tick ticker to show where we are.
# my $lsof = '/usr/bin/lsof';
# Compress::Raw::Bunzip2 needs several 100k of input data, we special case this.
# File::LibMagic wants to read ca. 70k of input data, before it says application/vnd.ms-excel
# Anything else works with 1024.
my $UNCOMP_BUFSZ = 1024;
# unpack will give up, after unpacking that many levels. It is more likely we
# got into a loop by then, than really have that many levels.
my $RECURSION_LIMIT = 200;
# Suggested place, where admins should install the helpers bundled with this module.
sub _default_helper_dir { $ENV{FILE_UNPACK_HELPER_DIR}||'/usr/share/File-Unpack/helper' }
# we use '=' in the mime_name, this expands to '/(x\-|ANY\+)?'
##
## Caution: always use (?: ... ) below for grouping, so that no extra capturing clauses are created.
my @builtin_mime_helpers = (
# mimetype pattern # suffix_re # command with redirects, as defined with IPC::Run::run
# Requires: xz bzip2 gzip unzip lzip
[ 'application=x-lzip', qr{(?:lz)}, [qw(/usr/bin/lzip -dc %(src)s)], qw(> %(destfile)s) ],
[ 'application=xz', qr{(?:xz|lz(ma)?)}, [qw(/usr/bin/lzcat)], qw(< %(src)s > %(destfile)s) ],
[ 'application=xz', qr{(?:xz|lz(ma)?)}, [qw(/usr/bin/xz -dc %(src)s)], qw(> %(destfile)s) ],
[ 'application=lzma', qr{(?:xz|lz(ma)?)}, [qw(/usr/bin/lzcat)], qw(< %(src)s > %(destfile)s) ],
[ 'application=lzma', qr{(?:xz|lz(ma)?)}, [qw(/usr/bin/xz -dc %(src)s)], qw(> %(destfile)s) ],
[ 'application=bzip2', qr{bz2}, [qw(/usr/bin/bunzip2 -dc -f %(src)s)], qw(> %(destfile)s) ],
[ 'application=gzip', qr{(?:gz|Z)}, [qw(/usr/bin/gzip -dc -f %(src)s)], qw(> %(destfile)s) ],
[ 'application=compress', qr{(?:gz|Z)}, [qw(/usr/bin/gzip -dc -f %(src)s)], qw(> %(destfile)s) ],
# Requires: sharutils
[ 'text=uuencode', qr{uu}, [qw(/usr/bin/uudecode -o %(destfile)s %(src)s)] ],
# Requires: upx
[ 'application=upx', qr{(?:upx\.exe|upx)}, [qw(/usr/bin/upx -q -q -q -d -o%(destfile)s %(lsrc)s) ] ],
# xml.summary.Mono.Security.Authenticode is twice inside of monodoc-1.0.4.tar.gz/Mono.zip/ -> use -o
[ 'application=zip', qr{(?:zip|jar|sar)}, [qw(/usr/bin/unzip -P no_pw -q -o %(src)s)] ],
# Requires: unrar
[ 'application=rar', qr{rar}, [qw(/usr/bin/unrar x -o- -p- -inul -kb -y %(src)s)] ],
# Requires: lha
[ 'application=x-lha', qr{lha}, [qw(/usr/bin/lha x -q %(src)s)] ],
# Requires: binutils
[ 'application=archive', qr{(?:a|ar|deb)}, [qw(/usr/bin/ar x %(src)s)] ],
[ 'application=x-deb', qr{deb}, [qw(/usr/bin/ar x %(src)s)] ],
[ 'application=x-debian-package', qr{deb}, [qw(/usr/bin/ar x %(src)s)] ],
# Requires: cabextract
[ 'application/vnd.ms-cab-compressed', qr{cab}, [qw(/usr/bin/cabextract -q %(src)s)] ],
# Requires: p7zip
[ 'application/x-7z-compressed', qr{7z}, [qw(/usr/bin/7z x -pPass -y %(src)s)] ],
# Requires: tar rpm cpio
[ 'application=tar', qr{(?:tar|gem)}, [\&_locate_tar, qw(-xf %(src)s)] ],
[ 'application=tar+bzip2', qr{(?:tar\.bz2|tbz)}, [\&_locate_tar, qw(-jxf %(src)s)] ],
[ 'application=tar+gzip', qr{t(?:ar\.gz|gz)}, [\&_locate_tar, qw(-zxf %(src)s)] ],
# [ 'application=tar+gzip', qr{t(?:ar\.gz|gz)}, [qw(/home/testy/src/C/slowcat)], qw(< %(src)s |), [\&_locate_tar, qw(-zxf -)] ],
[ 'application=tar+lzma', qr{tar\.(?:xz|lzma|lz)}, [qw(/usr/bin/lzcat)], qw(< %(src)s |), [\&_locate_tar, qw(-xf -)] ],
[ 'application=tar+lzma', qr{tar\.(?:xz|lzma|lz)}, [qw(/usr/bin/xz -dc -f %(src)s)], '|', [\&_locate_tar, qw(-xf -)] ],
[ 'application=rpm', qr{(?:src\.r|s|r)pm}, [qw(/usr/bin/rpm2cpio %(src)s)], '|', [\&_locate_cpio_i] ],
[ 'application=cpio', qr{cpio}, [\&_locate_cpio_i], qw(< %(src)s) ],
# Requires: poppler-tools
[ 'application=pdf', qr{pdf}, [qw(/usr/bin/pdftotext %(src)s %(destfile)s.txt)], '&', [qw(/usr/bin/pdfimages -j %(src)s pdfimages)] ],
);
## CAUTION keep _my_shell_quote in sync with all _locate_* functions.
sub _locate_tar
{
my $self = shift;
return @{$self->{_locate_tar}} if defined $self->{_locate_tar};
# cannot use tar -C %(destdir)s, we rely on being chdir'ed inside already :-)
# E: /bin/tar: /tmp/xxx/_VASn/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_: Cannot chdir: Permission denied
my @tar = (-f '/bin/tar' ? '/bin/tar' : '/usr/bin/tar' );
## osc co loves to create directories with : in them.
## Tell tar to accept such directories as directores.
push @tar, "--force-local"
unless $self->run([@tar, "--force-local", "--help"], { out_err => '/dev/null' });
push @tar, "--no-unquote"
unless $self->run([@tar, "--no-unquote", "--help"], { out_err => '/dev/null'});
$self->{_locate_tar} = \@tar;
return @tar;
}
sub _locate_cpio_i
{
my $self = shift;
return @{$self->{_locate_cpio_i}} if defined $self->{_locate_cpio_i};
my @cpio_i = ('/usr/bin/cpio', '-idm');
$cpio_i[1] .= 'u'
unless run(['/usr/bin/cpio', '-idmu', '--usage'], {out_err => '/dev/null'});
push @cpio_i, '--sparse'
unless run([@cpio_i, '--sparse', '--usage'], {out_err => '/dev/null'});
push @cpio_i, '--no-absolute-filenames'
unless run([@cpio_i, '--no-absolute-filenames', '--usage'], {out_err => '/dev/null'});
push @cpio_i, '--force-local'
unless run([@cpio_i, '--force-local', '--usage'], {out_err => '/dev/null'});
@{$self->{_locate_cpio_i}} = \@cpio_i;
return @cpio_i;
}
=head1 SYNOPSIS
This perl module comes with an executable script:
/usr/bin/file_unpack -h
/usr/bin/file_unpack [-1] [-m] ARCHIVE_FILE ...
File::Unpack is an unpacker for archives and files
(bz2/gz/zip/tar/cpio/iso/rpm/deb/cab/lzma/7z/rar ... pdf/odf) based on
MIME types. We call it strong, because it is not fooled by file suffixes, or
multiply wrapped packages. It recursively descends into each archive found
until it finally exposes all unpackable payload contents.
A logfile can be written, precisely describing MIME types and unpack actions.
use File::Unpack;
my $log;
my $u = File::Unpack->new(logfile => \$log);
my $m = $u->mime('/etc/init.d/rc');
print "$m->[0]; charset=$m->[1]\n";
# text/x-shellscript; charset=us-ascii
map { print "$_->{name}\n" } @{$u->mime_helper()};
# application/%rpm
# application/%tar+gzip
# application/%tar+bzip2
# ...
$u->unpack("inputfile.tar.bz2");
while ($log =~ m{^\s*"(.*?)":}g) # it's JSON.
{
print "$1\n"; # report all files unpacked
}
...
Most of the known archive file formats are supported. Shell-script-style
plugins can be added to support additinal formats.
Helper shell-scripts can be added to support additional mime-types. Example:
F<< $ echo "ar x $1" > /usr/share/File-Unpack/helper/application=x-debian-package >>
F<< $ chmod a+x /usr/share/File-Unpack/helper/application=x-debian-package >>
This example creates a trivial external equivalent of the builtin MIME helper for *.deb packages.
For details see the documentation of the C<unpack()> method.
C<unpack> examines the contents of an archive file or directory using an extensive
mime-type analysis. The contents is unpacked recursively to the given destination
directory; a listing of the unpacked files is reported through the built in
logging facility during unpacking. Most common archive file formats are handled
directly; more can easily be added as mime-type helper plugins.
=head1 SUBROUTINES/METHODS
=head2 new
my $u = new(destdir => '.', logfile => \*STDOUT, maxfilesize => '2G', verbose => 1,
world_readable => 0, one_shot => 0, no_op => 0, archive_name_as_dir => 0,
follow_file_symlinks => 0,
log_params => {}, log_type => 'JSON');
Creates an unpacker instance. The parameter C<destdir> must be a writable location; all output
files and directories are placed inside this destdir. Subdirectories will be
created in an attempt to reflect the structure of the input. Destdir defaults
to the current directory; relative paths are resolved immediatly, so that
chdir() after calling new is harmless.
The parameter C<logfile> can be a reference to a scalar, a filename, or a filedescriptor.
The logfile starts with a JSON formatted prolog, where all lines start
with printable characters.
For each file unpacked, a one line record is appended, starting with a single
whitespace ' ', and terminated by "\n". The format is a JSON-encoded C<< "key":
{value},\n >> pair, where key is the filename, and value is a hash including 'mime',
'size', and other information.
The logfile is terminated by an epilog, where each line starts with a printable character.
As part of the epilog, a dummy file named "\" with an empty hash is added to the list.
It should be ignored while parsing.
Per default, the logfile is sent to STDOUT.
The parameter C<maxfilesize> is a safeguard against compressed sparse files and
test-files for archivers. Such files could easily fill up any available disk
space when unpacked. Files hitting this limit will be silently truncated.
Check the logfile records or epilog to see if this has happened. BSD::Resource
is used manipulate RLIMIT_FSIZE.
The parameter C<one_shot> can optionally be set to non-zero, to limit unpacking
to one step of unpacking. Unpacking of well known compressed archives like
e.g. '.tar.bz2' is considered one step only. If uncompressing an archive is
considered an extra step before unpacking the archive depends on the configured
mime helpers.
The parameter C<no_op> causes unpack() to only print one shell command to
STDOUT and exit. This implies one_shot=1.
The parameter C<world_readable> causes unpack() change all directories to 0755,
and all files to 444. Otherwise 0700 and 0400 (user readable) is asserted.
The parameter C<follow_file_symlinks> causes some or all symlinks to files
to be included.
A value of 1 follows symlinks that exist in the input directory and point to a file.
This has no effect if the input is an archive file. A value of 2 also follows symlinks
that were extracted from archives. CAUTION: This may cause unpack() to visit
files or archives elsewhere in the local filesystem.
Directory symlinks are always excluded.
The parameter C<archive_name_as_dir> causes the unpacker to store all unpacked
files inside a directory with the same name as their archive.
The default depends on how many files are unpacked from the archive: If exactly one
file (or one toplevel directory) is unpacked, then no extra directory is used.
E.g. F<foo.tar.gz> would unpack to F<foo.tar> or
F<foo-1.0.zip> would unpack to F<foo-1.0/*> and no files outside this directory.
If multiple files (or directories) are unpacked, and the suffix of the archive can
be removed with the C<suffix_re> of its C<mime_helper>, then the
shortened name is used as a directory. E.g. F<foo.tar> would unpack to
F<foo/*>. Otherwise F<._> is appended to the archive name. E.g. F<foo.tar> would unpack to
F<foo.tar._/*>.
In any case, the suffix F<._> or F<._B<NNN>> is used to avoid conflicts with
already existing names where B<NNN> is a numeric value.
=head2 exclude
exclude(add => ['.svn', '*.orig' ], del => '.svn', force => 1, follow_file_symlinks => 0)
Defines the exclude-list for unpacking. This list is advisory for the MIME helpers.
The exclude-list items are shell glob patterns, where '*' or '?' never match '/'.
You can use force to have any of these removed after unpacking.
Use (vcs => 1) to exclude a long list of known version control system directories, use (vcs => 0) to remove them.
The default is C<< exclude(empty => 1) >>, which is the same as C<< exclude(empty_file => 1, empty_dir => 1) >> --
having the obvious meaning.
(re => 1) returns the active exclude-list as a regexp pattern.
Otherwise C<exclude> always returns the list as an array ref.
Some symbolic links are included if {follow_file_symlinks} is nonzero. For details see C<<new()>>.
If exclude patterns were effective, or if symlinks, fifos, sockets, ... were encountered during unpack(),
the logfile contains an additional 'skipped' keyword with statistics.
=cut
sub _glob_list_re
{
my @re;
return unless @_;
for my $text (@_)
{
# Taken from pdb2perl:glob2re() and adapted, to not match slashes in wildcards.
# This should be kept compatible with tar --exclude .
$text =~ s{([\.\(\)\[\]\{\}])}{\\$1}g; ## protect magic re characters.
$text =~ s{\*}{[^/]*}g; ## * -> [^/]*
$text =~ s{\?}{[^/]}g; ## ? -> [^/]
push @re, $text;
}
return '(/|^)(' . join('|', @re) . ')(/|$)';
}
sub _not_excluded
{
my $self = shift;
my ($dir, $file) = @_;
return 1 unless my $re = $self->{exclude}{re};
$dir ||= '';
$dir .= '/' unless $dir =~ m{/$};
$file = $dir . $file;
return 0 if $file =~ m{$re};
return 1;
}
sub exclude
{
my $self = shift;
my %opt = $#_ ? @_ : (add => $_[0]);
# ADD to this list from: https://build.opensuse.org/project/show?project=devel%3Atools%3Ascm
my @vcs = qw(SCCS RCS CVS .svn .git .hg .osc);
$opt{add} = [ $opt{add} ] unless ref $opt{add};
$opt{del} = [ $opt{del} ] unless ref $opt{del};
push @{$opt{add}}, @vcs if defined $opt{vcs} and $opt{vcs};
push @{$opt{del}}, @vcs if defined $opt{vcs} and !$opt{vcs};
for my $a (@{$opt{add}})
{
$self->{exclude}{list}{$a}++ if defined $a;
}
for my $a (@{$opt{del}})
{
delete $self->{exclude}{list}{$a} if defined $a;
}
my @list = sort keys %{$self->{exclude}{list}};
$self->{exclude}{re} = _glob_list_re(@list);
$opt{empty_dir} = $opt{empty_file} = $opt{empty} if defined $opt{empty};
for my $o (qw(empty_file empty_dir force))
{
$self->{exclude}{$o} = $opt{$o} if defined $opt{$o};
}
$self->{follow_file_symlinks} = $opt{follow_file_symlinks}
if defined $opt{follow_file_symlinks};
return $opt{re} ? $self->{exclude}{re} : \@list;
}
=begin private
=item log, logf, loggable_pathname
The C<log> method is used by C<unpack> to send text to the logfile.
The C<logf> method takes a filename and a hash, and logs a JSON formatted line.
The trailing newline character of a line is delayed; it is printed by the next call to
C<log> or C<logf>. In case of C<logf>, a comma is emitted before the newline
from the second call onward.
The C<loggable_pathname> shortens a path to be relative to either
$self->{destdir} or $self->{input} unless $self->{log_fullpath} is true.
If a hash is provided as a second parameter and the path was found to be relative
to $self->{input}, then an entry { 'srcdir' => 'input' } is added to this hash.
=end private
=cut
sub log
{
my ($self, $text) = @_;
if (my $fp = $self->{lfp})
{
my $oldpos = eval { $fp->tell; }; # old perl at SLES11 has no IO::Handle::tell()
$fp->write($text) or die "log($self->{logfile}): write failed: $!\n";
my $r = eval { $fp->tell - $oldpos; };
## We do not expect any multibyte utf8 issues in here. It is plain 7-bit JSON.
## E.g. /dev/null is not seekable. Be forgiving.
die "$oldpos,$r=log($self->{logfile}): write failed: $text\n" if $r and $r != length($text);
$self->{lfp_printed}++;
}
}
sub loggable_pathname
{
my ($self, $file, $hash) = @_;
unless ($self->{log_fullpath})
{
# very frequently, files are inside the destdir
unless ($file =~ s{^\Q$self->{destdir}\E/}{})
{
# less frequently, archives are logged inside the input dir
if ($self->{input})
{
if ($file =~ s{^\Q$self->{input}\E/}{\./input/./})
{
$hash->{srcdir} = 'input' if ref $hash eq 'HASH';
}
}
}
}
return $file;
}
sub logf
{
my ($self,$file,$hash,$suff) = @_;
$suff = "" unless defined $suff;
my $json = $self->{json} ||= JSON->new()->ascii(1);
$file = $self->loggable_pathname($file, $hash);
if (my $fp = $self->{lfp})
{
if ($self->{log_type} eq 'plain')
{
my $str = $file . ' (';
$str .= $hash->{mime} if defined $hash->{mime};
$str .= ')';
$str = "# $str -> " . $hash->{unpacked} if $hash->{unpacked};
$str .= "\n";
$self->log($str);
}
else
{
$self->log(qq[{ "oops": "logf used before prolog??",\n"unpacked_files":{\n])
unless $self->{lfp_printed}; # sysseek($fp, 0, 1); # }} there is no systell() ...
my $str = $json->encode({$file => $hash});
$str =~ s{^\{}{}s;
$str =~ s{\}$}{}s;
my $pre = " ";
$pre = ",\n " if $self->{logf_continuation}++;
die "logf failed to encode newline char: $str\n" if $str =~ m{(?:\n|\r)};
$self->log("$pre$str$suff");
}
}
}
$SIG{'XFSZ'} = sub
{
print STDERR "soft RLIMIT_FSIZE exceeded. SIGXFSZ recieved. Exiting\n";
exit;
};
# if this returns 0, we test again and call it again, possibly.
# if this returns nonzero, we just continue.
sub _default_fs_warn
{
carp "Filesystem (@_) is almost full.\n $0 paused for 30 sec.\n";
sleep(30);
return 0;
}
## returns 1, if enough space free.
## returns 0, if warn-method was called, and returned nonzero
## returns -1, if no warn method
## or does not return at all, and rechecks the status
## with at least on second delay, if warn-method returns 0.
sub _fs_check
{
my ($self, $needed_b, $needed_i, $needed_p) = @_;
$needed_b = '1M' unless defined $needed_b; # bytes
$needed_i = 100 unless defined $needed_i; # inodes
$needed_p = 1.0 unless defined $needed_p; # percent
$needed_b = _bytes_unit($needed_b);
my $DIR;
open $DIR, "<", $self->{destdir} or
opendir $DIR, $self->{destdir} or return;
## fileno() does not work with opendir() handles.
my $fd = fileno($DIR); return unless defined $fd;
for (;;)
{
my $st = eval { [ fstatvfs($fd) ] };
my $total_b = $st->[1] * $st->[2]; # f_frsize * f_blocks
my $free_b = $st->[0] * $st->[4]; # f_bsize * f_bavail
my $free_i = $st->[7]; # f_favail
my $perc = 100.0 * ($total_b - $free_b) / ($total_b||1);
return 1 if $free_b >= $needed_b &&
$free_i >= $needed_i &&
(100-$perc > $needed_p);
return -1 unless $self->{fs_warn};
my $w = $self->{fs_warn}->($self->{destdir}, $perc, $free_b, $free_i);
return 0 if $w;
sleep 1;
}
}
sub new
{
my $self = shift;
my $class = ref($self) || $self;
my %obj = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
$obj{verbose} = 1 unless defined $obj{verbose};
$obj{destdir} ||= '.';
$obj{logfile} ||= \*STDOUT;
$obj{log_type} ||= 'json'; # or 'plain'
$obj{log_type} = lc $obj{log_type};
$obj{maxfilesize} = $ENV{'FILE_UNPACK_MAXFILESIZE'}||'2.5G' unless defined $obj{maxfilesize};
$obj{maxfilesize} = _bytes_unit($obj{maxfilesize});
$ENV{'FILE_UNPACK_MAXFILESIZE'} = $obj{maxfilesize}; # so that children see the same.
mkpath($obj{destdir}); # abs_path is unreliable if destdir does not exist
$obj{destdir} = Cwd::fast_abs_path($obj{destdir});
$obj{destdir} =~ s{(.)/+$}{$1}; # assert no trailing '/'.
# used in unpack() to jail mime_helpers deep inside destdir:
$obj{dot_dot_safeguard} = 20 unless defined $obj{dot_dot_safeguard};
$obj{jail_chmod0} ||= 0;
# used in unpack, print only:
$obj{no_op} ||= 0;
# used in unpack, blocks recursion after archive unpacking:
$obj{one_shot} ||= $obj{no_op};
# With $self->{within_archives} we know the difference between symlinks found in
# the given repository or symlinks that were unpacked from an archive.
# Those from an archive are followed only with follow_file_symlinks == 2.
$obj{follow_file_symlinks} ||= 0;
warn "WARNING: We are running as root: Malicious archives may clobber your filesystem.\n" if $obj{verbose} and !$>;
if (ref $obj{logfile} eq 'SCALAR' or !(ref $obj{logfile}))
{
open $obj{lfp}, ">", $obj{logfile} or croak "open logfile $obj{logfile} failed: $!\n";
}
else
{
$obj{lfp} = $obj{logfile};
}
# make $obj{lfp} unbuffered, so that other processes can read line by line...
$obj{lfp}->autoflush(1);
$obj{lfp_printed} = 0;
$obj{readable_file_modes} = [ 0400 ];
$obj{readable_dir_modes} = [ 0700, 0500 ];
if ($obj{world_readable})
{
unshift @{$obj{readable_file_modes}}, 0444;
unshift @{$obj{readable_dir_modes}}, 0755;
}
if ($obj{maxfilesize})
{
eval
{
no strict;
# helper/application=x-shellscript calls File::Unpack->new(), with defaults...
my @have = BSD::Resource::getrlimit(RLIMIT_FSIZE);
if ($have[0] == RLIM_INFINITY or $have[0] > $obj{maxfilesize})
{
# if RLIM_INFINITY is seen as an attempt to increase limits, we would fail. Ignore this.
BSD::Resource::setrlimit(RLIMIT_FSIZE, $obj{maxfilesize}, RLIM_INFINITY) or
BSD::Resource::setrlimit(RLIMIT_FSIZE, $obj{maxfilesize}, $obj{maxfilesize}) or
warn "RLIMIT_FSIZE($obj{maxfilesize}), limit=($have[0],$have[1]) failed\n";
}
};
if ($@)
{
carp "WARNING maxfilesize=$obj{maxfilesize} ignored:\n $@ $!\n Maybe package perl-BSD-Resource is not installed??\n\n";
}
}
$obj{minfree}{factor} = 10 unless defined $obj{minfree}{factor};
$obj{minfree}{bytes} = '1M' unless defined $obj{minfree}{bytes};
$obj{minfree}{percent} = '1%' unless defined $obj{minfree}{percent};
minfree(\%obj, warning => $obj{fs_warn}||\&_default_fs_warn);
$obj{exclude}{empty_dir} = 1 unless defined $obj{exclude}{empty_dir};
$obj{exclude}{empty_file} = 1 unless defined $obj{exclude}{empty_file};
$self = bless \%obj, $class;
for my $h (@builtin_mime_helpers)
{
$self->mime_helper(@$h);
}
$obj{helper_dir} = _default_helper_dir unless exists $obj{helper_dir};
$self->mime_helper_dir($obj{helper_dir}) if defined $obj{helper_dir} and -d $obj{helper_dir};
unless ($ENV{PERL5LIB})
{
# in case we are using non-standard perl lib dirs, put them into the environment,
# so that any helper scripts see them too. They might need them, if written in perl.
use Config;
my $pat = qr{^(?:\Q$Config{vendorlib}\E|\Q$Config{sitelib}\E|\Q$Config{privlib}\E)\b};
my @add; # all dirs, that come before the standard dirs.
for my $i (@INC)
{
last if $i =~ m{$pat};
push @add, $i;
}
$ENV{PERL5LIB} = join ':', @add if @add;
}
return $self;
}
sub DESTROY
{
my $self = shift;
# when unpack() processes an input, it should delete {lfp} afterwards.
# Added some 'or' cases, as $self->{input} might be empty, although we had processed an input.
#
# We rather catch an error, than produce incomplete output.
# 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
#
if (($self->{input} or
($self->{lfp_printed}||0) or
($self->{recursion_level}||0)) and $self->{lfp})
{
if ($self->{log_type} eq 'plain')
{
# pass
}
else
{
$self->log(sprintf(qq[{"pid":"%d", "unpacked":{], $$)) unless $self->{lfp_printed};
}
my $r = $self->{recursion_level}||0;
# this should never happen.
# always delete $self->{lfp} manually, when done.
## {{
my $msg = "unexpected destructor seen";
$msg = join('; ', @{$self->{error}}) if $self->{error};
if ($self->{log_type} eq 'plain')
{
$self->log("# error: (l=$self->{lfp_printed},r=$r): $msg\n");
}
else
{
$self->log(qq[\n}, "error":"(l=$self->{lfp_printed},r=$r): $msg"}\n]);
}
close $self->{lfp} if $self->{lfp} ne $self->{logfile};
delete $self->{lfp};
delete $self->{lfp_printed};
}
if ($self->{configdir})
{
rmtree($self->{configdir});
delete $self->{configdir};
}
}
=head2 unpack
$u->unpack($archive, [$destdir])
Determines the contents of an archive and recursivly extracts its files.
An archive may be the pathname of a file or directory. The extracted contents will be
stored in F<destdir/$subdir/$dest_name>, where dest_name is the filename
component of archive without any leading pathname components, and possibly
stripped or added suffix. (Subdir defaults to ''.) If archive is a directory,
then dest_name will also be a directory. If archive is a file, the type of
dest_name depends on the type of packing: If the archive expands to multiple
files, dest_name will be a directory, otherwise it will be a file. If a file of
the same name already exists in the destination subdir, an additional subdir
component is created to avoid any conflicts.
For each extracted file, a record is written to the logfile.
When unpacking is finished, the logfile contains one valid JSON structure.
Unpack achieves this by writing suitable prolog and epilog lines to the logfile.
The logfile can also be parsed line by line. All file records is one line and start
with a ' ' whitespace, and end in a ',' comma. Everything else is prolog or epilog.
The actual unpacking is dispatched to MIME type specific helpers,
selected using C<mime>. A MIME helper can either be built-in code, or an
external shell-script found in a directory registered with
C<mime_helper_dir>. The standard place for external helpers is
F</usr/share/File-Unpack/helper>; it can be changed by the environment variable
F<FILE_UNPACK_HELPER_DIR> or the C<new> parameter C<helper_dir>.
The naming of helper scripts is described under C<mime_helper()>.
A MIME helper must have executable permission and is called with 6 parameters:
source_path, destfile, destination_path, mimetype, description, and config_dir.
Note, that destination_path is a freshly created empty working directory, even
if the unpacker is expected to unpack only a single file. The unpacker is
called after chdir into destination_path, so you usually do not need to
evaluate the third parameter.
The directory C<config_dir> contains unpack configuration in .sh, .js and possibly
other formats. A MIME helper may use this information, but need not.
All data passed into C<new> is reflected there, as well as the active exclude-list.
Using the config information can help a MIME helper to skip unwanted
work or otherwise optimize unpacking.
C<unpack> monitors the available filesystem space in destdir. If there is less space
than configured with C<minfree>, a warning can be printed and unpacking is
optionally paused. It also monitors the MIME helpers progress reading the archive
at source_path and reports percentages to STDERR (if verbose is 1 or more).
After the MIME helper is finished, C<unpack> examines the files it created.
If it created no files in F<destdir>, an error is reported, and the
F<source_path> may be passed to other unpackers, or finally be added to the log as is.
If the MIME helper wants to express that F<source_path> is already unpacked as far as possible
and should be added to the log without any error messages, it creates a symbolic link
F<destdir> pointing to F<source_path>.
The system considers replacing the
directory with a file, if all of the following conditions are met:
=over
=item *
There is exactly one file in the directory.
=item *
The file name is identical with the directory name,
except for one changed or removed
suffix-word. (*.tar.gz -> *.tar; or *.tgz -> *.tar)
=item *
The file must not already exist in the parent directory.
=back
C<unpack> prepares 20 empty subdirectory levels and chdirs the unpacker
in there. This number can be adjusted using C<< new(dot_dot_safeguard => 20) >>.
A directory 20 levels up from the current working dir has mode 0 while
the MIME helper runs. C<unpack> can optionally chmod(0) the parent of the subdirectory
after it chdirs the unpacker inside. Use C<< new(jail_chmod0 => 1) >> for this, default
is off. If enabled, a MIME helper trying to place files outside of the specified
destination_path may receive 'permission denied' conditions.
These are special hacks to keep badly constructed
tar-balls, cpio-, or zip-archives at bay.
Please note, that this can help against archives containing relative paths
(like starting with '../../../foo'), but will be ineffective with absolute paths
(starting with '/foo').
It is the responsibility of MIME helpers to not create absolute paths;
C<unpack> should not be run as the root user, to minimize the risk of
compromising the root filesystem.
A missing MIME helper is skipped, and subsequent helpers may take effect. A
MIME helper is expected to return an exit status of 0 upon success. If it runs
into a problem, it should print lines
starting with the affected filenames to stderr.
Such errors are recorded in the log with the unpacked archive, and as far as
files were created, also with these files.
Symbolic links are ignored while unpacking.
Currently you can call C<unpack> only once.
=cut
sub unpack
{
## as long as $archive is outside $self->{destdir}, we construct our destdir by
## replacing $self->{input_dir} with $self->{destdir}.
## This $self->{input_dir} must be created and kept constant at the earliest
## possible call.
## When the $archive is inside $self->{destdir}, we do not use $self->{input_dir},
## we then use the current $in_dir as destdir.
##
## Whenever an archive path outside $self->{destdir} is found,
## it is first passed through Cwd::fast_abs_path before any other processing occurs.
##
my ($self, $archive, $destdir) = @_;
$destdir = $self->{destdir} unless defined $destdir;
$destdir = $1 if $destdir =~ m{^(.*)$}s; # brute force untaint
if (($self->{recursion_level}||0) > $RECURSION_LIMIT)
{
push @{$self->{error}}, "unpack('$archive','$destdir'): recursion limit $RECURSION_LIMIT";
## this is only an emergency stop.
return 1;
}
if ($archive !~ m{^/} or $archive !~ m{^\Q$self->{destdir}\E/})
{
# Cwd::fast_abs_path($archive) not only makes nice absolute paths, but it also expands
# file symlinks. This is a bad idea for two reasons:
# * when we allow {follow_file_symlinks} the link destination gets into the log file,
# rather than the (expected) link itself.
# * Also, this could easily trigger "path escaped" below .
######
if ($self->{follow_file_symlinks} && $archive =~ m{^(.*)/(.*?)$})
{
# we solve both issues by doing this:
# chop off the filename; expand the path; re-add the filename.
my ($a_path, $a_file) = ($1,$2);
$a_path = Cwd::fast_abs_path($a_path) if -e $a_path;
$archive = $a_path . '/' . $a_file;
}
else
{
$archive = Cwd::fast_abs_path($archive) if -e $archive;
}
}
my $start_time = time;
if ($self->{recursion_level}++ == 0)
{
print STDERR "unpack: starting...\n" if $self->{verbose} > 1;
## State that needs to be reset when (re)starting goes in here.
#
# CAUTION: recursion_level decrements again, as we return from unpack()
# how do we assert, that this code only runs at the start,
# and not once again at the end?
$self->{inside_archives} = 0;
$self->{json} ||= JSON->new()->ascii(1); # used often, create it unconditionally here and once.
$self->{iput} = $archive;
$self->{progress_tstamp} = $start_time;
($self->{input_dir}, $self->{input_file}) = ($1, $2) if $archive =~ m{^(.*)/([^/]*)$};
if ($self->{log_type} eq 'plain')
{
# pass
}
else
{
# logfile prolog
my $prolog = {destdir=>$self->{destdir}, fu=>$VERSION, pid=>$$, input => $archive, start => scalar localtime};
$prolog->{params} = $self->{log_params} if keys %{$self->{log_params}};
my $s = $self->{json}->encode($prolog);
$s =~ s@}$@, "unpacked":{\n@;
$self->log($s);
}
}
unless (-e $archive)
{
# contstucted $archive wrongly
# e.g. we have 'pax/data/a/' instead of 'pax/data/_fu_3CEuA/a/'
push @{$self->{error}}, "unpack('$archive'): not much file or directory; ";
return 1;
}
unless ($self->{input_dir})
{
push @{$self->{error}}, "unpack('$archive'); internal error: no {input_dir}";
return 1;
}
my ($in_dir, $in_file) = ('/', '');
($in_dir, $in_file) = ($1, $2) if $archive =~ m{^(.*/)([^/]*)$};
my $inside_destdir = 1;
my $subdir = $in_dir; # remainder after stripping $orig_archive_prefix / $self->{destdir}
unless ($subdir =~ s{^\Q$self->{destdir}\E/+}{})
{
$inside_destdir = 0;
die "$archive path escaped. Neither inside original $self->{input_dir} nor inside destdir='$self->{destdir}'\n"
unless $subdir =~ s{^\Q$self->{input_dir}\E/+}{};
}
print STDERR "unpack: r=$self->{recursion_level} in_dir=$in_dir, in_file=$in_file, destdir=$destdir\n" if $self->{verbose} > 1;
my @missing_unpacker;
if ($self->{progress_tstamp} + 10 < $start_time)
{
printf "T: %d files ...\n", $self->{file_count}||0;
$self->{progress_tstamp} = $start_time;
}
if (-d $archive)
{
$self->_chmod_add($archive, @{$self->{readable_dir_modes}});
if (opendir DIR, $archive)
{
my @f = sort grep { $_ ne '.' && $_ ne '..' } readdir DIR;
closedir DIR;
print STDERR "dir = @f\n" if $self->{verbose} > 1;
for my $f (@f)
{
if ($self->{exclude}{re} && $f =~ m{$self->{exclude}{re}})
{
$self->{skipped}{exclude}++;
}
my $new_in = "$archive/$f";
## if $archive is $inside_destdir, then $archive is normally indentical to $destdir.
## ($inside_destdir means inside $self->{destdir}, actually)
my $new_destdir = $destdir; $new_destdir .= "/$f" if -d $new_in;
my $symlink_to_skip = -l $new_in;
my $dangeous_symlink = $self->{inside_archives} ? 1 : 0;
if ($symlink_to_skip and ($self->{follow_file_symlinks} > $dangeous_symlink))
{
$symlink_to_skip = 0 if -f $new_in;
# directory and dead symlinks we always skip.
# directory symlinks could cause us to recurse out of the current tree.
}
if ($symlink_to_skip)
{
# test -l first, as -f could be also true here...
print STDERR "symlink $new_in: skipped\n" if $self->{verbose} > 1;
$self->{skipped}{symlink}++;
}
elsif (-f $new_in or -d _)
{
$self->unpack($new_in, $new_destdir);
}
else
{
print STDERR "special file $new_in: skipped\n" if $self->{verbose} > 1;
$self->{skipped}{device_node}++;
}
$self->{progress_tstamp} = time;
}
}
else
{
push @{$self->{error}}, "unpack dir ($archive) failed: $!";
}
}