// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Mobius Forensic Toolkit
// Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019 Eduardo Aguiar
//
// 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, 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 "imagefile_impl.h"
#include "sector_reader_impl_dynamic.h"
#include "sector_reader_impl_fixed.h"
#include <mobius/decoder/data_decoder.h>
#include <mobius/exception.inc>
#include <mobius/io/file.h>
#include <mobius/io/sector_reader.h>
#include <stdexcept>

namespace mobius
{
namespace imagefile
{
namespace vhd
{
namespace
{
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Constants
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
static constexpr int SECTOR_SIZE = 512;		// always 512 bytes
static constexpr int DISK_TYPE_FIXED = 2;
static constexpr int DISK_TYPE_DYNAMIC = 3;
static constexpr int DISK_TYPE_DIFFERENCING = 4;

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//! \brief Decode timestamp
//! \return datetime object
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
mobius::datetime::datetime
decode_timestamp (std::uint32_t timestamp)
{
  mobius::datetime::datetime dt;

  if (timestamp)
    dt = mobius::datetime::datetime (2000, 1, 1, 0, 0, 0) + mobius::datetime::timedelta (0, 0, timestamp, 0);

  return dt;
}

} // namespace

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//! \brief Check if URL is an instance of imagefile vhd
//! \return True/false
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
bool
imagefile_impl::is_instance (const std::string& url)
{
  bool is_instance = false;
  mobius::io::file f (url);

  if (f && f.exists ())
    {
      auto reader = f.new_reader ();
      reader.seek (-SECTOR_SIZE, mobius::io::reader::whence_type::end);

      auto data = reader.read (8);
      is_instance = data == "conectix";
    }

  return is_instance;
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//! \brief Constructor
//! \param url Imagefile URL
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
imagefile_impl::imagefile_impl (const std::string& url)
  : url_ (url)
{
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//! \brief Create new sector_reader for imagefile
//! \return sector_reader
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
mobius::io::sector_reader
imagefile_impl::new_sector_reader () const
{
  if (disk_type_ == DISK_TYPE_FIXED)
    return mobius::io::sector_reader (
             std::make_shared <sector_reader_impl_fixed> (*this)
           );

  else if (disk_type_ == DISK_TYPE_DYNAMIC)
    return mobius::io::sector_reader (
             std::make_shared <sector_reader_impl_dynamic> (*this)
           );

  else
    throw std::runtime_error (MOBIUS_EXCEPTION_MSG ("Unsupported disk type"));
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//! \brief Create new reader for imagefile
//! \return reader
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
mobius::io::reader
imagefile_impl::new_reader () const
{
  return mobius::io::new_reader_from_sector_reader (new_sector_reader ());
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//! \brief Create new writer for imagefile
//! \return writer
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
mobius::io::writer
imagefile_impl::new_writer () const
{
  throw std::runtime_error (MOBIUS_EXCEPTION_MSG ("Writer not implemented"));
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//! \brief Get metadata
//! \return Imagefile metadata
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
mobius::metadata
imagefile_impl::get_metadata () const
{
  return mobius::metadata
  {
    {
      "url",
      "URL",
      "std::string",
      url_
    },
    {
      "type",
      "type",
      "std::string",
      get_type ()
    },
    {
      "size",
      "size",
      "size_type",
      std::to_string (get_size ()) + " bytes"
    },
    {
      "sectors",
      "number of sectors",
      "size_type",
      std::to_string (get_sectors ())
    },
    {
      "sector_size",
      "sector size",
      "size_type",
      std::to_string (get_sector_size ()) + " bytes"
    },
    {
      "format_version",
      "file format version",
      "std::string",
      get_format_version ()
    },
    {
      "disk_type",
      "disk type",
      "std::uint32_t",
      std::to_string (get_disk_type ())
    },
    {
      "uuid",
      "disk UUID",
      "std::string",
      get_disk_uuid ()
    },
    {
      "acquisition_time",
      "acquisition date/time",
      "mobius::datetime::datetime",
      to_string (get_acquisition_time ())
    },
    {
      "acquisition_tool",
      "acquisition tool",
      "std::string",
      get_acquisition_tool ()
    },
    {
      "acquisition_platform",
      "acquisition platform",
      "std::string",
      get_acquisition_platform ()
    },
  };
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//! \brief Get Block Allocation Table
//! \return Table
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
imagefile_impl::table_type
imagefile_impl::get_block_allocation_table () const
{
  if (get_disk_type () != DISK_TYPE_DYNAMIC)
    throw std::runtime_error (MOBIUS_EXCEPTION_MSG ("Disk type has no Block Allocation Table"));

  return block_allocation_table_;
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//! \brief Get block size
//! \return block size
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
std::uint32_t
imagefile_impl::get_block_size () const
{
  if (get_disk_type () != DISK_TYPE_DYNAMIC)
    throw std::runtime_error (MOBIUS_EXCEPTION_MSG ("Disk type has no block size"));

  return block_size_;
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//! \brief Load metadata from imagefile
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void
imagefile_impl::_load_metadata () const
{
  if (metadata_loaded_)
    return;

  // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  // Check if imagefile exists
  // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  mobius::io::file f (url_);

  if (!f || !f.exists ())
    throw std::runtime_error (MOBIUS_EXCEPTION_MSG ("Image file not found"));

  // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  // Decode Hard Disk Footer
  // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  auto reader = f.new_reader ();
  reader.seek (-SECTOR_SIZE, mobius::io::reader::whence_type::end);
  mobius::decoder::data_decoder decoder (reader);
  
  // test signature
  auto signature = decoder.get_string_by_size (8);

  if (signature != "conectix")
    throw std::runtime_error (MOBIUS_EXCEPTION_MSG ("Invalid VHD signature"));

  // features
  decoder.skip (4);
  
  // format version
  format_version_ = std::to_string (decoder.get_uint16_be ());
  format_version_ += '.' + std::to_string (decoder.get_uint16_be ());
  
  // data offset
  auto data_offset = decoder.get_uint64_be ();
  
  // acquisition info
  acquisition_time_ = decode_timestamp (decoder.get_uint32_be ());

  acquisition_tool_ = decoder.get_string_by_size (4) + " v";
  acquisition_tool_ += std::to_string (decoder.get_uint16_be ());
  acquisition_tool_ += '.' + std::to_string (decoder.get_uint16_be ());
  
  acquisition_platform_ = decoder.get_string_by_size (4);
  
  // size
  decoder.skip (8);		// original size
  size_ = decoder.get_uint64_be ();
  sector_size_ = SECTOR_SIZE;	// constant
  sectors_ = (size_ + sector_size_ - 1) / sector_size_;

  // disk type
  decoder.skip (4);		// disk geometry
  disk_type_ = decoder.get_uint32_be ();
  decoder.skip (4);		// checksum

  if (disk_type_ != DISK_TYPE_FIXED && disk_type_ != DISK_TYPE_DYNAMIC)
    throw std::runtime_error (MOBIUS_EXCEPTION_MSG ("Unsupported disk type"));

  // UUID
  disk_uuid_ = decoder.get_uuid ();

  // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  // Decode Dynamic Disk Header, if disk type == 3 (DISK_TYPE_DYNAMIC)
  // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  if (disk_type_ == DISK_TYPE_DYNAMIC)
    {
      decoder.seek (data_offset);
      
      // test signature
      auto signature = decoder.get_string_by_size (8);

      if (signature != "cxsparse")
        throw std::runtime_error (MOBIUS_EXCEPTION_MSG ("Invalid VHD Dynamic Disk Header signature"));
      
      // data offset (unused)
      decoder.skip (8);
      
      // table offset
      auto table_offset = decoder.get_uint64_be ();
      
      // header version
      decoder.skip (4);
      
      // max_table_entries
      auto max_table_entries = decoder.get_uint32_be ();

      // block_size
      block_size_ = decoder.get_uint32_be ();

      // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
      // Decode Block Allocation Table
      // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
      decoder.seek (table_offset);

      block_allocation_table_.reserve (max_table_entries);

      for (std::uint64_t i = 0;i < max_table_entries; i++)
        {
          auto offset = decoder.get_uint32_be ();
          block_allocation_table_.push_back (offset);
        }
    }

  metadata_loaded_ = true;
}

} // namespace vhd
} // namespace imagefile
} // namespace mobius
