summaryrefslogtreecommitdiffstats
path: root/extract.cc
blob: 7d4b3aef9894a0e8de232081d8d520b94e320107 (plain)
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
/*  Tarlz - Archiver with multimember lzip compression
    Copyright (C) 2013-2019 Antonio Diaz Diaz.

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

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

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#define _FILE_OFFSET_BITS 64

#include <algorithm>
#include <cctype>
#include <cerrno>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <pthread.h>
#include <stdint.h>
#include <unistd.h>
#include <utime.h>
#include <sys/stat.h>
#include <sys/types.h>
#if defined(__GNU_LIBRARY__)
#include <sys/sysmacros.h>		// for major, minor, makedev
#endif
#include <lzlib.h>

#include "arg_parser.h"
#include "lzip_index.h"
#include "tarlz.h"


namespace {

Resizable_buffer grbuf;
bool archive_is_uncompressed_seekable = false;
bool archive_has_lz_ext;			// local var for archive_read

bool skip_warn( const bool reset = false )	// avoid duplicate warnings
  {
  static bool skipping = false;

  if( reset ) skipping = false;
  else if( !skipping )
    { skipping = true; show_error( "Skipping to next header." ); return true; }
  return false;
  }


bool make_path( const std::string & name )
  {
  const mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
  unsigned end = name.size();	// first slash before last component

  while( end > 0 && name[end-1] == '/' ) --end;	// remove trailing slashes
  while( end > 0 && name[end-1] != '/' ) --end;	// remove last component
  while( end > 0 && name[end-1] == '/' ) --end;	// remove more slashes

  unsigned index = 0;
  while( index < end )
    {
    while( index < end && name[index] == '/' ) ++index;
    unsigned first = index;
    while( index < end && name[index] != '/' ) ++index;
    if( first < index )
      {
      const std::string partial( name, 0, index );
      struct stat st;
      if( stat( partial.c_str(), &st ) == 0 )
        { if( !S_ISDIR( st.st_mode ) ) return false; }
      else if( mkdir( partial.c_str(), mode ) != 0 )
        return false;
      }
    }
  return true;
  }


// Return value: 0 = OK, 1 = damaged member, 2 = fatal error.
// If sizep and error, return in *sizep the number of bytes read.
// The first 6 bytes of the archive must be intact for islz to be meaningful.
int archive_read( const int infd, uint8_t * const buf, const int size,
                  int * const sizep = 0 )
  {
  static LZ_Decoder * decoder = 0;
  static bool at_eof = false;
  static bool fatal = false;
  static bool first_call = true;

  if( sizep ) *sizep = 0;
  if( fatal ) return 2;
  if( first_call )					// check format
    {
    first_call = false;
    if( size != header_size )
      internal_error( "size != header_size on first call." );
    const int rd = readblock( infd, buf, size );
    if( sizep ) *sizep = rd;
    if( rd != size && errno )
      { show_error( "Error reading archive", errno ); fatal = true; return 2; }
    const Lzip_header & header = (*(const Lzip_header *)buf);
    bool islz = ( rd >= min_member_size && header.verify_magic() &&
                  header.verify_version() &&
                  isvalid_ds( header.dictionary_size() ) );
    const bool istar = ( rd == size && verify_ustar_chksum( buf ) );
    const bool iseof =
      ( !islz && !istar && rd == size && block_is_zero( buf, size ) );
    if( !islz && !istar && !iseof )		// corrupt or invalid format
      {
      show_error( "This does not look like a POSIX tar archive." );
      if( archive_has_lz_ext && rd >= min_member_size ) islz = true;
      if( !islz ) return 1;
      }
    if( !islz )						// uncompressed
      { if( rd == size ) return 0; fatal = true; return 2; }
    archive_is_uncompressed_seekable = false;		// compressed
    decoder = LZ_decompress_open();
    if( !decoder || LZ_decompress_errno( decoder ) != LZ_ok )
      { show_error( mem_msg );
        LZ_decompress_close( decoder ); fatal = true; return 2; }
    if( LZ_decompress_write( decoder, buf, rd ) != rd )
      internal_error( "library error (LZ_decompress_write)." );
    const int res = archive_read( infd, buf, size, sizep );
    if( res != 0 ) { if( res == 2 ) fatal = true; return res; }
    if( verify_ustar_chksum( buf ) || block_is_zero( buf, size ) ) return 0;
    show_error( "This does not look like a POSIX tar.lz archive." );
    fatal = true; return 2;
    }

  if( !decoder )					// uncompressed
    {
    const int rd = readblock( infd, buf, size ); if( rd == size ) return 0;
    if( sizep ) *sizep = rd;
    show_error( "Archive ends unexpectedly." ); fatal = true; return 2;
    }
  const int ibuf_size = 16384;
  uint8_t ibuf[ibuf_size];
  int sz = 0;
  while( sz < size )
    {
    const int rd = LZ_decompress_read( decoder, buf + sz, size - sz );
    if( rd < 0 )
      {
      if( LZ_decompress_sync_to_member( decoder ) < 0 )
        internal_error( "library error (LZ_decompress_sync_to_member)." );
      skip_warn(); set_error_status( 2 ); return 1;
      }
    if( rd == 0 && LZ_decompress_finished( decoder ) == 1 )
      { LZ_decompress_close( decoder );
        show_error( "Archive ends unexpectedly." ); fatal = true; return 2; }
    sz += rd; if( sizep ) *sizep = sz;
    if( sz == size && LZ_decompress_finished( decoder ) == 1 &&
        LZ_decompress_close( decoder ) < 0 )
      { show_error( "LZ_decompress_close failed." ); fatal = true; return 2; }
    if( sz < size && !at_eof && LZ_decompress_write_size( decoder ) > 0 )
      {
      const int rsize = std::min( ibuf_size, LZ_decompress_write_size( decoder ) );
      const int rd = readblock( infd, ibuf, rsize );
      if( LZ_decompress_write( decoder, ibuf, rd ) != rd )
        internal_error( "library error (LZ_decompress_write)." );
      if( rd < rsize )
        {
        at_eof = true; LZ_decompress_finish( decoder );
        if( errno )
          { show_error( "Error reading archive", errno ); fatal = true;
            return 2; }
        }
      }
    }
  return 0;
  }


enum { mode_string_size = 10,
       group_string_size = 1 + uname_l + 1 + gname_l + 1 };	// 67

void format_mode_string( const Tar_header header, char buf[mode_string_size] )
  {
  const Typeflag typeflag = (Typeflag)header[typeflag_o];

  std::memcpy( buf, "----------", mode_string_size );
  switch( typeflag )
    {
    case tf_regular: break;
    case tf_link: buf[0] = 'h'; break;
    case tf_symlink: buf[0] = 'l'; break;
    case tf_chardev: buf[0] = 'c'; break;
    case tf_blockdev: buf[0] = 'b'; break;
    case tf_directory: buf[0] = 'd'; break;
    case tf_fifo: buf[0] = 'p'; break;
    case tf_hiperf: buf[0] = 'C'; break;
    default: buf[0] = '?';
    }
  const mode_t mode = parse_octal( header + mode_o, mode_l );	// 12 bits
  const bool setuid = mode & S_ISUID;
  const bool setgid = mode & S_ISGID;
  const bool sticky = mode & S_ISVTX;
  if( mode & S_IRUSR ) buf[1] = 'r';
  if( mode & S_IWUSR ) buf[2] = 'w';
  if( mode & S_IXUSR ) buf[3] = setuid ? 's' : 'x';
  else if( setuid ) buf[3] = 'S';
  if( mode & S_IRGRP ) buf[4] = 'r';
  if( mode & S_IWGRP ) buf[5] = 'w';
  if( mode & S_IXGRP ) buf[6] = setgid ? 's' : 'x';
  else if( setgid ) buf[6] = 'S';
  if( mode & S_IROTH ) buf[7] = 'r';
  if( mode & S_IWOTH ) buf[8] = 'w';
  if( mode & S_IXOTH ) buf[9] = sticky ? 't' : 'x';
  else if( sticky ) buf[9] = 'T';
  }


int format_user_group_string( const Tar_header header,
                              char buf[group_string_size] )
  {
  int len;
  if( header[uname_o] && header[gname_o] )
    len = snprintf( buf, group_string_size,
                    " %.32s/%.32s", header + uname_o, header + gname_o );
  else
    {
    const unsigned uid = parse_octal( header + uid_o, uid_l );
    const unsigned gid = parse_octal( header + gid_o, gid_l );
    len = snprintf( buf, group_string_size, " %u/%u", uid, gid );
    }
  return len;
  }

} // end namespace

bool block_is_zero( const uint8_t * const buf, const int size )
  {
  for( int i = 0; i < size; ++i ) if( buf[i] != 0 ) return false;
  return true;
  }


bool format_member_name( const Extended & extended, const Tar_header header,
                         Resizable_buffer & rbuf, const bool long_format )
  {
  if( long_format )
    {
    format_mode_string( header, rbuf() );
    const int group_string_len =
      format_user_group_string( header, rbuf() + mode_string_size );
    int offset = mode_string_size + group_string_len;
    const time_t mtime = parse_octal( header + mtime_o, mtime_l ); // 33 bits
    struct tm tms;
    const struct tm * tm = localtime_r( &mtime, &tms );
    if( !tm )
      { time_t z = 0; tm = localtime_r( &z, &tms ); if( !tm ) tm = &tms; }
    const Typeflag typeflag = (Typeflag)header[typeflag_o];
    const bool islink = ( typeflag == tf_link || typeflag == tf_symlink );
    const char * const link_string = !islink ? "" :
                         ( ( typeflag == tf_link ) ? " link to " : " -> " );
    if( typeflag == tf_chardev || typeflag == tf_blockdev )
      offset += snprintf( rbuf() + offset, rbuf.size() - offset, " %5u,%u",
                  (unsigned)parse_octal( header + devmajor_o, devmajor_l ),
                  (unsigned)parse_octal( header + devminor_o, devminor_l ) );
    else
      offset += snprintf( rbuf() + offset, rbuf.size() - offset, " %9llu",
                          extended.file_size() );
    for( int i = 0; i < 2; ++i )
      {
      const int len = snprintf( rbuf() + offset, rbuf.size() - offset,
                " %4d-%02u-%02u %02u:%02u %s%s%s\n",
                1900 + tm->tm_year, 1 + tm->tm_mon, tm->tm_mday,
                tm->tm_hour, tm->tm_min, extended.path().c_str(),
                link_string, islink ? extended.linkpath().c_str() : "" );
      if( (int)rbuf.size() > len + offset ) break;
      if( !rbuf.resize( len + offset + 1 ) ) return false;
      }
    }
  else
    {
    if( rbuf.size() < extended.path().size() + 2 &&
        !rbuf.resize( extended.path().size() + 2 ) ) return false;
    snprintf( rbuf(), rbuf.size(), "%s\n", extended.path().c_str() );
    }
  return true;
  }

namespace {

bool show_member_name( const Extended & extended, const Tar_header header,
                       const int vlevel, Resizable_buffer & rbuf )
  {
  if( verbosity >= vlevel )
    {
    if( !format_member_name( extended, header, rbuf, verbosity > vlevel ) )
      { show_error( mem_msg ); return false; }
    std::fputs( rbuf(), stdout );
    std::fflush( stdout );
    }
  return true;
  }


int skip_member( const int infd, const Extended & extended )
  {
  unsigned long long rest = extended.file_size();
  const int rem = rest % header_size;
  const int padding = rem ? header_size - rem : 0;
  if( archive_is_uncompressed_seekable &&
      lseek( infd, rest + padding, SEEK_CUR ) > 0 ) return 0;
  const unsigned bufsize = 32 * header_size;
  uint8_t buf[bufsize];
  while( rest > 0 )
    {
    const int rsize = ( rest >= bufsize ) ? bufsize : rest + padding;
    const int ret = archive_read( infd, buf, rsize );
    if( ret != 0 ) { if( ret == 2 ) return 2; else break; }
    if( rest < bufsize ) break;
    rest -= rsize;
    }
  return 0;
  }


void show_file_diff( const char * const filename, const char * const msg )
  {
  if( verbosity >= 0 )
    { std::printf( "%s: %s\n", filename, msg ); std::fflush( stdout ); }
  }


int compare_member( const int infd1, const Extended & extended,
                    const Tar_header header, const bool ignore_ids )
  {
  if( !show_member_name( extended, header, 1, grbuf ) ) return 1;
  unsigned long long rest = extended.file_size();
  const char * const filename = extended.path().c_str();
  const Typeflag typeflag = (Typeflag)header[typeflag_o];
  bool diff = false, size_differs = false, type_differs = true;
  struct stat st;
  if( hstat( filename, &st ) != 0 )
    show_file_error( filename, "Warning: Can't stat", errno );
  else if( ( typeflag == tf_regular || typeflag == tf_hiperf ) &&
           !S_ISREG( st.st_mode ) )
    show_file_diff( filename, "Is not a regular file" );
  else if( typeflag == tf_symlink && !S_ISLNK( st.st_mode ) )
    show_file_diff( filename, "Is not a symlink" );
  else if( typeflag == tf_chardev && !S_ISCHR( st.st_mode ) )
    show_file_diff( filename, "Is not a character device" );
  else if( typeflag == tf_blockdev && !S_ISBLK( st.st_mode ) )
    show_file_diff( filename, "Is not a block device" );
  else if( typeflag == tf_directory && !S_ISDIR( st.st_mode ) )
    show_file_diff( filename, "Is not a directory" );
  else if( typeflag == tf_fifo && !S_ISFIFO( st.st_mode ) )
    show_file_diff( filename, "Is not a FIFO" );
  else
    {
    type_differs = false;
    if( typeflag != tf_symlink )
      {
      const mode_t mode = parse_octal( header + mode_o, mode_l );  // 12 bits
      if( mode != ( st.st_mode & ( S_ISUID | S_ISGID | S_ISVTX |
                                   S_IRWXU | S_IRWXG | S_IRWXO ) ) )
        { show_file_diff( filename, "Mode differs" ); diff = true; }
      }
    if( !ignore_ids )
      {
      if( (uid_t)parse_octal( header + uid_o, uid_l ) != st.st_uid )
        { show_file_diff( filename, "Uid differs" ); diff = true; }
      if( (gid_t)parse_octal( header + gid_o, gid_l ) != st.st_gid )
        { show_file_diff( filename, "Gid differs" ); diff = true; }
      }
    if( typeflag != tf_symlink )
      {
      if( typeflag != tf_directory )
        {
        const time_t mtime = parse_octal( header + mtime_o, mtime_l ); // 33 bits
        if( mtime != st.st_mtime )
          { show_file_diff( filename, "Mod time differs" ); diff = true; }
        }
      if( ( typeflag == tf_regular || typeflag == tf_hiperf ) &&
          (off_t)rest != st.st_size )		// don't compare contents
        { show_file_diff( filename, "Size differs" ); size_differs = true; }
      if( ( typeflag == tf_chardev || typeflag == tf_blockdev ) &&
          ( parse_octal( header + devmajor_o, devmajor_l ) !=
            (unsigned)major( st.st_rdev ) ||
            parse_octal( header + devminor_o, devminor_l ) !=
            (unsigned)minor( st.st_rdev ) ) )
        { show_file_diff( filename, "Device number differs" ); diff = true; }
      }
    else
      {
      char * const buf = new char[st.st_size+1];
      long len = readlink( filename, buf, st.st_size );
      bool e = ( len != st.st_size );
      if( !e )
        {
        while( len > 1 && buf[len-1] == '/' ) --len;	// trailing '/'
        buf[len] = 0;
        if( extended.linkpath() != buf ) e = true;
        }
      delete[] buf;
      if( e ) { show_file_diff( filename, "Symlink differs" ); diff = true; }
      }
    }
  if( diff || size_differs || type_differs )
    { diff = false; set_error_status( 1 ); }
  if( rest == 0 ) return 0;
  if( ( typeflag != tf_regular && typeflag != tf_hiperf ) ||
      size_differs || type_differs ) return skip_member( infd1, extended );
  // else compare file contents
  const int rem = rest % header_size;
  const int padding = rem ? header_size - rem : 0;
  const unsigned bufsize = 32 * header_size;
  uint8_t buf1[bufsize];
  uint8_t buf2[bufsize];
  const int infd2 = open_instream( filename );
  if( infd2 < 0 )
    { set_error_status( 1 ); return skip_member( infd1, extended ); }
  int retval = 0;
  while( rest > 0 )
    {
    const int rsize1 = ( rest >= bufsize ) ? bufsize : rest + padding;
    const int rsize2 = ( rest >= bufsize ) ? bufsize : rest;
    const int ret = archive_read( infd1, buf1, rsize1 );
    if( ret != 0 ) { if( ret == 2 ) retval = 2; diff = true; break; }
    if( !diff )
      {
      const int rd = readblock( infd2, buf2, rsize2 );
      if( rd != rsize2 )
        {
        if( errno ) show_file_error( filename, "Read error", errno );
        else show_file_diff( filename, "EOF found in file" );
        diff = true;
        }
      else
        {
        int i = 0; while( i < rsize2 && buf1[i] == buf2[i] ) ++i;
        if( i < rsize2 )
          { show_file_diff( filename, "Contents differ" ); diff = true; }
        }
      }
    if( rest < bufsize ) break;
    rest -= rsize1;
    }
  if( diff ) set_error_status( 1 );
  close( infd2 );
  return retval;
  }


int list_member( const int infd, const Extended & extended,
                 const Tar_header header )
  {
  if( !show_member_name( extended, header, 0, grbuf ) ) return 1;
  return skip_member( infd, extended );
  }


bool contains_dotdot( const char * const filename )
  {
  for( int i = 0; filename[i]; ++i )
    if( dotdot_at_i( filename, i ) ) return true;
  return false;
  }


int extract_member( const int infd, const Extended & extended,
                    const Tar_header header, const bool keep_damaged )
  {
  const char * const filename = extended.path().c_str();
  if( contains_dotdot( filename ) )
    {
    show_file_error( filename, "Contains a '..' component, skipping." );
    return skip_member( infd, extended );
    }
  const mode_t mode = parse_octal( header + mode_o, mode_l );	 // 12 bits
  const time_t mtime = parse_octal( header + mtime_o, mtime_l ); // 33 bits
  const Typeflag typeflag = (Typeflag)header[typeflag_o];
  const bool islink = ( typeflag == tf_link || typeflag == tf_symlink );
  int outfd = -1;

  if( !show_member_name( extended, header, 1, grbuf ) ) return 1;
  std::remove( filename );
  make_path( filename );
  switch( typeflag )
    {
    case tf_regular:
    case tf_hiperf:
      outfd = open_outstream( filename );
      if( outfd < 0 ) return 2;
      chmod( filename, mode );			// ignore errors
      break;
    case tf_link:
    case tf_symlink:
      {
      const char * const linkname = extended.linkpath().c_str();
      const bool hard = typeflag == tf_link;
      if( ( hard && link( linkname, filename ) != 0 ) ||
          ( !hard && symlink( linkname, filename ) != 0 ) )
        {
        if( verbosity >= 0 )
          std::fprintf( stderr, "Can't %slink file '%s' to '%s': %s.\n",
                        hard ? "" : "sym", linkname, filename,
                        std::strerror( errno ) );
        return 2;
        }
      } break;
    case tf_directory:
      if( mkdir( filename, mode ) != 0 && errno != EEXIST )
        {
        show_file_error( filename, "Can't create directory", errno );
        return 2;
        }
      break;
    case tf_chardev:
    case tf_blockdev:
      {
      const unsigned dev =
        makedev( parse_octal( header + devmajor_o, devmajor_l ),
                 parse_octal( header + devminor_o, devminor_l ) );
      const int dmode = ( typeflag == tf_chardev ? S_IFCHR : S_IFBLK ) | mode;
      if( mknod( filename, dmode, dev ) != 0 )
        {
        show_file_error( filename, "Can't create device node", errno );
        return 2;
        }
      break;
      }
    case tf_fifo:
      if( mkfifo( filename, mode ) != 0 && errno != EEXIST )
        {
        show_file_error( filename, "Can't create FIFO file", errno );
        return 2;
        }
      break;
    default:
      if( verbosity >= 0 )
        std::fprintf( stderr, "File type '%c' not supported for file '%s'.\n",
                      typeflag, filename );
      return 2;
    }

  const uid_t uid = (uid_t)parse_octal( header + uid_o, uid_l );
  const gid_t gid = (gid_t)parse_octal( header + gid_o, gid_l );
  if( !islink && chown( filename, uid, gid ) != 0 &&
      errno != EPERM && errno != EINVAL )
    {
    show_file_error( filename, "Can't change file owner", errno );
    return 2;
    }

  const unsigned bufsize = 32 * header_size;
  uint8_t buf[bufsize];
  unsigned long long rest = extended.file_size();
  const int rem = rest % header_size;
  const int padding = rem ? header_size - rem : 0;
  while( rest > 0 )
    {
    const int rsize = ( rest >= bufsize ) ? bufsize : rest + padding;
    int rd;
    const int ret = archive_read( infd, buf, rsize, &rd );
    if( ret != 0 )
      {
      if( outfd >= 0 )
        {
        if( keep_damaged )
          { writeblock( outfd, buf, std::min( rest, (unsigned long long)rd ) );
            close( outfd ); }
        else { close( outfd ); std::remove( filename ); }
        }
      if( ret == 2 ) return 2; else return 0;
      }
    const int wsize = ( rest >= bufsize ) ? bufsize : rest;
    if( outfd >= 0 && writeblock( outfd, buf, wsize ) != wsize )
      { show_file_error( filename, "Error writing file", errno ); return 2; }
    rest -= wsize;
    }
  if( outfd >= 0 && close( outfd ) != 0 )
    { show_file_error( filename, "Error closing file", errno ); return 2; }
  if( !islink )
    {
    struct utimbuf t;
    t.actime = mtime;
    t.modtime = mtime;
    utime( filename, &t );			// ignore errors
    }
  return 0;
  }

} // end namespace


// return true if dir is a parent directory of name
bool compare_prefix_dir( const char * const dir, const char * const name )
  {
  int len = 0;
  while( dir[len] && dir[len] == name[len] ) ++len;
  return ( !dir[len] && len > 0 && ( dir[len-1] == '/' || name[len] == '/' ) );
  }


// compare two file names ignoring trailing slashes
bool compare_tslash( const char * const name1, const char * const name2 )
  {
  const char * p = name1;
  const char * q = name2;
  while( *p && *p == *q ) { ++p; ++q; }
  while( *p == '/' ) ++p;
  while( *q == '/' ) ++q;
  return ( !*p && !*q );
  }

namespace {

bool parse_records( const int infd, Extended & extended,
                    const Tar_header header, Resizable_buffer & rbuf,
                    const bool permissive )
  {
  const unsigned long long edsize = parse_octal( header + size_o, size_l );
  const unsigned long long bufsize = round_up( edsize );
  if( edsize == 0 || edsize >= 1ULL << 33 || bufsize == 0 || bufsize >= INT_MAX )
    return false;				// overflow or no extended data
  if( !rbuf.resize( bufsize ) ) return false;	// extended records buffer
  return ( archive_read( infd, (uint8_t *)rbuf(), bufsize ) == 0 &&
           extended.parse( rbuf(), edsize, permissive ) );
  }

} // end namespace


/* Returns the number of bytes really read.
   If (returned value < size) and (errno == 0), means EOF was reached.
*/
int readblock( const int fd, uint8_t * const buf, const int size )
  {
  int sz = 0;
  errno = 0;
  while( sz < size )
    {
    const int n = read( fd, buf + sz, size - sz );
    if( n > 0 ) sz += n;
    else if( n == 0 ) break;				// EOF
    else if( errno != EINTR ) break;
    errno = 0;
    }
  return sz;
  }


/* Returns the number of bytes really written.
   If (returned value < size), it is always an error.
*/
int writeblock( const int fd, const uint8_t * const buf, const int size )
  {
  int sz = 0;
  errno = 0;
  while( sz < size )
    {
    const int n = write( fd, buf + sz, size - sz );
    if( n > 0 ) sz += n;
    else if( n < 0 && errno != EINTR ) break;
    errno = 0;
    }
  return sz;
  }


unsigned long long parse_octal( const uint8_t * const ptr, const int size )
  {
  unsigned long long result = 0;
  int i = 0;
  while( i < size && std::isspace( ptr[i] ) ) ++i;
  for( ; i < size && ptr[i] >= '0' && ptr[i] <= '7'; ++i )
    { result <<= 3; result += ptr[i] - '0'; }
  return result;
  }


int decode( const std::string & archive_name, const Arg_parser & parser,
            const int filenames, const int num_workers, const int debug_level,
            const Program_mode program_mode, const bool ignore_ids,
            const bool keep_damaged, const bool missing_crc,
            const bool permissive )
  {
  const int infd = archive_name.size() ?
                   open_instream( archive_name ) : STDIN_FILENO;
  if( infd < 0 ) return 1;

  // Execute -C options and mark filenames to be compared, extracted or listed.
  // name_pending is of type char instead of bool to allow concurrent update.
  std::vector< char > name_pending( parser.arguments(), false );
  for( int i = 0; i < parser.arguments(); ++i )
    {
    const int code = parser.code( i );
    if( code == 'C' && program_mode != m_list )
      {
      const char * const dir = parser.argument( i ).c_str();
      if( chdir( dir ) != 0 )
        { show_file_error( dir, "Error changing working directory", errno );
          return 1; }
      }
    if( !code && parser.argument( i ).size() &&
        !Exclude::excluded( parser.argument( i ).c_str() ) )
      name_pending[i] = true;
    }

  // multi-threaded --list is faster even with 1 thread and 1 file in archive
  if( program_mode == m_list && num_workers > 0 )
    {
    const Lzip_index lzip_index( infd, true, false );	// only regular files
    const long members = lzip_index.members();
    if( lzip_index.retval() == 0 && members >= 2 )	// one file + eof
      {
      // show_file_error( archive_name.c_str(), "Is compressed seekable" );
      return list_lz( parser, name_pending, lzip_index, filenames, debug_level,
                      infd, std::min( (long)num_workers, members ),
                      missing_crc, permissive );
      }
    if( lseek( infd, 0, SEEK_SET ) == 0 && lzip_index.retval() != 0 &&
        lzip_index.file_size() > 3 * header_size )
      archive_is_uncompressed_seekable = true;	// unless compressed corrupt
    }

  archive_has_lz_ext = has_lz_ext( archive_name );	// var for archive_read
  Extended extended;			// metadata from extended records
  int retval = 0;
  bool prev_extended = false;		// prev header was extended
  while( true )				// process one tar member per iteration
    {
    Tar_header header;
    const int ret = archive_read( infd, header, header_size );
    if( ret == 2 ) return 2;
    if( ret != 0 || !verify_ustar_chksum( header ) )
      {
      if( ret == 0 && block_is_zero( header, header_size ) )
        {
        if( !prev_extended ) break;		// EOF
        show_file_error( archive_name.c_str(),
          "Format violation: extended header followed by EOF blocks." );
        return 2;
        }
      if( skip_warn() && verbosity >= 2 )
        std::fprintf( stderr, "ustar chksum = %07o\n", ustar_chksum( header ) );
      set_error_status( 2 ); continue;
      }
    skip_warn( true );				// reset warning

    const Typeflag typeflag = (Typeflag)header[typeflag_o];
    if( typeflag == tf_global )
      {
      if( prev_extended )
        { show_file_error( archive_name.c_str(),
            "Format violation: extended header followed by global header." );
          return 2; }
      Extended dummy;		// global headers are parsed and ignored
      if( !parse_records( infd, dummy, header, grbuf, true ) )
        { show_file_error( archive_name.c_str(),
            "Error in global extended records. Skipping to next header." );
          set_error_status( 2 ); }
      continue;
      }
    if( typeflag == tf_extended )
      {
      if( prev_extended && !permissive )
        { show_file_error( archive_name.c_str(),
            "Format violation: consecutive extended headers found."
                      /*" Use --permissive.", 0, true*/ ); return 2; }
      if( !parse_records( infd, extended, header, grbuf, permissive ) )
        { show_file_error( archive_name.c_str(),
            "Error in extended records. Skipping to next header." );
          extended.reset(); set_error_status( 2 ); }
      else if( !extended.crc_present() && missing_crc )
        { show_file_error( archive_name.c_str(),
                           "Missing CRC in extended records." ); return 2; }
      prev_extended = true;
      continue;
      }
    prev_extended = false;

    extended.fill_from_ustar( header );		// copy metadata from header

    const bool skip = check_skip_filename( parser, name_pending,
                                       extended.path().c_str(), filenames );
    if( skip )
      retval = skip_member( infd, extended );
    else if( program_mode == m_list )
      retval = list_member( infd, extended, header );
    else if( program_mode == m_diff )
      retval = compare_member( infd, extended, header, ignore_ids );
    else
      retval = extract_member( infd, extended, header, keep_damaged );
    extended.reset();
    if( retval )
      { show_error( "Error is not recoverable: exiting now." );
        return retval; }
    }

  for( int i = 0; i < parser.arguments(); ++i )
    if( !parser.code( i ) && parser.argument( i ).size() && name_pending[i] )
      {
      show_file_error( parser.argument( i ).c_str(), "Not found in archive." );
      retval = 1;
      }
  return final_exit_status( retval, program_mode != m_diff );
  }