File: unp

package info (click to toggle)
unp 2.0~pre4
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 84 kB
  • ctags: 23
  • sloc: perl: 486; makefile: 58; sh: 7
file content (607 lines) | stat: -rwxr-xr-x 15,798 bytes parent folder | download
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
#! /usr/bin/perl
#
# "unp" runs the correct unpack program depending on the file extension
# of the given parameter.
# 
# Author: Eduard Bloch <blade@debian.org>, 2010
#
# UI modelled after unp versions 1.x by Eduard Bloch (2000-2009) and original
# unp by Andre Karwath (1997).
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# -----------------------------------------------------------------------
# If you make changes to this script, please feel free to forward the new 
# version to the author.
# -----------------------------------------------------------------------

require 5.002;

use Getopt::Long qw(:config no_ignore_case bundling pass_through);
use File::Basename;
use Cwd;

use strict;
#use diagnostics;

my @ifiles;
my @xargs;
my @tools;
my $retcode=0;

my $opt_quiet;
my $opt_debug;
my $opt_help;
my $opt_force;
my $opt_formats;
my $opt_umode;
my $opt_umode_smart;
my $opt_verbose;

BEGIN {
  eval 'use Locale::gettext';
  if ($@) {
    eval q{ sub gettext { return shift; } };
  } else {
    textdomain('unp');
  }
}

my $catmode = $0=~/(^|\/ucat)$/;

&init_formats;
&parse_cli;
&process_files if !$catmode;
&cat_files if $catmode;
print STDERR "WARNING: There were errors while processing files!\n" if $retcode;
print "retcode: $retcode\n" if $opt_debug;
# return something meaning, i.e. it may be single unpacker's only return code
exit $retcode ? ( $retcode < 256 ? $retcode : 1 ) : 0;

sub show_help 
{
printf(gettext("
USAGE:
   %s [ options ] file [ files... ]
   file: compressed file(s) to expand/extract

   Use -- [ ARGUMENTS ] to pass arguments to external programs, eg. some tar options:
   unp fastgl.tgz xmnt.tgz -- -C /tmp

   Options:
   -f Continue even if program availability checks fail or directory collision occurs
   -u Special helper mode.
      For most archive types:
      - create directory <filename without suffix>/
      - extract contents there
      For Debian/Ubuntu packages:
      - extract data.tar.gz after each operation in local directory
      - extract control.tar.gz into control/<package_version_arch>/
   -U Smart mode, acts like -u (see above) if archive contains multiple
      elements but if there is only one file/directory element then it's stored 
      in the current directory.
   -s Show the list of supported formats
   -v More verbosity
   -h Show this help
"), $0) if !$catmode;
printf(gettext("
USAGE:
   %s [ options ] file [ files... ]
   Uncompress multiple files to STDOUT

   Options:
   -s  Show the list of supported formats
   -h  Show this help
   -v  More verbosity, to STDERR
"), $0) if $catmode;
exit 1;
}

sub init_formats
{
   my $sh="/bin/sh";

# Database format: providing packages (human readable), filename suffix,
# libmagic (file tool) pattern, process flags (bitfield), array of command sets
# (=arrays of command and arguments) where (optionally) the first argument may
# be interpreted as prerequisite list if it's an array itself. Flag values:
# 2:  retry other tools calls if the first candidate failed
# 4:  pass source and extra args in different order (src args...), good for
#     shell commands using $0 and $@
# 8:  stream filters, contents may be extracted if tar format is detected. Only
#     simple syntax allowed.
# 16: append suggested target name to calling arguments

   @tools = (
      [ "tar", "tar", "tar.archive", 0,
      [ "tar", "-x", "-v", "-f"]
      ],

      # shortcuts, no extra scripting needed
      [ "tar and gzip", "tgz|tar.gz", undef, 0,
      [[ "gzip" ], "tar",  "-z", "-x", "-v", "-f"]
      ],

      [ "tar with bzip2", "tar.bz2|tbz2", undef, 0,
      
      [ [ "bzip2" ], "tar", "--bzip2", "-x", "-v", "-f"]
      ],

      [ "tar and xz-utils", "tar.xz|txz", undef, 0,
      
      [ [ "xz" ], "tar", "--xz", "-x", "-v", "-f"]
      ],

      [ "tar and lzip", "tar.lzip", undef, 0,
      
      [[ "lzip" ], "tar", "--lzip", "-x", "-v", "-f"]
      ],

      [ "tar and lzop", "tar.lzop|tzo", undef, 0,
      
      [[ "lzop" ], "tar", "--lzop", "-x", "-v", "-f"]
      ],

      [ "tar and compress", "tar.z", undef, 0,
      
      [ [ "compress" ], "tar", "-Z", "-x", "-v", "-f"]
      ],

      # XXX: that's ok for now but if support for other unpackers is needed
      # (like multithreaded implementations) than ucat code needs to be
      # extended to check them
      [ "gzip", "gz", "gzip.compressed.data", 8,
      [ "gzip", "-cd" ]
      ],

      [ "bzip2", "bz2", "bzip2.compressed", 8,
      [ "bzip2", "-cd" ]
      ],

      [ "lzop", "lzo", "lzop.compressed", 8,
      [ "lzop", "-cd" ]
      ],

      [ "xz-utils", "xz", "xz.compressed", 8,
      [ "xzcat" ]
      ],

      [ "xz-utils", "lzma", "lzma.compressed", 8,
      [ "lzcat" ]
      ],

      [ gettext("cpio or afio"), "cpio|afio",  "cpio", 4,
      [ "afio", "-Z", "-v", "-i" ],
      [ ["cpio"], $sh, "-c", 'cpio -i -d	--verbose "$@" < "$0"' ]
      ],

      [ gettext("rpm2cpio and cpio"), "rpm", 'PPM\ v', 4,
      [ ["rpm2cpio", "cpio"], 'rpm2cpio < "$0" | cpio -i -d	--verbose "$@"' ]
      ],

      [ gettext("formail and mpack"), "mbox", "(mail.text)|news", 4,
      [ ["formail","munpack"], $sh, "-c", 'formail -s munpack "$@" < "$0"' ]
      ],

      [ gettext("libchm-bin or archmage"), "chm", "Windows HtmlHelp Data", 16,
      [ 'extract_chmLib' ],
      [ 'archmage']
      ],

      [ gettext("rar or unrar or unrar-free"), "rar",  "RAR.*archive", 0,
      [ "rar", "x" ],
      [ "unrar", "x" ]
      ]
      ,
      [ "binutils", "ar|deb", "(Debian binary package|\ ar.*archive)", 0,
      [ "ar", "-x", "-v" ]
      ]
      ,
      [ "unzip", "zip|cbz|cbr|jar|war|ear|xpi|adf", "Zip.*archive", 0,
      [ "unzip" ]
      ]
      ,
      [ "lha", "lha|lzh", "LHa.*archive", 0,
      [ "lha", "x" ]
      ]
      ,
      [ "arj", "arj", "ARJ.*archive", 0,
      [ "arj", "x" ],
      [ "unarj", "x" ],
      ]
      ,
      [ "ppmd", "pmd", "PPmd.*archive", 0,
      [ "PPMd", "x" ]
      ]
      ,
      [ "zoo", "zoo", "Zoo.*archive", 0,
      [ "unzoo", "-x" ]
      ]
      ,
      [ "sharutils", "shar", "shell.*archive", 0,
      [ "unshar" ]
      ]
      ,
      [ "sharutils", "uu", "uuencoded", 0,
      [ "undecode" ]
      ]
      ,
      [ "tnef", "dat", "Transport Neutral Encapsulation Format", 0,
      [ "tnef", "-v" ]
      ]
      ,
      [ gettext("p7zip or p7zip-full"), "7z", "7-zip.*archive", 0,
      [ "7z", "x" ]
      ]
      ,
      [ "cabextract", "cab", "CAB file", 0,
      [ "cabextract" ]
      ]
      ,
      [ "unace", "ace", "ACE.*archive", 0,
      [ "unace", "e" ]
      ]
      ,
      [ "xdms", "dms", "DMS.*archive", 0,
      [ "xdms", "x" ]
      ]
      ,
      [ "unlzx", "lzx", "LZX.*archive", 0,
      [ "unace", "e" ]
      ]
      ,
      [ "macutils", "sea|sea\.bin", "SEA.*archive", 0,
      [ "macutils", "-v" ]
      ]
      ,
      [ "macutils", "hqx", "BinHex.binary", 0,
      [ "hexbin", "-v" ]
      ]
      ,
      [ "maybe orange or unzip or unrar or unarj or lha ", "exe", "executable", 3,
      [ "orange" ],
      [ "unzip" ],
      [ "unrar", "x" ],
      [ "rar", "x" ],
      [ "arj", "x" ],
      [ "lha", "x" ]
      ]

);
}

sub show_formats
{
   print "Known archive formats and tools:\n";
   my %t;
   my $len=0;
   foreach my $line (@tools)
   {
      my @dset = @$line;
      my $sux = $dset[1];
      $sux=~s/\|/,/g;
      $t{$sux}=$dset[0];
      $len=length($sux) if(length($sux)>$len && length($sux)<20);
      #print $sux . ":\t\t$dset[0]\n";
   }
   foreach (sort (keys %t))
   {
      print "$_:";
      my $diff=$len-length($_);
      print " "x$diff." $t{$_}\n";
   }
   exit 1;
}

sub parse_cli
{
   my %options = (
      "q|quiet"                => \$opt_quiet,
      "d|debug"                => \$opt_debug,
      "h|help"                => \$opt_help,
      "f|force"               => \$opt_force,
      "s|show-formats"        => \$opt_formats,
      "u|to-subdir"           => \$opt_umode,
      "U|smart-subdir"        => \$opt_umode_smart,
      "v|verbose"             => \$opt_verbose
   );
   &show_help unless ( GetOptions(%options));
   &show_help if ($opt_help);
   &show_formats if ($opt_formats);
   while(@ARGV)
   {
      if("--" eq $ARGV[0])
      {
         shift(@ARGV);
         @xargs = @ARGV;
         last;
      }
      push(@ifiles, shift(@ARGV));
   }
   print join(" ; ", "ifiles", @ifiles, "xargs", @xargs, "argv", @ARGV, "\n") if $opt_debug;
}

sub try_unarch
{
   my $ifile=shift;
   my $magicdata=shift;
   print "magic string: $magicdata\n" if $opt_debug && $magicdata;
   foreach my $line (@tools)
   {
      my ($name, $suxARG, $patARG, $cmdflags) = @$line;

      print "hm, $magicdata vs. $patARG\n" if $opt_debug;
      # can test it with magic data whatsoever?
      next if(defined($magicdata) && !defined($patARG));

      if(
         (defined($magicdata) && $magicdata=~/$patARG/)
         || ( !defined($magicdata) && $ifile =~ /.*\.($suxARG)$/) )
      {
         print "got unpacker description for $ifile\n" if $opt_debug;
         my $misscount=0;
         my @dset = @$line;

         TOOL: foreach my $pArgs (@dset[4..$#dset])
         {
            my @args=@$pArgs;
            my @prqs = ($args[0]);

            # there is a list of prqs prepended, use that one and weed out the ref
            @prqs=@{shift(@args)} if( ref($args[0]) eq "ARRAY");

            my $misscountCur=0;
            foreach(@prqs)
            {
               if(!which($_))
               {
                  $misscountCur++;
                  $misscount++;
               }
            }

            if(! $misscountCur)
            {
               my $rcodeprev=$retcode;
               $retcode+=&unpack_one($ifile, $line, @args);
               # we must try other tools if specified and if the system call inside returned non-0 result
               next TOOL if( ($cmdflags & 2) && ($rcodeprev != $retcode));
               return 1;
            }
         }
         if($misscount)
         {
            print STDERR gettext("Error, following packages must be installed in order to proceed:\n").$name."\n";
            exit 1;
         }
      }
   }
   return 0;
}

sub getmagic
{
   if(open(my $fd, "-|", "file", shift))
   {
      return <$fd>;
      close $fd;
   }
   return "G.N.D.N.";
}

sub cat_file
{
   my $file=shift;
   if(open(my $fd, $file) )
   {
      my $buf;
      while(my $len=sysread($fd, $buf, 1<<16, 0))
      {
         my $off=0;
         my $res;
         while($res=syswrite(STDOUT, $buf, $len, $off))
         {
            die "Failed to print: $!\n" if !defined($res);
            last if 0==$res;
            $off+=$res;
            last if $off>=$len;
         }
      }
      close $fd || $retcode++;
   }
   else { $retcode++; }
}

sub process_files
{
   IFILE:
   foreach my $ifile (@ifiles)
   {
      if(!-r $ifile)
      {
         printf(gettext("Cannot read %s, skipping...\n"), $ifile);
         $retcode++;
         next IFILE;
      }
      &try_unarch($ifile) && next IFILE;
      &try_unarch($ifile, getmagic($ifile)) && next IFILE;
      print "Failed to detect file type of $ifile, skipping...\n";
   }
}

sub cat_files
{
   IFILE:
   foreach my $ifile (@ifiles)
   {
      print STDERR sprintf(gettext("Processing file %s...\n"), $ifile) if $opt_verbose;
      if(!-r $ifile)
      {
         print STDERR sprintf(gettext("Cannot read %s, skipping...\n"), $ifile);
         $retcode++;
         next IFILE;
      }
      my $magicdata=getmagic($ifile);
      print "magic string: $magicdata\n" if $opt_debug;
      foreach my $line (@tools)
      {
         my ($name, $suxARG, $patARG, $cmdflags, $cmdREF) = @$line;
         next if ! ( $cmdflags == 8 &&  $magicdata=~/$patARG/);
         $retcode += (system(@$cmdREF, $ifile) >> 8);
         next IFILE;
      }
      &cat_file($ifile);
   }
}

sub which
{
   my $prog=shift;
   for(split(/:/,$ENV{"PATH"})) {
      if(-x "$_/$prog") {
         return 1;
      }
   }
   return undef;
}

sub unpack_one
{
   print "unpack_one: @_\n" if $opt_debug;

   my $file=shift;
   my $toolRef=shift;
   my $cwd=getcwd;

   my $ret=1;
   my $flags=@{$toolRef}[3];

   my $sufpat=@{$toolRef}[1];
   my $tgtname=basename($file);
   $tgtname=~s/(.*)\.($sufpat)$/$1/i;

   return special_debmode($file) if($opt_umode && $file=~/\.deb$/i);

   # make sure that target file/directory for certain types is not occupied
   if( ( $opt_umode_smart || $opt_umode || ( $flags & (8|16)) ) && -e $tgtname)
   {
      print STDERR sprintf(gettext(
            "Cannot create target %s: file already exists. Trying alternative targets...\n"),
         $tgtname);
      $tgtname.=".unp";
      if(-e $tgtname)
      {
         print STDERR sprintf(gettext(
         "Cannot create target %s: file already exists\n"), $tgtname);
         $tgtname.=".".rand;
      }
      if(-e $tgtname)
      {
         print STDERR sprintf(gettext(
               "Cannot create target %s: file already exists\n"), $tgtname);
         exit 1 if $opt_force;
      }
      print STDERR "Suggested target name: $tgtname\n";
   }
   print "tgtname: $tgtname\n" if $opt_debug;

   my $tmpdir;

   if($opt_umode || $opt_umode_smart)
   {
      $file=Cwd::abs_path($file);
      print STDERR "set abs.path to $file\n" if $opt_debug;
      $tmpdir="unp.".rand;
      mkdir $tmpdir;
      chdir($tmpdir) || return 23;
   }

   my @cmd = (4 & $flags) ? (@_, $file, @xargs) : (@_, @xargs, $file);


   print "temp.cmd: ".join("\t", @cmd, "\n") if $opt_debug;

   # filter commands... use shell to keep our code simple. Tar stream may be
   # inside, detect it and unpack it.
   if(8 & $flags)
   {
      my $magic="";
      @cmd=("sh", "-c", join(" ", @_).' "$0" | file -', $file);
      if(open(my $fh, "-|", @cmd))
      {
         $magic = join('', <$fh>);
         close($fh);
      }
      print "Internal magic: $magic\n" if $opt_debug;
      if($magic=~/tar.archive/)
      {
         @cmd=("sh", "-c", join(" ", @_).' "$0" | tar -v -x -f - "$@" ', $file, @xargs);
      }
      else
      {
         @cmd=("sh", "-c", join(" ", @_).' "$0" > "$1"', $file, $tgtname);
      }
   }

   push(@cmd, $tgtname) if(16 & $flags);

   print join(" ", "test cmd line: ", @cmd) if $opt_debug;
   
   $ret = (system(@cmd) >> 8);

   if( $opt_umode_smart)
   {
      chdir "..";
      my @cont=(<$tmpdir/*>, <$tmpdir/.*>);
      # . and .. and one element?
      if(3==@cont)
      {
         # use same name as target, fall back to checked tgtname if that is already occupied
         my $cand=basename($cont[0]);
         if (-e $cand)
         {
            print gettext("Cannot create target directory (already exists), using alternative name\n");
            $cand=$tgtname ;
         }
         return 44 if ! (rename($cont[0], $cand) && rmdir $tmpdir);
      }
      else
      {
         rename $tmpdir, $tgtname || return 43;
      }

   }
   elsif ($opt_umode)
   {
      chdir "..";
      rename($tmpdir, $tgtname) || return 42;
   }

   chdir $cwd;

   return $ret;
}

sub special_debmode
{
   my $file=shift;
   basename($file)=~/^(.*)\.deb$/;
   my $bname=$1;
   die "cannot recognice package name\n" if !$bname;

   mkdir "control";
   my $contgt="control/$bname";
   mkdir $contgt;

   return (system("ar", "x", $file) >> 8 ) +
   (system("tar", "-z", "-x", "-v", "-f", "control.tar.gz", "-C", 
         $contgt) >> 8 ) +
   ( system("tar", "-z", "-x", "-v", "-f", "data.tar.gz") >> 8 );
}