Gzip.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. /*
  2. * Copyright (c) 2020-2022, the SerenityOS developers.
  3. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibCompress/Gzip.h>
  8. #include <AK/DeprecatedString.h>
  9. #include <AK/MemoryStream.h>
  10. #include <LibCore/DateTime.h>
  11. #include <LibCore/MemoryStream.h>
  12. namespace Compress {
  13. bool GzipDecompressor::is_likely_compressed(ReadonlyBytes bytes)
  14. {
  15. return bytes.size() >= 2 && bytes[0] == gzip_magic_1 && bytes[1] == gzip_magic_2;
  16. }
  17. bool BlockHeader::valid_magic_number() const
  18. {
  19. return identification_1 == gzip_magic_1 && identification_2 == gzip_magic_2;
  20. }
  21. bool BlockHeader::supported_by_implementation() const
  22. {
  23. if (compression_method != 0x08) {
  24. // RFC 1952 does not define any compression methods other than deflate.
  25. return false;
  26. }
  27. if (flags > Flags::MAX) {
  28. // RFC 1952 does not define any more flags.
  29. return false;
  30. }
  31. return true;
  32. }
  33. GzipDecompressor::GzipDecompressor(NonnullOwnPtr<Core::Stream::Stream> stream)
  34. : m_input_stream(move(stream))
  35. {
  36. }
  37. GzipDecompressor::~GzipDecompressor()
  38. {
  39. m_current_member.clear();
  40. }
  41. ErrorOr<Bytes> GzipDecompressor::read(Bytes bytes)
  42. {
  43. size_t total_read = 0;
  44. while (total_read < bytes.size()) {
  45. if (is_eof())
  46. break;
  47. auto slice = bytes.slice(total_read);
  48. if (m_current_member.has_value()) {
  49. auto current_slice = TRY(current_member().m_stream.read(slice));
  50. current_member().m_checksum.update(current_slice);
  51. current_member().m_nread += current_slice.size();
  52. if (current_slice.size() < slice.size()) {
  53. LittleEndian<u32> crc32, input_size;
  54. TRY(m_input_stream->read(crc32.bytes()));
  55. TRY(m_input_stream->read(input_size.bytes()));
  56. if (crc32 != current_member().m_checksum.digest())
  57. return Error::from_string_literal("Stored CRC32 does not match the calculated CRC32 of the current member");
  58. if (input_size != current_member().m_nread)
  59. return Error::from_string_literal("Input size does not match the number of read bytes");
  60. m_current_member.clear();
  61. total_read += current_slice.size();
  62. continue;
  63. }
  64. total_read += current_slice.size();
  65. continue;
  66. } else {
  67. auto current_partial_header_slice = Bytes { m_partial_header, sizeof(BlockHeader) }.slice(m_partial_header_offset);
  68. auto current_partial_header_data = TRY(m_input_stream->read(current_partial_header_slice));
  69. m_partial_header_offset += current_partial_header_data.size();
  70. if (is_eof())
  71. break;
  72. if (m_partial_header_offset < sizeof(BlockHeader)) {
  73. break; // partial header read
  74. }
  75. m_partial_header_offset = 0;
  76. BlockHeader header = *(reinterpret_cast<BlockHeader*>(m_partial_header));
  77. if (!header.valid_magic_number())
  78. return Error::from_string_literal("Header does not have a valid magic number");
  79. if (!header.supported_by_implementation())
  80. return Error::from_string_literal("Header is not supported by implementation");
  81. if (header.flags & Flags::FEXTRA) {
  82. LittleEndian<u16> subfield_id, length;
  83. TRY(m_input_stream->read(subfield_id.bytes()));
  84. TRY(m_input_stream->read(length.bytes()));
  85. TRY(m_input_stream->discard(length));
  86. }
  87. auto discard_string = [&]() -> ErrorOr<void> {
  88. char next_char;
  89. do {
  90. TRY(m_input_stream->read({ &next_char, sizeof(next_char) }));
  91. } while (next_char);
  92. return {};
  93. };
  94. if (header.flags & Flags::FNAME)
  95. TRY(discard_string());
  96. if (header.flags & Flags::FCOMMENT)
  97. TRY(discard_string());
  98. if (header.flags & Flags::FHCRC) {
  99. LittleEndian<u16> crc16;
  100. TRY(m_input_stream->read(crc16.bytes()));
  101. // FIXME: we should probably verify this instead of just assuming it matches
  102. }
  103. m_current_member.emplace(header, *m_input_stream);
  104. continue;
  105. }
  106. }
  107. return bytes.slice(0, total_read);
  108. }
  109. Optional<DeprecatedString> GzipDecompressor::describe_header(ReadonlyBytes bytes)
  110. {
  111. if (bytes.size() < sizeof(BlockHeader))
  112. return {};
  113. auto& header = *(reinterpret_cast<BlockHeader const*>(bytes.data()));
  114. if (!header.valid_magic_number() || !header.supported_by_implementation())
  115. return {};
  116. LittleEndian<u32> original_size = *reinterpret_cast<u32 const*>(bytes.offset(bytes.size() - sizeof(u32)));
  117. return DeprecatedString::formatted("last modified: {}, original size {}", Core::DateTime::from_timestamp(header.modification_time).to_deprecated_string(), (u32)original_size);
  118. }
  119. ErrorOr<ByteBuffer> GzipDecompressor::decompress_all(ReadonlyBytes bytes)
  120. {
  121. auto memory_stream = TRY(Core::Stream::FixedMemoryStream::construct(bytes));
  122. auto gzip_stream = make<GzipDecompressor>(move(memory_stream));
  123. DuplexMemoryStream output_stream;
  124. auto buffer = TRY(ByteBuffer::create_uninitialized(4096));
  125. while (!gzip_stream->is_eof()) {
  126. auto const data = TRY(gzip_stream->read(buffer));
  127. output_stream.write_or_error(data);
  128. }
  129. return output_stream.copy_into_contiguous_buffer();
  130. }
  131. bool GzipDecompressor::is_eof() const { return m_input_stream->is_eof(); }
  132. ErrorOr<size_t> GzipDecompressor::write(ReadonlyBytes)
  133. {
  134. VERIFY_NOT_REACHED();
  135. }
  136. GzipCompressor::GzipCompressor(OutputStream& stream)
  137. : m_output_stream(stream)
  138. {
  139. }
  140. size_t GzipCompressor::write(ReadonlyBytes bytes)
  141. {
  142. BlockHeader header;
  143. header.identification_1 = 0x1f;
  144. header.identification_2 = 0x8b;
  145. header.compression_method = 0x08;
  146. header.flags = 0;
  147. header.modification_time = 0;
  148. header.extra_flags = 3; // DEFLATE sets 2 for maximum compression and 4 for minimum compression
  149. header.operating_system = 3; // unix
  150. m_output_stream << Bytes { &header, sizeof(header) };
  151. DeflateCompressor compressed_stream { m_output_stream };
  152. VERIFY(compressed_stream.write_or_error(bytes));
  153. compressed_stream.final_flush();
  154. Crypto::Checksum::CRC32 crc32;
  155. crc32.update(bytes);
  156. LittleEndian<u32> digest = crc32.digest();
  157. LittleEndian<u32> size = bytes.size();
  158. m_output_stream << digest << size;
  159. return bytes.size();
  160. }
  161. bool GzipCompressor::write_or_error(ReadonlyBytes bytes)
  162. {
  163. if (write(bytes) < bytes.size()) {
  164. set_fatal_error();
  165. return false;
  166. }
  167. return true;
  168. }
  169. Optional<ByteBuffer> GzipCompressor::compress_all(ReadonlyBytes bytes)
  170. {
  171. DuplexMemoryStream output_stream;
  172. GzipCompressor gzip_stream { output_stream };
  173. gzip_stream.write_or_error(bytes);
  174. if (gzip_stream.handle_any_error())
  175. return {};
  176. return output_stream.copy_into_contiguous_buffer();
  177. }
  178. }