/*  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/>.
*/

#include <algorithm>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <stdint.h>
#include <unistd.h>

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


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


void File_index::set_errno_error( const char * const msg )
  {
  error_ = msg; error_ += std::strerror( errno ); error_ += '.';
  retval_ = 1;
  }

void File_index::set_num_error( const char * const msg1, unsigned long long num,
                                const char * const msg2 )
  {
  char buf[80];
  snprintf( buf, sizeof buf, "%s%llu%s", msg1, num, msg2 );
  error_ = buf;
  retval_ = 2;
  }


File_index::File_index( const int infd )
  : isize( lseek( infd, 0, SEEK_END ) ), retval_( 0 )
  {
  if( isize < 0 )
    { set_errno_error( "Input file is not seekable: " ); return; }
  if( isize < min_member_size )
    { error_ = "Input file is too short."; retval_ = 2; return; }
  if( isize > INT64_MAX )
    { error_ = "Input file is too long (2^63 bytes or more).";
      retval_ = 2; return; }

  File_header header;
  if( seek_read( infd, header.data, File_header::size, 0 ) != File_header::size )
    { set_errno_error( "Error reading member header: " ); return; }
  if( !header.verify_magic() )
    { error_ = "Bad magic number (file not in lzip format).";
      retval_ = 2; return; }
  if( !header.verify_version() )
    { set_num_error( "Version ", header.version(),
                     " member format not supported." ); return; }

  long long pos = isize;		// always points to a header or to EOF
  while( pos >= min_member_size )
    {
    File_trailer trailer;
    if( seek_read( infd, trailer.data, File_trailer::size,
                   pos - File_trailer::size ) != File_trailer::size )
      { set_errno_error( "Error reading member trailer: " ); break; }
    const long long member_size = trailer.member_size();
    if( member_size < min_member_size || member_size > pos )
      {
      if( member_vector.empty() )
        { --pos; continue; }			// maybe trailing garbage
      set_num_error( "Member size in trailer is corrupt at pos ", pos - 8 );
      break;
      }
    if( seek_read( infd, header.data, File_header::size,
                   pos - member_size ) != File_header::size )
      { set_errno_error( "Error reading member header: " ); break; }
    if( !header.verify_magic() || !header.verify_version() )
      {
      if( member_vector.empty() )
        { --pos; continue; }			// maybe trailing garbage
      set_num_error( "Bad header at pos ", pos - member_size );
      break;
      }
    if( member_vector.empty() && isize - pos > File_header::size &&
        seek_read( infd, header.data, File_header::size, pos ) == File_header::size &&
        header.verify_magic() && header.verify_version() )
      {
      error_ = "Last member in input file is truncated or corrupt.";
      retval_ = 2; break;
      }
    pos -= member_size;
    member_vector.push_back( Member( 0, trailer.data_size(),
                                     pos, member_size ) );
    }
  if( pos != 0 || member_vector.empty() )
    {
    member_vector.clear();
    if( retval_ == 0 ) { error_ = "Can't create file index."; retval_ = 2; }
    return;
    }
  std::reverse( member_vector.begin(), member_vector.end() );
  for( unsigned long i = 0; i < member_vector.size() - 1; ++i )
    {
    const long long end = member_vector[i].dblock.end();
    if( end < 0 || end > INT64_MAX )
      {
      member_vector.clear();
      error_ = "Data in input file is too long (2^63 bytes or more).";
      retval_ = 2; return;
      }
    member_vector[i+1].dblock.pos( end );
    }
  }


// All files in 'infd_vector' must be at least 'fsize' bytes long.
File_index::File_index( const std::vector< int > & infd_vector,
                        const long long fsize )
  : isize( fsize ), retval_( 0 )
  {
  if( isize < 0 )
    { set_errno_error( "Input file is not seekable: " ); return; }
  if( isize < min_member_size )
    { error_ = "Input file is too short."; retval_ = 2; return; }
  if( isize > INT64_MAX )
    { error_ = "Input file is too long (2^63 bytes or more).";
      retval_ = 2; return; }

  const int files = infd_vector.size();
  File_header header;
  bool done = false;
  for( int i = 0; i < files && !done; ++i )
    {
    const int infd = infd_vector[i];
    if( seek_read( infd, header.data, File_header::size, 0 ) != File_header::size )
      { set_errno_error( "Error reading member header: " ); return; }
    if( header.verify_magic() && header.verify_version() ) done = true;
    }
  if( !done )
    { error_ = "Bad magic number (file not in lzip format).";
      retval_ = 2; return; }

  long long pos = isize;		// always points to a header or to EOF
  while( pos >= min_member_size )
    {
    long long member_size;
    File_trailer trailer;
    done = false;
    for( int it = 0; it < files && !done; ++it )
      {
      const int tfd = infd_vector[it];
      if( seek_read( tfd, trailer.data, File_trailer::size,
                     pos - File_trailer::size ) != File_trailer::size )
        { set_errno_error( "Error reading member trailer: " ); goto error; }
      member_size = trailer.member_size();
      if( member_size >= min_member_size && member_size <= pos )
        for( int ih = 0; ih < files && !done; ++ih )
          {
          const int hfd = infd_vector[ih];
          if( seek_read( hfd, header.data, File_header::size,
                         pos - member_size ) != File_header::size )
            { set_errno_error( "Error reading member header: " ); goto error; }
          if( header.verify_magic() && header.verify_version() ) done = true;
          }
      }
    if( !done )
      {
      if( member_vector.empty() )		// maybe trailing garbage
        { --pos; continue; }
      set_num_error( "Member size in trailer may be corrupt at pos ", pos - 8 );
      break;
      }
    if( member_vector.empty() && isize - pos > File_header::size )
      for( int i = 0; i < files; ++i )
        {
        const int infd = infd_vector[i];
        if( seek_read( infd, header.data, File_header::size, pos ) == File_header::size &&
            header.verify_magic() && header.verify_version() )
          {
          error_ = "Last member in input file is truncated or corrupt.";
          retval_ = 2; goto error;
          }
        }
    pos -= member_size;
    member_vector.push_back( Member( 0, trailer.data_size(),
                                     pos, member_size ) );
    }
error:
  if( pos != 0 || member_vector.empty() )
    {
    member_vector.clear();
    if( retval_ == 0 ) { error_ = "Can't create file index."; retval_ = 2; }
    return;
    }
  std::reverse( member_vector.begin(), member_vector.end() );
  for( unsigned long i = 0; i < member_vector.size() - 1; ++i )
    {
    const long long end = member_vector[i].dblock.end();
    if( end < 0 || end > INT64_MAX )
      {
      member_vector.clear();
      error_ = "Data in input file is too long (2^63 bytes or more).";
      retval_ = 2; return;
      }
    member_vector[i+1].dblock.pos( end );
    }
  }
