summaryrefslogtreecommitdiffstats
path: root/repair.cc
blob: e8588e3545a03500eb2a768cd6a6dca7b04b2301 (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
/*  Lziprecover - Data recovery tool for the lzip format
    Copyright (C) 2009-2015 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 <cerrno>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <stdint.h>
#include <unistd.h>
#include <sys/stat.h>

#include "lzip.h"
#include "mtester.h"
#include "block.h"
#include "file_index.h"


namespace {

bool gross_damage( const long long msize, const uint8_t * const mbuffer )
  {
  enum { maxlen = 6 };		// max number of consecutive identical bytes
  long i = File_header::size;
  const long end = msize - File_trailer::size - maxlen;
  while( i < end )
    {
    const uint8_t byte = mbuffer[i];
    int len = 0;			// does not count the first byte
    while( mbuffer[++i] == byte && ++len < maxlen ) {}
    if( len >= maxlen ) return true;
    }
  return false;
  }


int seek_write( const int fd, const uint8_t * const buf, const int size,
                const long long pos )
  {
  if( lseek( fd, pos, SEEK_SET ) == pos )
    return writeblock( fd, buf, size );
  return 0;
  }

// Return value: -1 = master failed, 0 = begin reached, >0 = repaired pos
long repair_member( const long long mpos, const long long msize,
                    uint8_t * const mbuffer, const long begin, const long end,
                    const int verbosity )
  {
  for( long pos = end; pos >= begin && pos > end - 50000; )
    {
    const long min_pos = std::max( begin, pos - 100 );
    const LZ_mtester * master = prepare_master( mbuffer, msize, min_pos - 16 );
    if( !master ) return -1;
    for( ; pos >= min_pos; --pos )
      {
      if( verbosity >= 1 )
        {
        std::printf( "Trying position %llu \r", mpos + pos );
        std::fflush( stdout );
        }
      for( int j = 0; j < 255; ++j )
        {
        ++mbuffer[pos];
        if( test_member_rest( *master ) ) { delete master; return pos; }
        }
      ++mbuffer[pos];
      }
    delete master;
    }
  return 0;
  }

} // end namespace


int repair_file( const std::string & input_filename,
                 const std::string & output_filename, const int verbosity,
                 const bool force )
  {
  struct stat in_stats;				// not used
  const int infd = open_instream( input_filename.c_str(), &in_stats, true, true );
  if( infd < 0 ) return 1;

  Pretty_print pp( input_filename, verbosity );
  const File_index file_index( infd );
  if( file_index.retval() != 0 )
    { pp( file_index.error().c_str() ); return file_index.retval(); }

  if( !force && file_exists( output_filename ) ) return 1;
  int outfd = -1;
  for( long i = 0; i < file_index.members(); ++i )
    {
    const long long mpos = file_index.mblock( i ).pos();
    const long long msize = file_index.mblock( i ).size();
    if( !safe_seek( infd, mpos ) )
      cleanup_and_fail( output_filename, outfd, 1 );
    long long failure_pos = 0;
    if( try_decompress_member( infd, msize, &failure_pos ) ) continue;
    if( failure_pos < File_header::size )
      { show_error( "Can't repair error in input file." );
        cleanup_and_fail( output_filename, outfd, 2 ); }

    if( verbosity >= 1 )		// damaged member found
      {
      std::printf( "Repairing member %ld of %ld  (failure pos = %llu)\n",
                   i + 1, file_index.members(), mpos + failure_pos );
      std::fflush( stdout );
      }
    if( failure_pos >= msize - 8 ) failure_pos = msize - 8 - 1;
    uint8_t * const mbuffer = read_member( infd, mpos, msize );
    if( !mbuffer )
      cleanup_and_fail( output_filename, outfd, 1 );
    long pos = 0;
    if( !gross_damage( msize, mbuffer ) )
      {
      pos = repair_member( mpos, msize, mbuffer, File_header::size + 1,
                           File_header::size + 2, verbosity );
      if( pos == 0 )
        pos = repair_member( mpos, msize, mbuffer, File_header::size + 3,
                             failure_pos, verbosity );
      }
    if( pos < 0 )
      cleanup_and_fail( output_filename, outfd, 1 );
    if( pos > 0 )
      {
      if( outfd < 0 )		// first damaged member repaired
        {
        if( !safe_seek( infd, 0 ) ) return 1;
        outfd = open_outstream_rw( output_filename, true );
        if( outfd < 0 ) { close( infd ); return 1; }
        if( !copy_file( infd, outfd ) )		// copy whole file
          cleanup_and_fail( output_filename, outfd, 1 );
        }
      if( seek_write( outfd, mbuffer + pos, 1, mpos + pos ) != 1 )
        { show_error( "Error writing output file", errno );
          cleanup_and_fail( output_filename, outfd, 1 ); }
      }
    delete[] mbuffer;
    if( verbosity >= 1 ) std::fputc( '\n', stdout );
    if( pos == 0 )
      {
      show_error( "Can't repair input file. Error is probably larger than 1 byte." );
      cleanup_and_fail( output_filename, outfd, 2 );
      }
    }

  if( outfd < 0 )
    {
    if( verbosity >= 1 )
      std::fputs( "Input file has no errors. Recovery is not needed.\n", stdout );
    return 0;
    }
  if( close( outfd ) != 0 )
    {
    show_error( "Error closing output file", errno );
    cleanup_and_fail( output_filename, -1, 1 );
    }
  if( verbosity >= 1 )
    std::fputs( "Copy of input file repaired successfully.\n", stdout );
  return 0;
  }


int debug_delay( const std::string & input_filename, Block range,
                 const int verbosity )
  {
  struct stat in_stats;				// not used
  const int infd = open_instream( input_filename.c_str(), &in_stats, true, true );
  if( infd < 0 ) return 1;

  Pretty_print pp( input_filename, verbosity );
  const File_index file_index( infd );
  if( file_index.retval() != 0 )
    { pp( file_index.error().c_str() ); return file_index.retval(); }

  if( range.end() > file_index.file_end() )
    range.size( std::max( 0LL, file_index.file_end() - range.pos() ) );
  if( range.size() <= 0 )
    { if( verbosity >= 0 ) pp( "Nothing to do." ); return 0; }

  for( long i = 0; i < file_index.members(); ++i )
    {
    const Block & mb = file_index.mblock( i );
    if( !range.overlaps( mb ) ) continue;
    const long long mpos = file_index.mblock( i ).pos();
    const long long msize = file_index.mblock( i ).size();
    if( verbosity >= 1 )
      {
      std::printf( "Finding max delay in member %ld of %ld  (mpos = %llu, msize = %llu)\n",
                   i + 1, file_index.members(), mpos, msize );
      std::fflush( stdout );
      }
    uint8_t * const mbuffer = read_member( infd, mpos, msize );
    if( !mbuffer ) return 1;
    long pos = std::max( range.pos() - mpos, File_header::size + 1LL );
    const long end = std::min( range.end() - mpos, msize );
    long max_delay = 0;
    while( pos < end )
      {
      const LZ_mtester * master = prepare_master( mbuffer, msize, pos - 16 );
      if( !master )
        { show_error( "Can't prepare master." ); return 1; }
      const long partial_end = std::min( pos + 100, end );
      for( ; pos < partial_end; ++pos )
        {
        if( verbosity >= 1 )
          {
          std::printf( "Delays in position %llu \r", mpos + pos );
          std::fflush( stdout );
          }
        int value = -1;
        for( int j = 0; j < 256; ++j )
          {
          ++mbuffer[pos];
          if( j == 255 ) break;
          long failure_pos;
          if( test_member_rest( *master, &failure_pos ) ) continue;
          const long delay = failure_pos - pos;
          if( delay > max_delay ) { max_delay = delay; value = mbuffer[pos]; }
          }
        if( value >= 0 && verbosity >= 0 )
          {
          std::printf( "New max delay %lu at position %llu (0x%02X)\n",
                       max_delay, mpos + pos, value );
          std::fflush( stdout );
          }
        if( pos + max_delay >= msize ) { pos = end; break; }
        }
      delete master;
      }
    delete[] mbuffer;
    if( verbosity >= 1 ) std::fputc( '\n', stdout );
    }

  if( verbosity >= 1 ) std::fputs( "Done.\n", stdout );
  return 0;
  }


int debug_repair( const std::string & input_filename, const long long bad_pos,
                  const int verbosity, const uint8_t bad_value )
  {
  struct stat in_stats;				// not used
  const int infd = open_instream( input_filename.c_str(), &in_stats, true, true );
  if( infd < 0 ) return 1;

  Pretty_print pp( input_filename, verbosity );
  const File_index file_index( infd );
  if( file_index.retval() != 0 )
    { pp( file_index.error().c_str() ); return file_index.retval(); }

  long idx = 0;
  for( ; idx < file_index.members(); ++idx )
    if( file_index.mblock( idx ).includes( bad_pos ) ) break;
  if( idx >= file_index.members() )
    { if( verbosity >= 0 ) pp( "Nothing to do." ); return 0; }

  const long long mpos = file_index.mblock( idx ).pos();
  const long long msize = file_index.mblock( idx ).size();
  {
  long long failure_pos = 0;
  if( !safe_seek( infd, mpos ) ) return 1;
  if( !try_decompress_member( infd, msize, &failure_pos ) )
    {
    if( verbosity >= 0 )
      std::printf( "Member %ld of %ld already damaged  (failure pos = %llu)\n",
                   idx + 1, file_index.members(), mpos + failure_pos );
    return 1;
    }
  }
  uint8_t * const mbuffer = read_member( infd, mpos, msize );
  if( !mbuffer ) return 1;
  const uint8_t good_value = mbuffer[bad_pos-mpos];
  mbuffer[bad_pos-mpos] = bad_value;
  long failure_pos = 0;
  {
  const LZ_mtester * master = prepare_master( mbuffer, msize, 0 );
  if( !master )
    { show_error( "Can't prepare master." ); delete[] mbuffer; return 1; }
  if( test_member_rest( *master, &failure_pos ) )
    {
    if( verbosity >= 1 )
      std::fputs( "Member decompressed with no errors.\n", stdout );
    delete master;
    delete[] mbuffer;
    return 0;
    }
  delete master;
  if( verbosity >= 1 )
    {
    std::printf( "Test repairing member %ld of %ld  (mpos = %llu, msize = %llu)\n"
                 "  (damage pos = %llu (0x%02X->0x%02X), failure pos = %llu)\n",
                 idx + 1, file_index.members(), mpos, msize,
                 bad_pos, good_value, bad_value, mpos + failure_pos );
    std::fflush( stdout );
    }
  }
  if( failure_pos >= msize ) failure_pos = msize - 1;
  long pos = repair_member( mpos, msize, mbuffer, File_header::size + 1,
                            File_header::size + 2, verbosity );
  if( pos == 0 )
    pos = repair_member( mpos, msize, mbuffer, File_header::size + 3,
                         failure_pos, verbosity );
  delete[] mbuffer;
  if( pos < 0 )
    { show_error( "Can't prepare master." ); return 1; }
  if( verbosity >= 1 ) std::fputc( '\n', stdout );
  if( pos == 0 ) internal_error( "can't repair input file." );
  if( verbosity >= 1 )
    std::fputs( "Member repaired successfully.\n", stdout );
  return 0;
  }


int debug_show_packets( const std::string & input_filename,
                        const long long bad_pos, const int verbosity,
                        const uint8_t bad_value )
  {
  struct stat in_stats;				// not used
  const int infd = open_instream( input_filename.c_str(), &in_stats, true, true );
  if( infd < 0 ) return 1;

  Pretty_print pp( input_filename, verbosity );
  const File_index file_index( infd );
  if( file_index.retval() != 0 )
    { pp( file_index.error().c_str() ); return file_index.retval(); }

  int retval = 0;
  for( long i = 0; i < file_index.members(); ++i )
    {
    const long long dpos = file_index.dblock( i ).pos();
    const long long mpos = file_index.mblock( i ).pos();
    const long long msize = file_index.mblock( i ).size();
    if( verbosity >= 1 )
      std::printf( "Decoding LZMA packets in member %ld of %ld  (mpos = %llu, msize = %llu)\n"
                   "  mpos   dpos\n",
                   i + 1, file_index.members(), mpos, msize );
    uint8_t * const mbuffer = read_member( infd, mpos, msize );
    if( !mbuffer ) return 1;
    const File_header & header = *(File_header *)mbuffer;
    const unsigned dictionary_size = header.dictionary_size();
    if( !header.verify_magic() || !header.verify_version() ||
        dictionary_size < min_dictionary_size ||
        dictionary_size > max_dictionary_size )
      { show_error( "Header error." ); return 2; }
    if( bad_pos >= 0 && file_index.mblock( i ).includes( bad_pos ) )
      {
      if( verbosity >= 1 )
        std::printf( "Byte at pos %llu changed from 0x%02X to 0x%02X\n",
                     bad_pos, mbuffer[bad_pos-mpos], bad_value );
      mbuffer[bad_pos-mpos] = bad_value;
      }
    LZ_mtester mtester( mbuffer, msize, dictionary_size );
    const int result = mtester.debug_decode_member( dpos, mpos, true );
    delete[] mbuffer;
    if( result != 0 )
      {
      if( verbosity >= 0 && result <= 2 )
        std::printf( "%s at pos %llu\n", ( result == 2 ) ?
                     "File ends unexpectedly" : "Decoder error",
                     mpos + mtester.member_position() );
      retval = 2; break;
      }
    if( i + 1 < file_index.members() ) std::fputc( '\n', stdout );
    }

  if( verbosity >= 1 ) std::fputs( "Done.\n", stdout );
  return retval;
  }