Release the temporary ByteBuf in case of unexpected exception in WebSocketUtil.base64. (#10160)

Motivation:

An exception may occur between ByteBuf's allocation and release. So I think it's a good idea to place the release operation in a finally block.

Modification:

Release the temporary ByteBuf in finally blocks.

Result:

Avoid ByteBuf leak.
This commit is contained in:
feijermu 2020-04-03 20:49:40 +08:00 committed by GitHub
parent c90acf4766
commit bdaa935756
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 3 deletions

View File

@ -96,10 +96,18 @@ final class WebSocketUtil {
if (PlatformDependent.javaVersion() >= 8) {
return java.util.Base64.getEncoder().encodeToString(data);
}
String encodedString;
ByteBuf encodedData = Unpooled.wrappedBuffer(data);
ByteBuf encoded = Base64.encode(encodedData);
String encodedString = encoded.toString(CharsetUtil.UTF_8);
encoded.release();
try {
ByteBuf encoded = Base64.encode(encodedData);
try {
encodedString = encoded.toString(CharsetUtil.UTF_8);
} finally {
encoded.release();
}
} finally {
encodedData.release();
}
return encodedString;
}

View File

@ -17,6 +17,15 @@ package io.netty.handler.codec.http.websocketx;
import org.junit.Test;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.base64.Base64;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.EmptyArrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class WebSocketUtilTest {
@ -40,4 +49,26 @@ public class WebSocketUtilTest {
}
}
@Test
public void testBase64() {
String base64 = WebSocketUtil.base64(EmptyArrays.EMPTY_BYTES);
assertNotNull(base64);
assertTrue(base64.isEmpty());
base64 = WebSocketUtil.base64("foo".getBytes(CharsetUtil.UTF_8));
assertEquals(base64, "Zm9v");
base64 = WebSocketUtil.base64("bar".getBytes(CharsetUtil.UTF_8));
ByteBuf src = Unpooled.wrappedBuffer(base64.getBytes(CharsetUtil.UTF_8));
try {
ByteBuf dst = Base64.decode(src);
try {
assertEquals(new String(ByteBufUtil.getBytes(dst), CharsetUtil.UTF_8), "bar");
} finally {
dst.release();
}
} finally {
src.release();
}
}
}