Optimise uncompression of encrypted groups with invalid keys

Creating the InputStream first allows us to immediately fail if a key is
invalid, without having the chance of allocating a huge ByteBuf based on
an incorrect length.

Signed-off-by: Graham <gpe@openrs2.org>
master
Graham 2 years ago
parent caaddad0ed
commit 26651618ef
  1. 14
      cache/src/main/kotlin/org/openrs2/cache/Js5Compression.kt

@ -147,8 +147,8 @@ public object Js5Compression {
throw IOException("Uncompressed length is negative: $uncompressedLen")
}
plaintext.alloc().buffer(uncompressedLen, uncompressedLen).use { output ->
type.createInputStream(ByteBufInputStream(plaintext, len), uncompressedLen).use { inputStream ->
plaintext.alloc().buffer(uncompressedLen, uncompressedLen).use { output ->
var remaining = uncompressedLen
while (remaining > 0) {
val n = output.writeBytes(inputStream, remaining)
@ -161,12 +161,12 @@ public object Js5Compression {
if (inputStream.read() != -1) {
throw IOException("Uncompressed data overflow")
}
}
return output.retain()
}
}
}
}
public fun uncompressUnlessEncrypted(input: ByteBuf): ByteBuf? {
return uncompressIfKeyValid(input, XteaKey.ZERO)
@ -317,6 +317,8 @@ public object Js5Compression {
val uncompressedLen = plaintext.readInt()
check(uncompressedLen >= 0)
try {
type.createInputStream(ByteBufInputStream(plaintext, len), uncompressedLen).use { inputStream ->
/**
* We don't pass uncompressedLen to the buffer here: in some cases,
* an incorrect key can produce a valid header (particularly for
@ -330,8 +332,6 @@ public object Js5Compression {
* We therefore allow the buffer to grow dynamically.
*/
plaintext.alloc().buffer().use { output ->
try {
type.createInputStream(ByteBufInputStream(plaintext, len), uncompressedLen).use { inputStream ->
var remaining = uncompressedLen
while (remaining > 0) {
val n = output.writeBytes(inputStream, remaining)
@ -346,13 +346,13 @@ public object Js5Compression {
// uncompressed data overflow
return null
}
return output.retain()
}
}
} catch (ex: IOException) {
return null
}
return output.retain()
}
}
}

Loading…
Cancel
Save