rs03-recognize.c 15.9 KB
Newer Older
1
/*  dvdisaster: Additional error correction for optical media.
2
 *  Copyright (C) 2004-2017 Carsten Gnoerlich.
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
 *
 *  Email: carsten@dvdisaster.org  -or-  cgnoerlich@fsfe.org
 *  Project homepage: http://www.dvdisaster.org
 *
 *  This file is part of dvdisaster.
 *
 *  dvdisaster 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  dvdisaster 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 dvdisaster. If not, see <http://www.gnu.org/licenses/>.
 */

#include "dvdisaster.h"
#include "udf.h"

#include "rs03-includes.h"

/*
 * Aux. functions
 */

static int valid_crc_block(unsigned char *buf, guint64 sector, int image_expected)
{  CrcBlock *cb = alloca(2048);
   guint32 recorded_crc, real_crc;

   memcpy(cb, buf, 2048);

   /* See if the magic cookie is there */

   if(   strncmp((char*)cb->cookie, "*dvdisaster*", 12)
      || strncmp((char*)cb->method, "RS03", 4))
     return 0;

   /* Examine the checksum */
   
   recorded_crc = cb->selfCRC;

#ifdef HAVE_BIG_ENDIAN
   cb->selfCRC = 0x47504c00;
#else
   cb->selfCRC = 0x4c5047;
#endif
   real_crc = Crc32((unsigned char*)cb, 2048);

   if(real_crc != recorded_crc)
   {  Verbose(".. invalid CRC block %lld\n", (unsigned long long)sector);
      return 1;
   }

   /* If an ecc file header is found in the image (which might
      rightfully contain ecc files), ignore it */

   if(image_expected && (cb->methodFlags[0] & MFLAG_ECC_FILE))
   {  Verbose(".. Crc block from ecc file in image - IGNORED\n");
      return 1;
   }
    
   return 2;
}

/***
 *** Recognize a RS03 error correction file
 ***/

int RS03RecognizeFile(LargeFile *ecc_file, EccHeader **eh)
{  int crc_block = 0;
   int n;

   Verbose("RS03RecognizeFile(): examining %s\n", ecc_file->path);
   *eh = g_malloc(sizeof(EccHeader));

   /*** First see whether we have a valid ecc header. */
   
   LargeSeek(ecc_file, 0);
   n = LargeRead(ecc_file, *eh, sizeof(EccHeader));

   /* short read -> definitely not an ecc file */
   
   if(n != sizeof(EccHeader))
   {  g_free(*eh);
      *eh=NULL;
      Verbose("RS03RecognizeFile(): short read for ecc header\n");
      return ECCFILE_INVALID;
   }

   /* Validate the header */
   
   if(!strncmp((char*)(*eh)->cookie, "*dvdisaster*", 12))
   {  guint32 recorded_crc,real_crc;
   
      /* Examine the checksum */

     recorded_crc = (*eh)->selfCRC;

#ifdef HAVE_BIG_ENDIAN
      (*eh)->selfCRC = 0x47504c00;
#else
      (*eh)->selfCRC = 0x4c5047;
#endif
      real_crc = Crc32((unsigned char*)(*eh), 4096);

#ifdef HAVE_BIG_ENDIAN
      SwapEccHeaderBytes(*eh);
#endif

      if(real_crc != recorded_crc)
      {  Verbose("RS03RecognizeFile(): checksum error in ecc header\n");
      }
      else
      {  if(!strncmp((char*)(*eh)->method, "RS03", 4))
	 {  Verbose("RS03RecognizeFile(): ecc header found\n");
	    return ECCFILE_PRESENT;
	 }
	 else
	 {  Verbose("RS03RecognizeFile(): wrong codec\n");
	    g_free(*eh);
	    *eh=NULL;
	    return ECCFILE_WRONG_CODEC;
	 }
      }
   }
   else Verbose("RS03RecognizeFile(): no magic cookie in header\n");

   /* No ecc header found; search for CRC blocks.
      The CRC block follow directly after the ecc header,
      so simply continue reading in 2048 chunks until
      the file ends. There is no good criterion for stopping
      the read earlier since the file may be truncated and/or
      contain mangled contents in many unpredictable ways. */

   Verbose("RS03RecognizeFile(): exhaustive search for CRC blocks started\n");
   
   for(;;)
   {  unsigned char buf[2048];
      n = LargeRead(ecc_file, buf, 2048);

      if(n != 2048)
      {  if(n== 0 && LargeEOF(ecc_file))
	      Verbose("RS03RecognizeFile(): end of file reached\n");
	else Verbose("RS03RecognizeFile(): short read for CRC sector %d\n", crc_block);
	 g_free(*eh);
	 *eh=NULL;
	 return ECCFILE_INVALID;
      }

      if(valid_crc_block(buf, crc_block++, FALSE) == 2)
      {  ReconstructRS03Header(*eh, (CrcBlock*)buf);
	 Verbose("** Success: sector %d, rediscovered format with %d roots\n",
		 crc_block+1, (*eh)->eccBytes);

	 /* Rewrite the missing ecc header if possible */
	 
	 if(ecc_file->flags & O_RDWR || ecc_file->flags & O_WRONLY)
	 { int success=0; 
	   EccHeader *le_eh = *eh;
	   char buf[4096];

	   memset(buf, 0, 4096);
#ifdef HAVE_BIG_ENDIAN	   
	   /* eh contains the recovered ecc header in native endian format,
	      which is what we need it in, but it must be written out in
	      little endian. So we have to create an extra copy for writing
	      out when on a big endian machine. */

	   memcpy(buf, *eh, 4096);
	   le_eh = (EccHeader*)buf;
           SwapEccHeaderBytes(le_eh);
   	   le_eh->selfCRC = 0x47504c00;
	   le_eh->selfCRC = Crc32((unsigned char*)buf, 4096);
#endif
	   if(LargeSeek(ecc_file, 0))
	   {  if(LargeWrite(ecc_file, le_eh, 4096))
	        success=1;
	   }

	   if(success) Verbose("** Missing ecc header rewritten\n");
	   else        Verbose("** Note: Could not rewrite ecc header!\n");
	 }
 	 return ECCFILE_PRESENT;
      }
   }	
	
   /* Still nothing found. */

   g_free(*eh);
   *eh=NULL;
   Verbose("RS03RecognizeFile(): no ecc found\n");
   return ECCFILE_INVALID;
}

/***
 *** Recognize RS03 error correction data in the image
 ***/

#if 0
static int read_fingerprint(LargeFile *file, unsigned char *fingerprint, gint64 sector)
{  struct MD5Context md5ctxt;
   unsigned char buf[2048];
   int n;

   if(!LargeSeek(file, 2048LL*sector))
     return FALSE;

   n = LargeRead(file, buf, 2048);

   if(n != 2048) return FALSE;

   if(CheckForMissingSector(buf, sector, NULL, 0) != SECTOR_PRESENT)
     return FALSE;

   MD5Init(&md5ctxt);
   MD5Update(&md5ctxt, buf, 2048);
   MD5Final(fingerprint, &md5ctxt);

   return TRUE;
}
#endif

static EccHeader* valid_header(unsigned char *buf, gint64 hdr_pos, int image_expected)
{  EccHeader *eh = (EccHeader*)buf;
   guint32 recorded_crc, real_crc;
   //   unsigned char fingerprint[16];

   /* Medium read error in ecc header? */

   if(   (CheckForMissingSector(buf, hdr_pos, NULL, 0) != SECTOR_PRESENT)
      || (CheckForMissingSector(buf+2048, hdr_pos+1, NULL, 0) != SECTOR_PRESENT))
     return NULL;

   /* See if the magic cookie is there */

   if(   strncmp((char*)eh->cookie, "*dvdisaster*", 12)
	 || strncmp((char*)eh->method, "RS03", 4))
     return NULL;

   /* Examine the checksum */

   recorded_crc = eh->selfCRC;

#ifdef HAVE_BIG_ENDIAN
   eh->selfCRC = 0x47504c00;
#else
   eh->selfCRC = 0x4c5047;
#endif
   real_crc = Crc32((unsigned char*)eh, 4096);

   if(real_crc != recorded_crc)
     return NULL;

   /* If an ecc file header is found in the image (which might
      rightfully contain ecc files), ignore it */

   if(image_expected && (eh->methodFlags[0] & MFLAG_ECC_FILE))
   {  Verbose(".. Ecc file header in image - IGNORED\n");
      return NULL;
   }
   
   /* Check the fingerprint */

   eh = g_malloc(sizeof(EccHeader));
   memcpy(eh, buf, sizeof(EccHeader));
#ifdef HAVE_BIG_ENDIAN
   SwapEccHeaderBytes(eh);
#endif
   eh->selfCRC = recorded_crc;

#if 0  //FIXME
   status = read_fingerprint(file, fingerprint, eh->fpSector);

   if(!status)  /* be optimistic if fingerprint sector is unreadable */
     return eh;

   if(!memcmp(fingerprint, eh->mediumFP, 16))  /* good fingerprint */
     {  printf("RS03 header found\n");
      return eh;
     }
   g_free(eh);
#endif

   return eh;
}

EccHeader* FindRS03HeaderInImage(Image *image)
{  EccHeader *eh = NULL;
   gint64 hdr_pos;
   IsoInfo *ii; 
   unsigned char buf[4096];

   switch(image->type)
   { case IMAGE_FILE:
       Verbose("FindRS03HeaderInImage: file %s\n", image->file->path);
       break;

     case IMAGE_MEDIUM:
       Verbose("FindRS03HeaderInImage: medium %s\n", image->dh->device);
       break;

     default:
       Verbose("FindRS03HeaderInImage: unknown type %d\n", image->type);
       break;
   }

   /*** Try to find the header behind the ISO image */

   ii = image->isoInfo;
   if(!ii) Verbose(" . NO ISO structures found!\n");

   if(ii)
   {  hdr_pos = ii->volumeSize;

      if(ImageReadSectors(image, buf, hdr_pos, 2) == 2)
	{  eh = valid_header(buf, hdr_pos, TRUE);
	 if(eh) 
	 { Verbose("FindRS03HeaderInImage(): Header found at pos +0\n"); 
	   return eh;
	 }
      }

      hdr_pos = ii->volumeSize - 150;
      if(ImageReadSectors(image, buf, hdr_pos, 2) == 2)
	{  eh = valid_header(buf, hdr_pos, TRUE);
	 if(eh) 
	 { Verbose("FindRS03HeaderInImage(): Header found at pos -150\n"); 
	   return eh;
	 }
      }
   }
      
   return NULL;
}

typedef struct 
{  AlignedBuffer *layer[256];
   AlignedBuffer *ab;
   RS03Layout *layout[256];
   int layer_checked[256];
} recognize_context;

static void free_recognize_context(recognize_context *rc)
{  int i;

   if(rc->ab) FreeAlignedBuffer(rc->ab);

   for(i=0; i<255; i++)
   {  if(rc->layer[i])
         FreeAlignedBuffer(rc->layer[i]);
      if(rc->layout[i])
	 g_free(rc->layout[i]); 
   }
   g_free(rc);
}
   
int RS03RecognizeImage(Image *image)
{  recognize_context *rc = g_malloc0(sizeof(recognize_context));
   guint64 image_sectors;
   guint64 layer_size;
   int untested_layers;
   int layer, layer_sector;
   int i;

   switch(image->type)
   { case IMAGE_FILE:
       Verbose("RS03RecognizeImage: file %s\n", image->file->path);
       if(image->eccFile)
	 Stop("Internal error: RS03RecognizeImage() called with ecc file\n");
       image_sectors = image->sectorSize;
       break;

     case IMAGE_MEDIUM:
       Verbose("RS03RecognizeImage: medium %s\n", image->dh->device);
       image_sectors = MAX(image->dh->readCapacity, image->dh->userAreaSize);
       break;

     default:
       Verbose("RS03RecognizeImage: unknown type %d\n", image->type);
       free_recognize_context(rc);
       return FALSE;
       break;
   }

   /* Easy shot: Locate the ecc header in the image */

   image->eccHeader = FindRS03HeaderInImage(image); 
  
   if(image->eccHeader) 
   {  free_recognize_context(rc);
      return TRUE;
   }

   /* No exhaustive search on optical media unless explicitly okayed by user */

   if(!Closure->examineRS03 && image->type == IMAGE_MEDIUM)
   {  free_recognize_context(rc);
      Verbose("RS03RecognizeImage: skipping exhaustive RS03 search\n");
      return FALSE;
   }

   /* Determine image size in augmented case. */

   Verbose("RS03RecognizeImage: No EH, entering exhaustive search\n");

412
   if(Closure->debugMode && Closure->mediumSize > 170)
413 414 415 416 417 418 419 420
   {  layer_size = Closure->mediumSize/GF_FIELDMAX;
      Verbose("Warning: image size set to %lld for debugging!\n", Closure->mediumSize);
   }
   else
   {  if(image_sectors < CDR_SIZE)         layer_size = CDR_SIZE/GF_FIELDMAX;
      else if(image_sectors < DVD_SL_SIZE) layer_size = DVD_SL_SIZE/GF_FIELDMAX; 
      else if(image_sectors < DVD_DL_SIZE) layer_size = DVD_DL_SIZE/GF_FIELDMAX; 
      else if(image_sectors < BD_SL_SIZE)  layer_size = BD_SL_SIZE/GF_FIELDMAX; 
421 422
      else if(image_sectors < BD_DL_SIZE)  layer_size = BD_DL_SIZE/GF_FIELDMAX;
      else                                 layer_size = BDXL_TL_SIZE/GF_FIELDMAX; 
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
   }

   Verbose(".. trying layer size %lld\n", layer_size);

   /*
    * Try a quick scan for the CRC sectors in order
    * to re-discover the layout.
    */

   Verbose("Scanning layers for signatures.\n");

   /* Prepare layout for all possible cases (8..170 roots) */

   for(i=84; i<=247; i++)  /* allowed range of ndata */
   {  RS03Layout *lay;
      rc->layout[i] = lay = g_malloc0(sizeof(RS03Layout));
      lay->eh = NULL;
      lay->dataSectors = (i-1)*layer_size-2;
      lay->dataPadding = 0;
      lay->totalSectors = GF_FIELDMAX*layer_size;
      lay->sectorsPerLayer = layer_size;
      lay->mediumCapacity = 0;
      lay->eccHeaderPos = lay->dataSectors;
      lay->firstCrcPos = (i-1)*layer_size;
      lay->firstEccPos = i*layer_size;
      lay->nroots = GF_FIELDMAX-i;
      lay->ndata = i;
      lay->inLast = 2048;
      lay->target = ECC_IMAGE;
   }
   untested_layers = 247-84+1;

   rc->ab = CreateAlignedBuffer(2048);

   for(layer_sector = 0; layer_sector < layer_size; layer_sector++)
   {  CrcBlock *cb = (CrcBlock*)rc->ab->buf;

      Verbose("- layer slice %d\n", layer_sector);
      for(layer = 84; layer <= 247; layer++) 
      {  if(!rc->layer_checked[layer])
	 {  gint64 sector;
	    int crc_state;

	    sector = RS03SectorIndex(rc->layout[layer], layer, layer_sector);

	    /* reading beyond the image won't yield anything */
	    if(sector >= image_sectors)
	      goto mark_invalid_layer;

	    switch(image->type)
	    {  case IMAGE_FILE:
		 RS03ReadSectors(image, rc->layout[layer], rc->ab->buf,
				 layer, layer_sector, 1, RS03_READ_ALL);
		 if(CheckForMissingSector(rc->ab->buf, sector, NULL, 0) != SECTOR_PRESENT)
		    continue;  /* unreadble -> can't decide */
		 break;

	       case IMAGE_MEDIUM:
	       {  int n;	  
		  n = ImageReadSectors(image, rc->ab->buf, sector, 1);
		  if(!n)
		    continue; /* unreadble -> can't decide */
	       }
	    }
		  
	    /* CRC header found? */

	    crc_state = valid_crc_block(rc->ab->buf, sector, TRUE);
	    if(crc_state)
	    {  int nroots=255-layer-1;  

	       if(crc_state == 1) /* corrupted crc header, try this layer again later */
		 continue;
	       Verbose("** Success: sector %lld, rediscovered format with %d roots\n",
		       sector, nroots); 
	       image->eccHeader = g_malloc(sizeof(EccHeader));
	       ReconstructRS03Header(image->eccHeader, cb);
	       /* Note: Rewriting the missing ecc header makes no sense here
		  as we do not have access to the image written in the reading
	          functions, and the error correction will restore it anyways.
	          (contrary to the situation with ecc files) */
	       free_recognize_context(rc);
	       return TRUE;
	    }

	    /* Sector readable but not a CRC header -> skip this layer */

mark_invalid_layer:
	    if(!rc->layer_checked[layer])
	    {  rc->layer_checked[layer] = 1;
	       untested_layers--;
	    }
	    if(untested_layers <= 0)
	    {  Verbose("** All layers tested -> no RS03 data found\n");
	       free_recognize_context(rc);
	       return FALSE;
	    }	       
	 }
      }
      Verbose("-> %d untested layers remaining\n", untested_layers);
   }

   Verbose("-- whole medium/image scanned; %d layers remain untested\n", untested_layers);
   Verbose("-- giving now up as ecc-based search is not yet implemented\n");
   free_recognize_context(rc);
   return FALSE;
	    
   /* 
    * TODO: Assemble all ecc blocks and see whether the error corrction
    * succeeds for a certain number of roots
    */

#if 0
   for(i=0; i<255; i++)
      rc->layer[i] = CreateAlignedBuffer(2048);

   for(ecc_block=0; ecc_block<layer_size; ecc_block++)
   {  Verbose("Assembling ecc block %d\n", ecc_block); 

      /* Assemble the ecc block */

      for(i=0; i<255; i++)  
      {  gint64 sector = rc->bidx[i]++;
	 int n;

	 if(!LargeSeek(ecc_file, (gint64)(2048*sector)))
	    Stop(_("Failed seeking to sector %lld in image: %s"),
		 sector, strerror(errno));

	 n = LargeRead(ecc_file, rc->layer[i], 2048);
	 if(n != 2048)
	    Stop(_("Failed reading sector %lld in image: %s"),sector,strerror(errno));
      }	 

      /* Experimentally apply the RS code */

      for(ndata=255-8; ndata >=85; ndata--)
      {  CrcBlock *cb = (CrcBlock*)rc->layer[ndata];

	 /* Do the real decode here */


	 /* See if we have decoded a CRC block */

	 if(  !memcmp(cb->cookie, "*dvdisaster*", 12)
	    ||!memcmp(cb->method, "RS03", 4))
	 {  
	    nroots = 255-ndata-1;
	    Verbose(".. Success: rediscovered format with %d roots\n", nroots); 

	    image->eccHeader = g_malloc(sizeof(EccHeader));
	    ReconstructRS03Header(image->eccHeader, cb);
	    //FIXME: endianess okay?
	    free_recognize_context(rc);
	    return TRUE;
	 }
      }
   }
#endif

   free_recognize_context(rc);
   return FALSE;
}