Backport #177 to 1.9 (#179)

Motivation

Currently we don't confirm that the decompression has completed
successfully. This means that we can incorrectly spin forever attempting
to decompress past the end of a message, and that we can fail to notice
that a message is truncated. Neither of these is good.

Modifications

Propagate the message zlib gives us as to whether or not decompression
is done, and keep track of it.
Add some tests written by @vojtarylko to validate the behaviour.

Result

Correctly police the bounds of the messages.
This commit is contained in:
Cory Benfield authored and GitHub committed 2022-09-16 09:30:05 +01:00
1 parent 29e4c0a2b4
commit e8000754be
7 files changed
+137 -14

No files matched your search

@@ -29,10 +29,12 @@ public final class NIOHTTPRequestDecompressor: ChannelDuplexHandler, RemovableCh
private var decompressor: NIOHTTPDecompression.Decompressor
private var compression: Compression?
private var decompressionComplete: Bool
public init(limit: NIOHTTPDecompression.DecompressionLimit) {
self.decompressor = NIOHTTPDecompression.Decompressor(limit: limit)
self.compression = nil
self.decompressionComplete = false
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
@@ -61,10 +63,13 @@ public final class NIOHTTPRequestDecompressor: ChannelDuplexHandler, RemovableCh
return
}
while part.readableBytes > 0 {
while part.readableBytes > 0 && !self.decompressionComplete {
do {
var buffer = context.channel.allocator.buffer(capacity: 16384)
try self.decompressor.decompress(part: &part, buffer: &buffer, compressedLength: compression.contentLength)
let result = try self.decompressor.decompress(part: &part, buffer: &buffer, compressedLength: compression.contentLength)
if result.complete {
self.decompressionComplete = true
}
context.fireChannelRead(self.wrapInboundOut(.body(buffer)))
} catch let error {
@@ -72,10 +77,21 @@ public final class NIOHTTPRequestDecompressor: ChannelDuplexHandler, RemovableCh
return
}
}
if part.readableBytes > 0 {
context.fireErrorCaught(NIOHTTPDecompression.ExtraDecompressionError.invalidTrailingData)
}
case .end:
if self.compression != nil {
let wasDecompressionComplete = self.decompressionComplete
self.decompressor.deinitializeDecoder()
self.compression = nil
self.decompressionComplete = false
if !wasDecompressionComplete {
context.fireErrorCaught(NIOHTTPDecompression.ExtraDecompressionError.truncatedData)
}
}
context.fireChannelRead(data)