Gzip.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. size_t nread = current_member().m_stream.read(slice);
  50. current_member().m_checksum.update(slice.trim(nread));
  51. current_member().m_nread += nread;
  52. if (current_member().m_stream.handle_any_error())
  53. return Error::from_string_literal("Underlying DeflateDecompressor indicated an error");
  54. if (nread < slice.size()) {
  55. LittleEndian<u32> crc32, input_size;
  56. TRY(m_input_stream->read(crc32.bytes()));
  57. TRY(m_input_stream->read(input_size.bytes()));
  58. if (crc32 != current_member().m_checksum.digest())
  59. return Error::from_string_literal("Stored CRC32 does not match the calculated CRC32 of the current member");
  60. if (input_size != current_member().m_nread)
  61. return Error::from_string_literal("Input size does not match the number of read bytes");
  62. m_current_member.clear();
  63. total_read += nread;
  64. continue;
  65. }
  66. total_read += nread;
  67. continue;
  68. } else {
  69. auto current_partial_header_slice = Bytes { m_partial_header, sizeof(BlockHeader) }.slice(m_partial_header_offset);
  70. auto current_partial_header_data = TRY(m_input_stream->read(current_partial_header_slice));
  71. m_partial_header_offset += current_partial_header_data.size();
  72. if (is_eof())
  73. break;
  74. if (m_partial_header_offset < sizeof(BlockHeader)) {
  75. break; // partial header read
  76. }
  77. m_partial_header_offset = 0;
  78. BlockHeader header = *(reinterpret_cast<BlockHeader*>(m_partial_header));
  79. if (!header.valid_magic_number())
  80. return Error::from_string_literal("Header does not have a valid magic number");
  81. if (!header.supported_by_implementation())
  82. return Error::from_string_literal("Header is not supported by implementation");
  83. if (header.flags & Flags::FEXTRA) {
  84. LittleEndian<u16> subfield_id, length;
  85. TRY(m_input_stream->read(subfield_id.bytes()));
  86. TRY(m_input_stream->read(length.bytes()));
  87. TRY(m_input_stream->discard(length));
  88. }
  89. auto discard_string = [&]() -> ErrorOr<void> {
  90. char next_char;
  91. do {
  92. TRY(m_input_stream->read({ &next_char, sizeof(next_char) }));
  93. } while (next_char);
  94. return {};
  95. };
  96. if (header.flags & Flags::FNAME)
  97. TRY(discard_string());
  98. if (header.flags & Flags::FCOMMENT)
  99. TRY(discard_string());
  100. if (header.flags & Flags::FHCRC) {
  101. LittleEndian<u16> crc16;
  102. TRY(m_input_stream->read(crc16.bytes()));
  103. // FIXME: we should probably verify this instead of just assuming it matches
  104. }
  105. m_current_member.emplace(header, *m_input_stream);
  106. continue;
  107. }
  108. }
  109. return bytes.slice(0, total_read);
  110. }
  111. Optional<DeprecatedString> GzipDecompressor::describe_header(ReadonlyBytes bytes)
  112. {
  113. if (bytes.size() < sizeof(BlockHeader))
  114. return {};
  115. auto& header = *(reinterpret_cast<BlockHeader const*>(bytes.data()));
  116. if (!header.valid_magic_number() || !header.supported_by_implementation())
  117. return {};
  118. LittleEndian<u32> original_size = *reinterpret_cast<u32 const*>(bytes.offset(bytes.size() - sizeof(u32)));
  119. return DeprecatedString::formatted("last modified: {}, original size {}", Core::DateTime::from_timestamp(header.modification_time).to_deprecated_string(), (u32)original_size);
  120. }
  121. ErrorOr<ByteBuffer> GzipDecompressor::decompress_all(ReadonlyBytes bytes)
  122. {
  123. auto memory_stream = TRY(Core::Stream::MemoryStream::construct(bytes));
  124. auto gzip_stream = make<GzipDecompressor>(move(memory_stream));
  125. DuplexMemoryStream output_stream;
  126. auto buffer = TRY(ByteBuffer::create_uninitialized(4096));
  127. while (!gzip_stream->is_eof()) {
  128. auto const data = TRY(gzip_stream->read(buffer));
  129. output_stream.write_or_error(data);
  130. }
  131. return output_stream.copy_into_contiguous_buffer();
  132. }
  133. bool GzipDecompressor::is_eof() const { return m_input_stream->is_eof(); }
  134. ErrorOr<size_t> GzipDecompressor::write(ReadonlyBytes)
  135. {
  136. VERIFY_NOT_REACHED();
  137. }
  138. GzipCompressor::GzipCompressor(OutputStream& stream)
  139. : m_output_stream(stream)
  140. {
  141. }
  142. size_t GzipCompressor::write(ReadonlyBytes bytes)
  143. {
  144. BlockHeader header;
  145. header.identification_1 = 0x1f;
  146. header.identification_2 = 0x8b;
  147. header.compression_method = 0x08;
  148. header.flags = 0;
  149. header.modification_time = 0;
  150. header.extra_flags = 3; // DEFLATE sets 2 for maximum compression and 4 for minimum compression
  151. header.operating_system = 3; // unix
  152. m_output_stream << Bytes { &header, sizeof(header) };
  153. DeflateCompressor compressed_stream { m_output_stream };
  154. VERIFY(compressed_stream.write_or_error(bytes));
  155. compressed_stream.final_flush();
  156. Crypto::Checksum::CRC32 crc32;
  157. crc32.update(bytes);
  158. LittleEndian<u32> digest = crc32.digest();
  159. LittleEndian<u32> size = bytes.size();
  160. m_output_stream << digest << size;
  161. return bytes.size();
  162. }
  163. bool GzipCompressor::write_or_error(ReadonlyBytes bytes)
  164. {
  165. if (write(bytes) < bytes.size()) {
  166. set_fatal_error();
  167. return false;
  168. }
  169. return true;
  170. }
  171. Optional<ByteBuffer> GzipCompressor::compress_all(ReadonlyBytes bytes)
  172. {
  173. DuplexMemoryStream output_stream;
  174. GzipCompressor gzip_stream { output_stream };
  175. gzip_stream.write_or_error(bytes);
  176. if (gzip_stream.handle_any_error())
  177. return {};
  178. return output_stream.copy_into_contiguous_buffer();
  179. }
  180. }