Gzip.cpp 8.0 KB

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