@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() <= 0) return; Packet packet = null; byte packetId = in.readByte(); if (packetId < 0) { in.clear(); throw new DecoderException("WTF, why is the packet id lower than zero?!?! Id: " + packetId); } Class<? extends Packet> clazz = PacketManager.getInstance().getPacketClass(packetId); if (clazz != null) packet = clazz.newInstance(); if (packet == null) { throw new DecoderException("Cannot find packet id: " + packetId); } packet.decode(in); out.add(packet); }
private Function convertFunction ( final int functions ) { switch ( functions ) { case 0x03 | 4: return Function.STARTDT_ACT; case 0x03 | 8: return Function.STARTDT_CONFIRM; case 0x03 | 16: return Function.STOPDT_ACT; case 0x03 | 32: return Function.STOPDT_CONFIRM; case 0x03 | 64: return Function.TESTFR_ACT; case 0x03 | 128: return Function.TESTFR_CONFIRM; default: throw new DecoderException ( String.format ( "Invalid function codes for U-format (%02x)", functions ) ); } }
/** * Read string from buffer * * @param maxLength The slots length * @return The successful */ public String readString(int maxLength) { int i = this.readVarInt(); if(i > maxLength * 4 || i < 0) { throw new DecoderException("The received encoded string buffer length is not allowed!"); } else { ByteBuf part = buf.readBytes(i); String s = part.toString(Charsets.UTF_8); if(s.length() > maxLength) { throw new DecoderException("The received string length is longer than maximum allowed (" + i + " > " + maxLength + ")"); } else { return s; } } }
/** * Decodes the fixed header. It's one byte for the flags and then variable bytes for the remaining length. * * @param buffer the buffer to decode from * @return the fixed header */ private static MqttFixedHeader decodeFixedHeader(ByteBuf buffer) { short b1 = buffer.readUnsignedByte(); MqttMessageType messageType = MqttMessageType.valueOf(b1 >> 4); boolean dupFlag = (b1 & 0x08) == 0x08; int qosLevel = (b1 & 0x06) >> 1; boolean retain = (b1 & 0x01) != 0; int remainingLength = 0; int multiplier = 1; short digit; int loops = 0; do { digit = buffer.readUnsignedByte(); remainingLength += (digit & 127) * multiplier; multiplier *= 128; loops++; } while ((digit & 128) != 0 && loops < 4); // MQTT protocol limits Remaining Length to 4 bytes if (loops == 4 && (digit & 128) != 0) { throw new DecoderException("remaining length exceeds 4 digits (" + messageType + ')'); } return new MqttFixedHeader(messageType, dupFlag, MqttQoS.valueOf(qosLevel), retain, remainingLength); }
private static Result<MqttPublishVariableHeader> decodePublishVariableHeader( ByteBuf buffer, MqttFixedHeader mqttFixedHeader) { final Result<String> decodedTopic = decodeString(buffer); if (!isValidPublishTopicName(decodedTopic.value)) { throw new DecoderException("invalid publish topic name: " + decodedTopic.value + " (contains wildcards)"); } int numberOfBytesConsumed = decodedTopic.numberOfBytesConsumed; int messageId = -1; if (mqttFixedHeader.qosLevel().value() > 0) { final Result<Integer> decodedMessageId = decodeMessageId(buffer); messageId = decodedMessageId.value; numberOfBytesConsumed += decodedMessageId.numberOfBytesConsumed; } final MqttPublishVariableHeader mqttPublishVariableHeader = new MqttPublishVariableHeader(decodedTopic.value, messageId); return new Result<MqttPublishVariableHeader>(mqttPublishVariableHeader, numberOfBytesConsumed); }
/** * Decodes the specified region of the buffer into an unadjusted frame length. The default implementation is * capable of decoding the specified region into an unsigned 8/16/24/32/64 bit integer. Override this method to * decode the length field encoded differently. Note that this method must not modify the state of the specified * buffer (e.g. {@code readerIndex}, {@code writerIndex}, and the content of the buffer.) * * @throws DecoderException * if failed to decode the specified region */ protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) { buf = buf.order(order); long frameLength; switch (length) { case 1: frameLength = buf.getUnsignedByte(offset); break; case 2: frameLength = buf.getUnsignedShort(offset); break; case 3: frameLength = buf.getUnsignedMedium(offset); break; case 4: frameLength = buf.getUnsignedInt(offset); break; case 8: frameLength = buf.getLong(offset); break; default: throw new DecoderException( "unsupported lengthFieldLength: " + lengthFieldLength + " (expected: 1, 2, 3, 4, or 8)"); } return frameLength; }
void initiateProtocolOrSsl(String username, String password, String database, Handler<? super CommandResponse<Connection>> completionHandler) { ChannelPipeline pipeline = socket.channelHandlerContext().pipeline(); if (ssl) { Future<Void> upgradeFuture = Future.future(); upgradeFuture.setHandler(ar -> { if (ar.succeeded()) { initiateProtocol(username, password, database, completionHandler); } else { Throwable cause = ar.cause(); if (cause instanceof DecoderException) { DecoderException err = (DecoderException) cause; cause = err.getCause(); } completionHandler.handle(CommandResponse.failure(cause)); } }); pipeline.addBefore("handler", "initiate-ssl-handler", new InitiateSslHandler(this, upgradeFuture)); } else { initiateProtocol(username, password, database, completionHandler); } }
public int[] readVarIntArray(int maxLength) { int i = this.readVarIntFromBuffer(); if (i > maxLength) { throw new DecoderException("VarIntArray with size " + i + " is bigger than allowed " + maxLength); } else { int[] aint = new int[i]; for (int j = 0; j < aint.length; ++j) { aint[j] = this.readVarIntFromBuffer(); } return aint; } }
public long[] readLongArray(@Nullable long[] p_189423_1_, int p_189423_2_) { int i = this.readVarIntFromBuffer(); if (p_189423_1_ == null || p_189423_1_.length != i) { if (i > p_189423_2_) { throw new DecoderException("LongArray with size " + i + " is bigger than allowed " + p_189423_2_); } p_189423_1_ = new long[i]; } for (int j = 0; j < p_189423_1_.length; ++j) { p_189423_1_[j] = this.readLong(); } return p_189423_1_; }
@Nullable public static List < EntityDataManager.DataEntry<? >> readEntries(PacketBuffer buf) throws IOException { List < EntityDataManager.DataEntry<? >> list = null; int i; while ((i = buf.readUnsignedByte()) != 255) { if (list == null) { list = Lists. < EntityDataManager.DataEntry<? >> newArrayList(); } int j = buf.readVarIntFromBuffer(); DataSerializer<?> dataserializer = DataSerializers.getSerializer(j); if (dataserializer == null) { throw new DecoderException("Unknown serializer type " + j); } list.add(new EntityDataManager.DataEntry(dataserializer.createKey(i), dataserializer.read(buf))); } return list; }
@SideOnly(Side.CLIENT) public long[] readLongArray(@Nullable long[] p_189423_1_, int p_189423_2_) { int i = this.readVarIntFromBuffer(); if (p_189423_1_ == null || p_189423_1_.length != i) { if (i > p_189423_2_) { throw new DecoderException("LongArray with size " + i + " is bigger than allowed " + p_189423_2_); } p_189423_1_ = new long[i]; } for (int j = 0; j < p_189423_1_.length; ++j) { p_189423_1_[j] = this.readLong(); } return p_189423_1_; }
public String readText(final int i) { final int j = this.readVarInt(); if (j > (i << 2)) { throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + j + " > " + (i << 2) + ")"); } if (j < 0) { throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!"); } final String s = new String(this.readBytes(j).array(), StandardCharsets.UTF_8); if (s.length() > i) { throw new DecoderException("The received string length is longer than maximum allowed (" + j + " > " + i + ")"); } return s; }
@Override protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { ByteBuf buf = (ByteBuf) super.decode(ctx, buffer); if (buf != null) { try { int pos = buf.bytesBefore((byte) config.getStartByte()); if (pos >= 0) { ByteBuf msg = buf.readerIndex(pos + 1).slice(); LOG.debug("Message ends with length {}", msg.readableBytes()); return config.isProduceString() ? asString(msg) : asByteArray(msg); } else { throw new DecoderException("Did not find start byte " + (int) config.getStartByte()); } } finally { // We need to release the buf here to avoid the memory leak buf.release(); } } // Message not complete yet - return null to be called again LOG.debug("No complete messages yet at position {}", buffer.readableBytes()); return null; }
@Override public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if(cause instanceof DecoderException && cause != null) { cause = cause.getCause(); } errorHandler.logError(cause, false); if(cause instanceof NotSslRecordException) { log.warn("Someone ({}) speaks transport plaintext instead of ssl, will close the channel", ctx.channel().remoteAddress()); ctx.channel().close(); return; } else if (cause instanceof SSLException) { log.error("SSL Problem "+cause.getMessage(),cause); ctx.channel().close(); return; } else if (cause instanceof SSLHandshakeException) { log.error("Problem during handshake "+cause.getMessage()); ctx.channel().close(); return; } super.exceptionCaught(ctx, cause); }
@Override public Message decode(CodecContext context, ByteBuffer buf) throws CodecException { int action = buf.readByte(); Vector3i position = buf.read(Types.VECTOR_3_I); int face = buf.readByte(); switch (action) { case 0: case 1: case 2: return new MessagePlayInPlayerDigging(MessagePlayInPlayerDigging.Action.values()[action], position, fromFace(face)); case 3: case 4: return new MessagePlayInDropHeldItem(action == 3); case 5: return new MessagePlayInOutFinishUsingItem(); case 6: return new MessagePlayInSwapHandItems(); default: throw new DecoderException("Unknown player digging message action: " + action); } }
@Override public Message decode(CodecContext context, ByteBuffer buf) throws CodecException { final String channel = buf.readLimitedString(LanternChannelRegistrar.MAX_NAME_LENGTH); final int length = buf.available(); if (length > Short.MAX_VALUE) { throw new DecoderException("CustomPayload messages may not be longer then " + Short.MAX_VALUE + " bytes"); } final ByteBuffer content = buf.slice(); final Message message = decode0(context, content, channel); if (content.available() > 0) { Lantern.getLogger().warn("Trailing bytes {}b after decoding with custom payload message codec {} with channel {}!\n{}", content.available(), getClass().getName(), channel, message); } // Skip all the bytes, we already processed them buf.setReadIndex(buf.readerIndex() + buf.available()); return message; }
@Override public MessagePlayInUseEntity decode(CodecContext context, ByteBuffer buf) throws CodecException { final int entityId = buf.readVarInt(); final int action = buf.readVarInt(); if (action == 1) { return new MessagePlayInUseEntity.Attack(entityId); } else if (action == 0 || action == 2) { Vector3d position = null; if (action == 2) { final double x = buf.readFloat(); final double y = buf.readFloat(); final double z = buf.readFloat(); position = new Vector3d(x, y, z); } final HandType hand = buf.readVarInt() == 0 ? HandTypes.MAIN_HAND : HandTypes.OFF_HAND; return new MessagePlayInUseEntity.Interact(entityId, hand, position); } else { throw new DecoderException("Received a UseEntity message with a unknown action: " + action); } }
@Test(expected = DecoderException.class) public void failIfv1NotSupported() { EmbeddedChannel channel = new EmbeddedChannel(new VotifierProtocolDifferentiator(true, false)); VotifierSession session = new VotifierSession(); channel.attr(VotifierSession.KEY).set(session); ByteBuf test = Unpooled.buffer(256); for (int i = 0; i < 256; i++) { test.writeByte(0); } channel.writeInbound(test); assertEquals(VotifierSession.ProtocolVersion.ONE, session.getVersion()); channel.close(); }
@Test(expected = DecoderException.class) public void testFailureDecodeBadPacket() throws Exception { // Create a well-formed request EmbeddedChannel channel = createChannel(); Vote vote = new Vote("Test", "test", "test", "0"); JSONObject object = new JSONObject(); JSONObject payload = vote.serialize(); payload.put("challenge", SESSION.getChallenge()); object.put("payload", payload.toString()); // We "forget" the signature. try { channel.writeInbound(object.toString()); } finally { channel.close(); } }
@Test(expected = DecoderException.class) public void testFailureDecodeBadVoteField() throws Exception { // Create a well-formed request EmbeddedChannel channel = createChannel(); Vote vote = new Vote("Test", "test", "test", "0"); JSONObject object = new JSONObject(); JSONObject payload = vote.serialize(); // We "forget" the challenge. object.put("payload", payload.toString()); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(TestVotifierPlugin.getI().getTokens().get("default")); object.put("signature", Base64.getEncoder().encodeToString(mac.doFinal(payload.toString().getBytes(StandardCharsets.UTF_8)))); try { channel.writeInbound(object.toString()); } finally { channel.close(); } }
@Test(expected = DecoderException.class) public void testFailureDecodeBadChallenge() throws Exception { // Create a well-formed request EmbeddedChannel channel = createChannel(); Vote vote = new Vote("Test", "test", "test", "0"); JSONObject object = new JSONObject(); JSONObject payload = vote.serialize(); // We provide the wrong challenge. payload.put("challenge", "not a challenge for me"); object.put("payload", payload.toString()); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(TestVotifierPlugin.getI().getTokens().get("default")); object.put("signature", Base64.getEncoder().encode(mac.doFinal(payload.toString().getBytes(StandardCharsets.UTF_8)))); try { channel.writeInbound(object.toString()); } finally { channel.close(); } }
@Test public void testTruncatedPacket() throws Exception { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(false); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); // Push the first part of a 5-byte handshake message. ch.writeInbound(Unpooled.wrappedBuffer(new byte[]{22, 3, 1, 0, 5})); // Should decode nothing yet. assertThat(ch.readInbound(), is(nullValue())); try { // Push the second part of the 5-byte handshake message. ch.writeInbound(Unpooled.wrappedBuffer(new byte[]{2, 0, 0, 1, 0})); fail(); } catch (DecoderException e) { // The pushed message is invalid, so it should raise an exception if it decoded the message correctly. assertThat(e.getCause(), is(instanceOf(SSLProtocolException.class))); } }
@Test public void testFailSlowTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new DelimiterBasedFrameDecoder(1, true, false, Delimiters.nulDelimiter())); for (int i = 0; i < 2; i ++) { ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 1, 2 })); try { assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0 }))); fail(DecoderException.class.getSimpleName() + " must be raised."); } catch (TooLongFrameException e) { // Expected } ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 'A', 0 })); ByteBuf buf = releaseLater((ByteBuf) ch.readInbound()); assertEquals("A", buf.toString(CharsetUtil.ISO_8859_1)); } }
@Test public void testFailFastTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new DelimiterBasedFrameDecoder(1, Delimiters.nulDelimiter())); for (int i = 0; i < 2; i ++) { try { assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 1, 2 }))); fail(DecoderException.class.getSimpleName() + " must be raised."); } catch (TooLongFrameException e) { // Expected } ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 'A', 0 })); ByteBuf buf = releaseLater((ByteBuf) ch.readInbound()); assertEquals("A", buf.toString(CharsetUtil.ISO_8859_1)); } }
@Test public void testFailSlowTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new LengthFieldBasedFrameDecoder(5, 0, 4, 0, 4, false)); for (int i = 0; i < 2; i ++) { assertFalse(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0, 0, 2 }))); try { assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0 }))); fail(DecoderException.class.getSimpleName() + " must be raised."); } catch (TooLongFrameException e) { // Expected } ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0, 0, 1, 'A' })); ByteBuf buf = releaseLater((ByteBuf) ch.readInbound()); assertEquals("A", buf.toString(CharsetUtil.ISO_8859_1)); buf.release(); } }
@Test public void testFailFastTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new LengthFieldBasedFrameDecoder(5, 0, 4, 0, 4)); for (int i = 0; i < 2; i ++) { try { assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0, 0, 2 }))); fail(DecoderException.class.getSimpleName() + " must be raised."); } catch (TooLongFrameException e) { // Expected } ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0, 0, 0, 0, 1, 'A' })); ByteBuf buf = releaseLater((ByteBuf) ch.readInbound()); assertEquals("A", buf.toString(CharsetUtil.ISO_8859_1)); buf.release(); } }
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> packets) throws Exception { if (!buf.isReadable()) { return; } buf.markReaderIndex(); ReadableMiddlePacket transformer = registry.getTransformer(Protocol.GAME, buf.readUnsignedByte(), false); if (transformer != null) { transformer.read(buf); if (buf.isReadable()) { throw new DecoderException("Did not read all data from packet " + transformer.getClass().getName() + ", bytes left: " + buf.readableBytes()); } packets.addAll(transformer.toNative()); } else { buf.resetReaderIndex(); packets.add(new PacketWrapper(null, buf.copy())); } }
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> packets) throws Exception { if (!buf.isReadable()) { return; } buf.markReaderIndex(); ReadableMiddlePacket transformer = registry.getTransformer(Protocol.GAME, readPacketId(buf), false); if (transformer == null) { buf.resetReaderIndex(); packets.add(new PacketWrapper(null, buf.copy())); } else { transformer.read(buf); if (buf.isReadable()) { throw new DecoderException("Did not read all data from packet " + transformer.getClass().getName() + ", bytes left: " + buf.readableBytes()); } packets.addAll(transformer.toNative()); } }
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> packets) throws Exception { if (!buf.isReadable()) { return; } buf.markReaderIndex(); ReadableMiddlePacket transformer = registry.getTransformer(protocol, readPacketId(buf), false); if (transformer == null) { buf.resetReaderIndex(); packets.add(new PacketWrapper(null, buf.copy())); } else { transformer.read(buf); if (buf.isReadable()) { throw new DecoderException("Did not read all data from packet " + transformer.getClass().getName() + ", bytes left: " + buf.readableBytes()); } packets.addAll(transformer.toNative()); } }
public static EncapsulatedProtocolInfo readInfo(ByteBuf from) { int encapVersion = VarNumberSerializer.readVarInt(from); if (encapVersion > CURRENT_VERSION) { throw new DecoderException(MessageFormat.format("Unsupported encapsulation protocol verrsion {}", encapVersion)); } InetSocketAddress remoteaddress = null; if (from.readBoolean()) { try { InetAddress address = InetAddress.getByAddress(MiscSerializer.readBytes(from, VarNumberSerializer.readVarInt(from))); remoteaddress = new InetSocketAddress(address, VarNumberSerializer.readVarInt(from)); } catch (UnknownHostException e) { throw new DecoderException("Invalid ip address"); } } boolean hasCompression = from.readBoolean(); if (encapVersion == 0) { VarNumberSerializer.readVarInt(from); VarNumberSerializer.readVarInt(from); } return new EncapsulatedProtocolInfo(remoteaddress, hasCompression); }
private static Any<Key, JsonObject> extractChainData(Map<String, List<String>> maindata) throws ParseException { List<String> chain = maindata.get("chain"); try { PublicKey key = parseKey(MOJANG_KEY); boolean foundMojangKey = false; boolean signatureValid = false; for (String element : chain) { JWSObject jwsobject = JWSObject.parse(element); if (!foundMojangKey && jwsobject.getHeader().getX509CertURL().toString().equals(MOJANG_KEY)) { foundMojangKey = true; signatureValid = true; } if (foundMojangKey && !verify(jwsobject, key)) { signatureValid = false; } JsonObject jsonobject = Utils.GSON.fromJson(jwsobject.getPayload().toString(), JsonObject.class); key = parseKey(JsonUtils.getString(jsonobject, "identityPublicKey")); if (jsonobject.has("extraData")) { return new Any<Key, JsonObject>(signatureValid ? key : null, JsonUtils.getJsonObject(jsonobject, "extraData")); } } } catch (InvalidKeySpecException | JOSEException e) { throw new DecoderException("Unable to decode login chain", e); } throw new DecoderException("Unable to find extraData"); }
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> list) throws Exception { try { inflater.setInput(MiscSerializer.readAllBytes(buf)); int decompressedlength = inflater.inflate(decompressionbuffer); if (!inflater.finished()) { throw new DecoderException(MessageFormat.format("Badly compressed packet - size is larger than protocol maximum of {0}", maxPacketLength)); } ByteBuf uncompresseddata = Unpooled.wrappedBuffer(decompressionbuffer, 0, decompressedlength); while (uncompresseddata.isReadable()) { list.add(Unpooled.wrappedBuffer(MiscSerializer.readBytes(uncompresseddata, VarNumberSerializer.readVarInt(uncompresseddata)))); } } finally { inflater.reset(); } }
@Override protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> out) throws Exception { buffer.markReaderIndex(); try { final String command = nextString(buffer); // Extract event type switch (command) { case "LOG": decodeLogEvent(context, buffer, out); break; default: throw new IllegalStateException("Unknown command " + command); } } catch (Exception e) { buffer.resetReaderIndex(); throw new DecoderException("Invalid line event: " + buffer.toString(StandardCharsets.UTF_8), e); } }
@Override public void decodeResponseData(ByteBuf data, ModbusResponse response) { if (data.readableBytes() < getResponseDataLength()) { throw new DecoderException(); } ReadWordRegistersResponse readWordRegistersResponse = (ReadWordRegistersResponse) response; readWordRegistersResponse.setStartingAddress(startingAddress); int dataContentBytes = data.readUnsignedByte(); if (dataContentBytes != getResponseDataLength() - 1) { throw new DecoderException(); } readWordRegistersResponse.setQuantityAndAllocate(quantity); for (int i = 0; i < quantity; i++) { readWordRegistersResponse.setValue(i, data.readUnsignedShort()); } }
public static ListIdentity decode(ByteBuf buffer) { if (buffer.readableBytes() > 0) { CpfPacket packet = CpfPacket.decode(buffer); CpfItem[] items = packet.getItems(); if (items.length > 0) { if (items[0] instanceof CipIdentityItem) { return new ListIdentity((CipIdentityItem) items[0]); } else { throw new DecoderException( String.format("expected CipIdentityItem; received %s instead", items[0].getClass().getSimpleName())); } } else { return new ListIdentity(); } } return new ListIdentity(); }