stream_flags_decoder.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. ///////////////////////////////////////////////////////////////////////////////
  2. //
  3. /// \file stream_flags_decoder.c
  4. /// \brief Decodes Stream Header and Stream Footer from .xz files
  5. //
  6. // Author: Lasse Collin
  7. //
  8. // This file has been put into the public domain.
  9. // You can do whatever you want with this file.
  10. //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "stream_flags_common.h"
  13. static bool
  14. stream_flags_decode(lzma_stream_flags *options, const uint8_t *in)
  15. {
  16. // Reserved bits must be unset.
  17. if (in[0] != 0x00 || (in[1] & 0xF0))
  18. return true;
  19. options->version = 0;
  20. options->check = in[1] & 0x0F;
  21. return false;
  22. }
  23. extern LZMA_API(lzma_ret)
  24. lzma_stream_header_decode(lzma_stream_flags *options, const uint8_t *in)
  25. {
  26. // Magic
  27. if (memcmp(in, lzma_header_magic, sizeof(lzma_header_magic)) != 0)
  28. return LZMA_FORMAT_ERROR;
  29. // Verify the CRC32 so we can distinguish between corrupt
  30. // and unsupported files.
  31. const uint32_t crc = lzma_crc32(in + sizeof(lzma_header_magic),
  32. LZMA_STREAM_FLAGS_SIZE, 0);
  33. if (crc != read32le(in + sizeof(lzma_header_magic)
  34. + LZMA_STREAM_FLAGS_SIZE)) {
  35. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  36. return LZMA_DATA_ERROR;
  37. #endif
  38. }
  39. // Stream Flags
  40. if (stream_flags_decode(options, in + sizeof(lzma_header_magic)))
  41. return LZMA_OPTIONS_ERROR;
  42. // Set Backward Size to indicate unknown value. That way
  43. // lzma_stream_flags_compare() can be used to compare Stream Header
  44. // and Stream Footer while keeping it useful also for comparing
  45. // two Stream Footers.
  46. options->backward_size = LZMA_VLI_UNKNOWN;
  47. return LZMA_OK;
  48. }
  49. extern LZMA_API(lzma_ret)
  50. lzma_stream_footer_decode(lzma_stream_flags *options, const uint8_t *in)
  51. {
  52. // Magic
  53. if (memcmp(in + sizeof(uint32_t) * 2 + LZMA_STREAM_FLAGS_SIZE,
  54. lzma_footer_magic, sizeof(lzma_footer_magic)) != 0)
  55. return LZMA_FORMAT_ERROR;
  56. // CRC32
  57. const uint32_t crc = lzma_crc32(in + sizeof(uint32_t),
  58. sizeof(uint32_t) + LZMA_STREAM_FLAGS_SIZE, 0);
  59. if (crc != read32le(in)) {
  60. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  61. return LZMA_DATA_ERROR;
  62. #endif
  63. }
  64. // Stream Flags
  65. if (stream_flags_decode(options, in + sizeof(uint32_t) * 2))
  66. return LZMA_OPTIONS_ERROR;
  67. // Backward Size
  68. options->backward_size = read32le(in + sizeof(uint32_t));
  69. options->backward_size = (options->backward_size + 1) * 4;
  70. return LZMA_OK;
  71. }