diff --git a/ixwebsocket/IXGzipCodec.cpp b/ixwebsocket/IXGzipCodec.cpp index 02b3947e..fb5ebcb3 100644 --- a/ixwebsocket/IXGzipCodec.cpp +++ b/ixwebsocket/IXGzipCodec.cpp @@ -99,14 +99,15 @@ namespace ix const int kBufferSize = 1 << 14; std::array compressBuffer; + int ret; do { inflateState.avail_out = (uInt) kBufferSize; inflateState.next_out = &compressBuffer.front(); - int ret = inflate(&inflateState, Z_SYNC_FLUSH); + ret = inflate(&inflateState, Z_NO_FLUSH); - if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR) + if (ret != Z_OK && ret != Z_STREAM_END) { inflateEnd(&inflateState); return false; @@ -114,7 +115,7 @@ namespace ix out.append(reinterpret_cast(&compressBuffer.front()), kBufferSize - inflateState.avail_out); - } while (inflateState.avail_out == 0); + } while (ret != Z_STREAM_END); inflateEnd(&inflateState); return true; diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 653afdd4..9e346d3c 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -50,6 +50,7 @@ endif() if (USE_ZLIB) list(APPEND TEST_TARGET_NAMES + IXGzipCodecTest IXWebSocketPerMessageDeflateCompressorTest ) endif() diff --git a/test/IXGzipCodecTest.cpp b/test/IXGzipCodecTest.cpp new file mode 100644 index 00000000..edeefd0c --- /dev/null +++ b/test/IXGzipCodecTest.cpp @@ -0,0 +1,34 @@ +/* + * IXGzipCodecTest.cpp + * Copyright (c) 2026 Machine Zone, Inc. All rights reserved. + */ +#include +#include + +TEST_CASE("Gzip decoding requires a complete stream", "[gzip]") +{ + const std::string body = GENERATE(std::string(), std::string("hello"), std::string(32768, 'x')); + const std::string encoded = ix::gzipCompress(body); + REQUIRE_FALSE(encoded.empty()); + for (size_t length = 0; length < encoded.size(); ++length) + { + CAPTURE(length, encoded.size()); + std::string decoded; + CHECK_FALSE(ix::gzipDecompress(encoded.substr(0, length), decoded)); + } + std::string decoded; + REQUIRE(ix::gzipDecompress(encoded, decoded)); + CHECK(decoded == body); +} + +TEST_CASE("Gzip decoding checks integrity and preserves append behavior", "[gzip]") +{ + const std::string body("hello\0world", 11); + auto encoded = ix::gzipCompress(body); + std::string decoded = "prefix"; + REQUIRE(ix::gzipDecompress(encoded, decoded)); + CHECK(decoded == "prefix" + body); + encoded[encoded.size() - 8] ^= 1; + decoded.clear(); + CHECK_FALSE(ix::gzipDecompress(encoded, decoded)); +}