From: Robert Varga Date: Thu, 28 Jul 2022 18:15:30 +0000 (+0200) Subject: Use strict String->byte[] conversion X-Git-Tag: v4.0.0~9 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=netconf.git;a=commitdiff_plain;h=44926051c90f28ca6d6015ff57f5a4cbf9f716d4 Use strict String->byte[] conversion Improve defensiveness around constant encoding: the strings are expected to be be ASCII-only, so enforce that by using a properly-configured coder. Change-Id: I991640d6ad6e4c928b64fdabcbe7f0b60418c7af Signed-off-by: Robert Varga --- diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java index a077671c7f..fb21b7f8c2 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java @@ -7,8 +7,11 @@ */ package org.opendaylight.netconf.nettyutil.handler; -import static java.nio.charset.StandardCharsets.UTF_8; - +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; import org.opendaylight.netconf.util.messages.NetconfMessageConstants; /** @@ -17,11 +20,27 @@ import org.opendaylight.netconf.util.messages.NetconfMessageConstants; * @author Thomas Pantelis */ final class MessageParts { - static final byte[] END_OF_MESSAGE = NetconfMessageConstants.END_OF_MESSAGE.getBytes(UTF_8); - static final byte[] START_OF_CHUNK = NetconfMessageConstants.START_OF_CHUNK.getBytes(UTF_8); - static final byte[] END_OF_CHUNK = NetconfMessageConstants.END_OF_CHUNK.getBytes(UTF_8); + static final byte[] END_OF_MESSAGE = asciiBytes(NetconfMessageConstants.END_OF_MESSAGE); + static final byte[] START_OF_CHUNK = asciiBytes(NetconfMessageConstants.START_OF_CHUNK); + static final byte[] END_OF_CHUNK = asciiBytes(NetconfMessageConstants.END_OF_CHUNK); private MessageParts() { // Hidden on purpose } + + private static byte[] asciiBytes(final String str) { + final ByteBuffer buf; + try { + buf = StandardCharsets.US_ASCII.newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(str)); + } catch (CharacterCodingException e) { + throw new ExceptionInInitializerError(e); + } + + final byte[] ret = new byte[buf.remaining()]; + buf.get(ret); + return ret; + } }