List of usage examples for io.netty.handler.codec CorruptedFrameException CorruptedFrameException
public CorruptedFrameException(Throwable cause)
From source file:com.cc.nettytest.proxy.decoder.CCLengthFieldBasedFrameDecoder.java
License:Apache License
@Override public Object decode(ChannelHandlerContext ctx, ByteBuf inBuffer) throws Exception { if (discardingTooLongFrame) { long bytesToDiscard = this.bytesToDiscard; int localBytesToDiscard = (int) Math.min(bytesToDiscard, inBuffer.readableBytes()); inBuffer.skipBytes(localBytesToDiscard); bytesToDiscard -= localBytesToDiscard; this.bytesToDiscard = bytesToDiscard; failIfNecessary(ctx, false);//from ww w.j av a2 s . c o m return null; } if (inBuffer.readableBytes() < lengthFieldEndOffset) { return null; } int actualLengthFieldOffset = inBuffer.readerIndex() + lengthFieldOffset; long frameLength; switch (lengthFieldLength) { case 1: frameLength = inBuffer.getUnsignedByte(actualLengthFieldOffset); break; case 2: frameLength = inBuffer.getUnsignedShort(actualLengthFieldOffset); break; case 3: frameLength = inBuffer.getUnsignedMedium(actualLengthFieldOffset); break; case 4: frameLength = ByteBufUtil.swapInt((int) inBuffer.getUnsignedInt(actualLengthFieldOffset)); //SWAP FOR UIMANAGER break; case 8: frameLength = inBuffer.getLong(actualLengthFieldOffset); break; default: throw new Error("should not reach here"); } if (frameLength < 0) { inBuffer.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength); } frameLength += lengthAdjustment + lengthFieldEndOffset; if (frameLength < lengthFieldEndOffset) { inBuffer.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less " + "than lengthFieldEndOffset: " + lengthFieldEndOffset); } if (frameLength > maxFrameLength) { // Enter the discard mode and discard everything received so far. discardingTooLongFrame = true; tooLongFrameLength = frameLength; bytesToDiscard = frameLength - inBuffer.readableBytes(); inBuffer.skipBytes(inBuffer.readableBytes()); failIfNecessary(ctx, true); return null; } // never overflows because it's less than maxFrameLength int frameLengthInt = (int) frameLength; if (inBuffer.readableBytes() < frameLengthInt) { return null; } if (initialBytesToStrip > frameLengthInt) { inBuffer.skipBytes(frameLengthInt); throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less " + "than initialBytesToStrip: " + initialBytesToStrip); } inBuffer.skipBytes(initialBytesToStrip); // extract frame int readerIndex = inBuffer.readerIndex(); int actualFrameLength = frameLengthInt - initialBytesToStrip; ByteBuf frame = extractFrame(inBuffer, readerIndex, actualFrameLength); inBuffer.readerIndex(readerIndex + actualFrameLength); return frame; }
From source file:com.chat.common.netty.handler.decode.LengthFieldBasedFrameDecoder.java
License:Apache License
/** * Create a frame out of the {@link ByteBuf} and return it. * * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to * @param in the {@link ByteBuf} from which to read data * @return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could * be created.// ww w.j a va 2s. c om */ protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { if (discardingTooLongFrame) { long bytesToDiscard = this.bytesToDiscard; int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes()); in.skipBytes(localBytesToDiscard); bytesToDiscard -= localBytesToDiscard; this.bytesToDiscard = bytesToDiscard; failIfNecessary(false); } if (in.readableBytes() < lengthFieldEndOffset) { return null; } int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset; long frameLength = getUnadjustedFrameLength(in, actualLengthFieldOffset, lengthFieldLength, byteOrder); if (frameLength < 0) { in.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength); } frameLength += lengthAdjustment + lengthFieldEndOffset; if (frameLength < lengthFieldEndOffset) { in.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less " + "than lengthFieldEndOffset: " + lengthFieldEndOffset); } if (frameLength > maxFrameLength) { long discard = frameLength - in.readableBytes(); tooLongFrameLength = frameLength; if (discard < 0) { // buffer contains more bytes then the frameLength so we can discard all now in.skipBytes((int) frameLength); } else { // Enter the discard mode and discard everything received so far. discardingTooLongFrame = true; bytesToDiscard = discard; in.skipBytes(in.readableBytes()); } failIfNecessary(true); return null; } // never overflows because it's less than maxFrameLength int frameLengthInt = (int) frameLength; if (in.readableBytes() < frameLengthInt) { return null; } if (initialBytesToStrip > frameLengthInt) { in.skipBytes(frameLengthInt); throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less " + "than initialBytesToStrip: " + initialBytesToStrip); } in.skipBytes(initialBytesToStrip); // extract frame int readerIndex = in.readerIndex(); int actualFrameLength = frameLengthInt - initialBytesToStrip; ByteBuf frame = extractFrame(ctx, in, readerIndex, actualFrameLength); in.readerIndex(readerIndex + actualFrameLength); return frame; }
From source file:com.chat.common.netty.handler.decode.ProtobufVarint32FrameDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { in.markReaderIndex();//from w ww. ja v a2 s. com int preIndex = in.readerIndex(); int length = readRawVarint32(in); if (preIndex == in.readerIndex()) { return; } if (length < 0) { throw new CorruptedFrameException("negative length: " + length); } if (in.readableBytes() < length) { in.resetReaderIndex(); } else { out.add(in.readRetainedSlice(length)); } }
From source file:com.chat.common.netty.handler.decode.ProtobufVarint32FrameDecoder.java
License:Apache License
/** * Reads variable length 32bit int from buffer * * @return decoded int if buffers readerIndex has been forwarded else nonsense value *//*from w ww .j a v a 2s. co m*/ private static int readRawVarint32(ByteBuf buffer) { if (!buffer.isReadable()) { return 0; } buffer.markReaderIndex(); byte tmp = buffer.readByte(); if (tmp >= 0) { return tmp; } else { int result = tmp & 127; if (!buffer.isReadable()) { buffer.resetReaderIndex(); return 0; } if ((tmp = buffer.readByte()) >= 0) { result |= tmp << 7; } else { result |= (tmp & 127) << 7; if (!buffer.isReadable()) { buffer.resetReaderIndex(); return 0; } if ((tmp = buffer.readByte()) >= 0) { result |= tmp << 14; } else { result |= (tmp & 127) << 14; if (!buffer.isReadable()) { buffer.resetReaderIndex(); return 0; } if ((tmp = buffer.readByte()) >= 0) { result |= tmp << 21; } else { result |= (tmp & 127) << 21; if (!buffer.isReadable()) { buffer.resetReaderIndex(); return 0; } result |= (tmp = buffer.readByte()) << 28; if (tmp < 0) { throw new CorruptedFrameException("malformed varint."); } } } } return result; } }
From source file:com.dempe.chat.common.mqtt.codec.ConnectDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException { in.resetReaderIndex();/*from ww w. j a v a 2s .c o m*/ //Common decoding part ConnectMessage message = new ConnectMessage(); if (!decodeCommonHeader(message, 0x00, in)) { in.resetReaderIndex(); return; } int remainingLength = message.getRemainingLength(); int start = in.readerIndex(); int protocolNameLen = in.readUnsignedShort(); byte[] encProtoName; String protoName; Attribute<Integer> versionAttr = ctx.attr(MQTTDecoder.PROTOCOL_VERSION); switch (protocolNameLen) { case 6: //MQTT version 3.1 "MQIsdp" //ProtocolName 8 bytes or 6 bytes if (in.readableBytes() < 10) { in.resetReaderIndex(); return; } encProtoName = new byte[6]; in.readBytes(encProtoName); protoName = new String(encProtoName, "UTF-8"); if (!"MQIsdp".equals(protoName)) { in.resetReaderIndex(); throw new CorruptedFrameException("Invalid protoName: " + protoName); } message.setProtocolName(protoName); versionAttr.set((int) Utils.VERSION_3_1); break; case 4: //MQTT version 3.1.1 "MQTT" //ProtocolName 6 bytes if (in.readableBytes() < 8) { in.resetReaderIndex(); return; } encProtoName = new byte[4]; in.readBytes(encProtoName); protoName = new String(encProtoName, "UTF-8"); if (!"MQTT".equals(protoName)) { in.resetReaderIndex(); throw new CorruptedFrameException("Invalid protoName: " + protoName); } message.setProtocolName(protoName); versionAttr.set((int) Utils.VERSION_3_1_1); break; default: //protocol broken throw new CorruptedFrameException("Invalid protoName size: " + protocolNameLen); } //ProtocolVersion 1 byte (value 0x03 for 3.1, 0x04 for 3.1.1) message.setProtocolVersion(in.readByte()); if (message.getProtocolVersion() == Utils.VERSION_3_1_1) { //if 3.1.1, check the flags (dup, retain and qos == 0) if (message.isDupFlag() || message.isRetainFlag() || message.getQos() != AbstractMessage.QOSType.MOST_ONE) { throw new CorruptedFrameException("Received a CONNECT with fixed header flags != 0"); } //check if this is another connect from the same client on the same session Attribute<Boolean> connectAttr = ctx.attr(ConnectDecoder.CONNECT_STATUS); Boolean alreadyConnected = connectAttr.get(); if (alreadyConnected == null) { //never set connectAttr.set(true); } else if (alreadyConnected) { throw new CorruptedFrameException("Received a second CONNECT on the same network connection"); } } //Connection flag byte connFlags = in.readByte(); if (message.getProtocolVersion() == Utils.VERSION_3_1_1) { if ((connFlags & 0x01) != 0) { //bit(0) of connection flags is != 0 throw new CorruptedFrameException("Received a CONNECT with connectionFlags[0(bit)] != 0"); } } boolean cleanSession = ((connFlags & 0x02) >> 1) == 1; boolean willFlag = ((connFlags & 0x04) >> 2) == 1; byte willQos = (byte) ((connFlags & 0x18) >> 3); if (willQos > 2) { in.resetReaderIndex(); throw new CorruptedFrameException("Expected will QoS in range 0..2 but found: " + willQos); } boolean willRetain = ((connFlags & 0x20) >> 5) == 1; boolean passwordFlag = ((connFlags & 0x40) >> 6) == 1; boolean userFlag = ((connFlags & 0x80) >> 7) == 1; //a password is true iff user is true. if (!userFlag && passwordFlag) { in.resetReaderIndex(); throw new CorruptedFrameException( "Expected password flag to true if the user flag is true but was: " + passwordFlag); } message.setCleanSession(cleanSession); message.setWillFlag(willFlag); message.setWillQos(willQos); message.setWillRetain(willRetain); message.setPasswordFlag(passwordFlag); message.setUserFlag(userFlag); //Keep Alive timer 2 bytes //int keepAlive = Utils.readWord(in); int keepAlive = in.readUnsignedShort(); message.setKeepAlive(keepAlive); if ((remainingLength == 12 && message.getProtocolVersion() == Utils.VERSION_3_1) || (remainingLength == 10 && message.getProtocolVersion() == Utils.VERSION_3_1_1)) { out.add(message); return; } //Decode the ClientID String clientID = Utils.decodeString(in); if (clientID == null) { in.resetReaderIndex(); return; } message.setClientID(clientID); //Decode willTopic if (willFlag) { String willTopic = Utils.decodeString(in); if (willTopic == null) { in.resetReaderIndex(); return; } message.setWillTopic(willTopic); } //Decode willMessage if (willFlag) { byte[] willMessage = Utils.readFixedLengthContent(in); if (willMessage == null) { in.resetReaderIndex(); return; } message.setWillMessage(willMessage); } //Compatibility check with v3.0, remaining length has precedence over //the user and password flags int readed = in.readerIndex() - start; if (readed == remainingLength) { out.add(message); return; } //Decode username if (userFlag) { String userName = Utils.decodeString(in); if (userName == null) { in.resetReaderIndex(); return; } message.setUsername(userName); } readed = in.readerIndex() - start; if (readed == remainingLength) { out.add(message); return; } //Decode password if (passwordFlag) { byte[] password = Utils.readFixedLengthContent(in); if (password == null) { in.resetReaderIndex(); return; } message.setPassword(password); } out.add(message); }
From source file:com.dempe.chat.common.mqtt.codec.DemuxDecoder.java
License:Open Source License
private boolean genericDecodeCommonHeader(AbstractMessage message, Integer expectedFlagsOpt, ByteBuf in) { //Common decoding part if (in.readableBytes() < 2) { return false; }//w w w . j a va 2 s . co m byte h1 = in.readByte(); byte messageType = (byte) ((h1 & 0x00F0) >> 4); byte flags = (byte) (h1 & 0x0F); if (expectedFlagsOpt != null) { int expectedFlags = expectedFlagsOpt; if ((byte) expectedFlags != flags) { String hexExpected = Integer.toHexString(expectedFlags); String hexReceived = Integer.toHexString(flags); throw new CorruptedFrameException( String.format("Received a message with fixed header flags (%s) != expected (%s)", hexReceived, hexExpected)); } } boolean dupFlag = ((byte) ((h1 & 0x0008) >> 3) == 1); byte qosLevel = (byte) ((h1 & 0x0006) >> 1); boolean retainFlag = ((byte) (h1 & 0x0001) == 1); int remainingLength = Utils.decodeRemainingLenght(in); if (remainingLength == -1) { return false; } message.setMessageType(messageType); message.setDupFlag(dupFlag); try { message.setQos(AbstractMessage.QOSType.valueOf(qosLevel)); } catch (IllegalArgumentException e) { throw new CorruptedFrameException(String.format("Received an invalid QOS: %s", e.getMessage()), e); } message.setRetainFlag(retainFlag); message.setRemainingLength(remainingLength); return true; }
From source file:com.dempe.chat.common.mqtt.codec.MQTTDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { in.markReaderIndex();/*from w w w .j a va 2 s.c om*/ if (!Utils.checkHeaderAvailability(in)) { in.resetReaderIndex(); return; } in.resetReaderIndex(); byte messageType = Utils.readMessageType(in); DemuxDecoder decoder = m_decoderMap.get(messageType); if (decoder == null) { throw new CorruptedFrameException("Can't find any suitable decoder for message type: " + messageType); } decoder.decode(ctx, in, out); }
From source file:com.dempe.chat.common.mqtt.codec.MQTTEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext chc, AbstractMessage msg, ByteBuf bb) throws Exception { DemuxEncoder encoder = m_encoderMap.get(msg.getMessageType()); if (encoder == null) { throw new CorruptedFrameException( "Can't find any suitable decoder for message type: " + msg.getMessageType()); }/*from w ww . j ava 2 s .c om*/ encoder.encode(chc, msg, bb); }
From source file:com.dempe.chat.common.mqtt.codec.PublishDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { LOG.debug("decode invoked with buffer {}", in); in.resetReaderIndex();/*from www.j a va 2s.c o m*/ int startPos = in.readerIndex(); //Common decoding part PublishMessage message = new PublishMessage(); if (!decodeCommonHeader(message, in)) { LOG.debug("decode ask for more data after {}", in); in.resetReaderIndex(); return; } if (Utils.isMQTT3_1_1(ctx)) { if (message.getQos() == AbstractMessage.QOSType.MOST_ONE && message.isDupFlag()) { //bad protocol, if QoS=0 => DUP = 0 throw new CorruptedFrameException("Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation"); } if (message.getQos() == AbstractMessage.QOSType.RESERVED) { throw new CorruptedFrameException( "Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation"); } } int remainingLength = message.getRemainingLength(); //Topic name String topic = Utils.decodeString(in); if (topic == null) { in.resetReaderIndex(); return; } //[MQTT-3.3.2-2] The Topic Name in the PUBLISH Packet MUST NOT contain wildcard characters. if (topic.contains("+") || topic.contains("#")) { throw new CorruptedFrameException( "Received a PUBLISH with topic containing wild card chars, topic: " + topic); } //check topic is at least one char [MQTT-4.7.3-1] if (topic.length() == 0) { throw new CorruptedFrameException("Received a PUBLISH with topic without any character"); } message.setTopicName(topic); if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) { message.setMessageID(in.readUnsignedShort()); } int stopPos = in.readerIndex(); //read the payload int payloadSize = remainingLength - (stopPos - startPos - 2) + (Utils.numBytesToEncode(remainingLength) - 1); if (in.readableBytes() < payloadSize) { in.resetReaderIndex(); return; } ByteBuf bb = Unpooled.buffer(payloadSize); in.readBytes(bb); message.setPayload(bb.nioBuffer()); out.add(message); }
From source file:com.dempe.chat.common.mqtt.codec.SubscribeDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { //Common decoding part SubscribeMessage message = new SubscribeMessage(); in.resetReaderIndex();// w w w.jav a2 s .co m if (!decodeCommonHeader(message, 0x02, in)) { in.resetReaderIndex(); return; } //check qos level if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) { throw new CorruptedFrameException( "Received SUBSCRIBE message with QoS other than LEAST_ONE, was: " + message.getQos()); } int start = in.readerIndex(); //read messageIDs message.setMessageID(in.readUnsignedShort()); int read = in.readerIndex() - start; while (read < message.getRemainingLength()) { decodeSubscription(in, message); read = in.readerIndex() - start; } if (message.subscriptions().isEmpty()) { throw new CorruptedFrameException("subscribe MUST have got at least 1 couple topic/QoS"); } out.add(message); }