From 04efd16a838a065c8b7c405e8d2e290f1f49bbc3 Mon Sep 17 00:00:00 2001 From: Andrew Steinborn Date: Mon, 29 Jul 2019 06:04:37 -0400 Subject: [PATCH] Avoid a memory copy in creating modern-style forwarding data --- .../backend/LoginSessionHandler.java | 26 ++++++++----------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java index b2535931e..d18951369 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/LoginSessionHandler.java @@ -117,32 +117,28 @@ public class LoginSessionHandler implements MinecraftSessionHandler { private static ByteBuf createForwardingData(byte[] hmacSecret, String address, GameProfile profile) { - ByteBuf dataToForward = Unpooled.buffer(); - ByteBuf finalData = Unpooled.buffer(); + ByteBuf forwarded = Unpooled.buffer(2048); try { - ProtocolUtils.writeVarInt(dataToForward, VelocityConstants.FORWARDING_VERSION); - ProtocolUtils.writeString(dataToForward, address); - ProtocolUtils.writeUuid(dataToForward, profile.getId()); - ProtocolUtils.writeString(dataToForward, profile.getName()); - ProtocolUtils.writeProperties(dataToForward, profile.getProperties()); + ProtocolUtils.writeVarInt(forwarded, VelocityConstants.FORWARDING_VERSION); + ProtocolUtils.writeString(forwarded, address); + ProtocolUtils.writeUuid(forwarded, profile.getId()); + ProtocolUtils.writeString(forwarded, profile.getName()); + ProtocolUtils.writeProperties(forwarded, profile.getProperties()); SecretKey key = new SecretKeySpec(hmacSecret, "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(key); - mac.update(dataToForward.array(), dataToForward.arrayOffset(), dataToForward.readableBytes()); + mac.update(forwarded.array(), forwarded.arrayOffset(), forwarded.readableBytes()); byte[] sig = mac.doFinal(); - finalData.writeBytes(sig); - finalData.writeBytes(dataToForward); - return finalData; + + return Unpooled.wrappedBuffer(Unpooled.wrappedBuffer(sig), forwarded); } catch (InvalidKeyException e) { - finalData.release(); + forwarded.release(); throw new RuntimeException("Unable to authenticate data", e); } catch (NoSuchAlgorithmException e) { // Should never happen - finalData.release(); + forwarded.release(); throw new AssertionError(e); - } finally { - dataToForward.release(); } } }