Example usage for io.netty.buffer ByteBufUtil hexDump

List of usage examples for io.netty.buffer ByteBufUtil hexDump

Introduction

In this page you can find the example usage for io.netty.buffer ByteBufUtil hexDump.

Prototype

public static String hexDump(byte[] array) 

Source Link

Document

Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a> of the specified byte array.

Usage

From source file:com.linecorp.armeria.client.http.HttpSessionHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof Http2Settings) {
        // Expected
    } else {//  w w  w .j  ava 2 s  .co  m
        try {
            final String typeInfo;
            if (msg instanceof ByteBuf) {
                typeInfo = msg + " HexDump: " + ByteBufUtil.hexDump((ByteBuf) msg);
            } else {
                typeInfo = String.valueOf(msg);
            }
            throw new IllegalStateException("unexpected message type: " + typeInfo);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}

From source file:com.linecorp.armeria.common.http.Http2GoAwayListener.java

License:Apache License

private void onGoAway(String sentOrReceived, int lastStreamId, long errorCode, ByteBuf debugData) {
    if (errorCode != Http2Error.NO_ERROR.code()) {
        if (logger.isWarnEnabled()) {
            logger.warn("{} {} a GOAWAY frame: lastStreamId={}, errorCode={}, debugData=\"{}\" (Hex: {})", ch,
                    sentOrReceived, lastStreamId, errorStr(errorCode),
                    debugData.toString(StandardCharsets.UTF_8), ByteBufUtil.hexDump(debugData));
        }/*from  ww w  . j  ava  2 s. co  m*/
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("{} {} a GOAWAY frame: lastStreamId={}, errorCode=NO_ERROR", ch, sentOrReceived,
                    lastStreamId);
        }
    }
}

From source file:com.netflix.iep.http.NetflixJsonObjectDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (state == ST_CORRUPTED) {
        in.skipBytes(in.readableBytes());
        return;/*w w w  . j av  a  2  s  . co  m*/
    }

    if (LOGGER.isTraceEnabled()) {
        byte[] bytes = new byte[in.readableBytes()];
        in.getBytes(in.readerIndex(), bytes, 0, in.readableBytes());
        LOGGER.trace("starting [" + in.readerIndex() + ":" + in.readableBytes() + "]:" + new String(bytes));
    }

    // index of next byte to process.
    int len = this.len;
    int wrtIdx = in.writerIndex();

    for (; in.readerIndex() + len < wrtIdx; len++) {
        if (len > maxObjectLength) {
            // buffer size exceeded maxObjectLength; discarding the complete buffer.
            in.skipBytes(in.readableBytes());
            reset();
            throw new TooLongFrameException(
                    "object length exceeds " + maxObjectLength + ": " + len + " bytes discarded");
        }
        byte c = in.getByte(in.readerIndex() + len);
        if (state == ST_DECODING_NORMAL) {
            decodeByte(c, in, in.readerIndex() + len);

            // All opening braces/brackets have been closed. That's enough to conclude
            // that the JSON object/array is complete.
            if (openBraces == 0) {
                ByteBuf json = extractObject(ctx, in, in.readerIndex(), len + 1);
                if (json != null) {
                    out.add(json);
                }

                // The JSON object/array was extracted => discard the bytes from
                // the input buffer.
                in.readerIndex(in.readerIndex() + len + 1);
                len = 0;
                // Reset the object state to get ready for the next JSON object/text
                // coming along the byte stream.
                reset();
                break;
            }
        } else if (state == ST_DECODING_ARRAY_STREAM) {
            if (len == 0 && Character.isWhitespace(c)) {
                in.skipBytes(1);
                len--;
            }
            decodeByte(c, in, in.readerIndex() + len);
            if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) {
                ByteBuf json = extractObject(ctx, in, in.readerIndex(), len);
                if (json != null) {
                    out.add(json);
                }

                in.readerIndex(in.readerIndex() + len + 1);
                len = 0;

                if (c == ']') {
                    reset();
                }
                break;
            }
            // JSON object/array detected. Accumulate bytes until all braces/brackets are closed.
        } else if (c == '{' || c == '[') {
            initDecoding(c);

            if (state == ST_DECODING_ARRAY_STREAM) {
                // Discard the array bracket
                in.skipBytes(1);
                len--;
            }
            // Discard leading spaces in front of a JSON object/array.
        } else if (Character.isWhitespace(c)) {
            in.skipBytes(1);
            len--;
        } else {
            state = ST_CORRUPTED;
            throw new CorruptedFrameException("invalid JSON received at byte position "
                    + (in.readerIndex() + len) + ": " + ByteBufUtil.hexDump(in));
        }
    }

    this.len = len;

    if (LOGGER.isTraceEnabled()) {
        byte[] bytes = new byte[in.readableBytes()];
        in.getBytes(in.readerIndex(), bytes, 0, in.readableBytes());
        LOGGER.trace("remainder [" + in.readerIndex() + ":" + in.readableBytes() + "]:" + new String(bytes));
    }
}

From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyBackendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    ByteBuf buf = (ByteBuf) msg;/* w  w  w. j a  va 2s . co  m*/
    System.out.println("channelRead:" + ByteBufUtil.hexDump((buf)));
    while (buf.readableBytes() > 0) {

        int payload = buf.readUnsignedMedium();
        int frameType = buf.readByte();
        Http2Flags flags = new Http2Flags(buf.readUnsignedByte());
        int streamId = readUnsignedInt(buf);
        ByteBuf payloadBuf = buf.readBytes(payload);
        ByteBuf copy = ctx.alloc().buffer();
        System.out.println("frame_type:" + frameType + "," + ByteBufUtil.hexDump((payloadBuf)));
        switch (frameType) {
        case Http2FrameTypes.SETTINGS:
            handleSettingFrame(ctx, flags);
            break;
        case Http2FrameTypes.WINDOW_UPDATE:
            handleWindowsUpdateFrame(ctx);
            break;
        case Http2FrameTypes.HEADERS:

            copy.writeMedium(payload);
            copy.writeByte(frameType);
            copy.writeByte(flags.value());
            copy.writeInt(streamId);
            copy.writeBytes(payloadBuf);
            forward(ctx, copy);
            break;
        case Http2FrameTypes.DATA:
            copy.writeMedium(payload);
            copy.writeByte(frameType);
            copy.writeByte(flags.value());
            copy.writeInt(streamId);
            copy.writeBytes(payloadBuf);
            forward(ctx, copy);
            break;
        default:
            break;

        }
    }

}

From source file:com.vethrfolnir.game.network.mu.crypt.MuDecoder.java

License:Open Source License

/**
 * C3 C4//  ww w . j  a  va 2s . c o m
 * @param buff
 * @return 
 */
public static ByteBuf DecodePacket(ByteBuf buff) {
    if (buff.writerIndex() <= 2) {
        log.fatal("Ambiguous buffer! " + ByteBufUtil.hexDump(buff));
        return null;
    }
    if (buff.readerIndex() != 0) {
        log.warn("Buffer must be at index 0!");
        buff.readerIndex(0);
    }

    int header = GetHeaderSize(buff);
    int packetSize = GetPacketSize(buff);
    int decodedSize = GetDecodedSize(buff);

    int contentSize = packetSize - header;

    //System.out.println("Header[0x"+PrintData.fillHex(buff.getUnsignedByte(0), 2)+"] size: "+GetHeaderSize(buff)+" Packet Size: "+GetPacketSize(buff) +" Content Size: "+contentSize +" Decoded: "+ GetDecodedSize(buff));

    ByteBuf out = alloc.heapBuffer(decodedSize, decodedSize);

    int originalHead = buff.getUnsignedByte(0);

    buff.readerIndex(header);
    int size = DecodeBlock(buff, out, header, contentSize);
    //buff.clear();

    size += header - 1;

    out.writerIndex(0);
    out.writeByte(originalHead);

    switch (originalHead) {
    case 0xc3:
        out.writeByte(size);
        break;
    case 0xC4:
        out.writeByte(size >> 8);
        out.writeByte(size & 0xFF);
        break;
    }

    out.writerIndex(size);
    out.readerIndex(header);

    DecXor32(out, header, size);

    out.readerIndex(0);
    return out;
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws SSLException {

    final int startOffset = in.readerIndex();
    final int endOffset = in.writerIndex();
    int offset = startOffset;
    int totalLength = 0;

    // If we calculated the length of the current SSL record before, use that information.
    if (packetLength > 0) {
        if (endOffset - startOffset < packetLength) {
            return;
        } else {//from   w ww.j  a  v a2 s  .co m
            offset += packetLength;
            totalLength = packetLength;
            packetLength = 0;
        }
    }

    boolean nonSslRecord = false;

    while (totalLength < OpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) {
        final int readableBytes = endOffset - offset;
        if (readableBytes < 5) {
            break;
        }

        final int packetLength = getEncryptedPacketLength(in, offset);
        if (packetLength == -1) {
            nonSslRecord = true;
            break;
        }

        assert packetLength > 0;

        if (packetLength > readableBytes) {
            // wait until the whole packet can be read
            this.packetLength = packetLength;
            break;
        }

        int newTotalLength = totalLength + packetLength;
        if (newTotalLength > OpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) {
            // Don't read too much.
            break;
        }

        // We have a whole packet.
        // Increment the offset to handle the next packet.
        offset += packetLength;
        totalLength = newTotalLength;
    }

    if (totalLength > 0) {
        // The buffer contains one or more full SSL records.
        // Slice out the whole packet so unwrap will only be called with complete packets.
        // Also directly reset the packetLength. This is needed as unwrap(..) may trigger
        // decode(...) again via:
        // 1) unwrap(..) is called
        // 2) wrap(...) is called from within unwrap(...)
        // 3) wrap(...) calls unwrapLater(...)
        // 4) unwrapLater(...) calls decode(...)
        //
        // See https://github.com/netty/netty/issues/1534

        in.skipBytes(totalLength);
        final ByteBuffer inNetBuf = in.nioBuffer(startOffset, totalLength);
        unwrap(ctx, inNetBuf, totalLength);
        assert !inNetBuf.hasRemaining() || engine.isInboundDone();
    }

    if (nonSslRecord) {
        // Not an SSL/TLS packet
        NotSslRecordException e = new NotSslRecordException(
                "not an SSL/TLS record: " + ByteBufUtil.hexDump(in));
        in.skipBytes(in.readableBytes());
        ctx.fireExceptionCaught(e);
        setHandshakeFailure(e);
    }
}

From source file:eu.jangos.realm.network.decoder.RealmPacketDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    logger.debug("Packet received: " + in.readableBytes());

    // We should at least get the header.
    if (in.readableBytes() < HEADER_LENGTH) {
        logger.debug("Packet received but less than header size.");
        return;/*from   w  w w  .ja va 2  s. c om*/
    }

    ByteBuf msg = in.order(ByteOrder.LITTLE_ENDIAN);

    // We should decrypt the header only once per packet.
    if (opcode == 0) {
        byte[] header = new byte[HEADER_LENGTH];
        int readBytes = (ctx.channel().attr(AUTH).get() == AuthStep.STEP_AUTHED ? HEADER_LENGTH : 4);

        for (int i = 0; i < readBytes; i++) {
            header[i] = msg.readByte();
        }

        header = ctx.channel().attr(CRYPT).get().decrypt(header);

        size = (short) ((header[0] << 8 | header[1]) & 0xFF);
        opcode = (short) ((header[3] << 8 | header[2] & 0xFF));

        logger.debug("Opcode received: " + opcode + ", with size: " + size + " (readable bytes: "
                + in.readableBytes() + ") ");
    }

    if ((in.readableBytes() + 4) < size) {
        logger.debug(
                "Packet size is higher than the available bytes. (" + in.readableBytes() + ", " + size + ")");
        return;
    }

    final Opcodes code = Opcodes.convert(opcode);

    if (code == null) {
        return;
    }

    AbstractRealmClientPacket packet = null;

    switch (code) {
    case CMSG_PING:
        packet = new CMSG_PING(code, size);
        break;
    case CMSG_AUTH_SESSION:
        packet = new CMSG_AUTH_SESSION(code, (short) 0);
        break;
    case CMSG_CHAR_ENUM:
        packet = new CMSG_CHAR_ENUM(code, size);
        break;
    case CMSG_CHAR_CREATE:
        packet = new CMSG_CHAR_CREATE(code, size);
        break;
    case CMSG_CHAR_DELETE:
        packet = new CMSG_CHAR_DELETE(code, size);
        break;
    case CMSG_PLAYER_LOGIN:
        packet = new CMSG_PLAYER_LOGIN(code, size);
        break;
    default:
        logger.debug("Context: " + ctx.name() + "Packet received, opcode not supported: " + code);
        msg.clear();
        ctx.close();
        break;
    }

    if (packet != null) {
        try {
            logger.debug("Context: " + ctx.name() + "Packet received, opcode: " + code);
            logger.debug("Packet content: \n"
                    + StringUtils.toPacketString(ByteBufUtil.hexDump(msg).toUpperCase(), size, code));
            packet.decode(msg);
            opcode = 0;
            size = 0;
        } catch (Exception e) {
            return;
        }
        out.add(packet);
        msg.clear();
    }
}

From source file:eu.jangos.realm.network.encoder.RealmPacketEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, AbstractRealmServerPacket msg, ByteBuf out) throws Exception {
    logger.debug("Context: " + ctx.name() + ", packet: " + msg.toString());
    msg.encode(out);//w  w w. j  a va2s .  co m

    logger.debug("Packet content: \n"
            + StringUtils.toPacketString(ByteBufUtil.hexDump(out).toUpperCase(), msg.getSize(), msg.getCode()));

    // Reversing header.                              
    reverseHeader(ctx, out);
}

From source file:io.datty.spring.converter.AbstractConverterTest.java

License:Apache License

public String toString(Object val) {
    if (val == null) {
        return "null";
    } else if (val instanceof ByteBuf) {
        ByteBuf bb = (ByteBuf) val;
        return ByteBufUtil.hexDump(bb);
    } else if (val instanceof List) {
        List<Object> list = (List<Object>) val;
        StringBuilder str = new StringBuilder();
        str.append("[");
        int size = list.size();
        for (int i = 0; i != size; ++i) {
            Object element = list.get(i);
            if (str.length() != 1) {
                str.append(", ");
            }/* w  w  w  . ja v a 2 s. co m*/
            str.append(toString(element));
        }
        str.append("]");
        return str.toString();
    } else if (val instanceof Map) {
        Map<Object, Object> map = (Map<Object, Object>) val;
        StringBuilder str = new StringBuilder();
        str.append("{");
        for (Map.Entry<Object, Object> e : map.entrySet()) {
            Object key = e.getKey();
            Object element = e.getValue();
            if (str.length() != 1) {
                str.append(", ");
            }
            str.append(toString(key));
            str.append("=");
            str.append(toString(element));
        }
        str.append("}");
        return str.toString();
    } else if (val.getClass().isArray()) {
        StringBuilder str = new StringBuilder();
        str.append("[");
        int size = Array.getLength(val);
        for (int i = 0; i != size; ++i) {
            Object element = Array.get(val, i);
            if (str.length() != 1) {
                str.append(", ");
            }
            str.append(toString(element));
        }
        str.append("]");
        return str.toString();
    } else {
        return String.valueOf(val);
    }
}

From source file:io.grpc.netty.WriteBufferingAndExceptionHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {//  w  ww .  jav a 2s. c om
        if (logger.isLoggable(Level.FINE)) {
            Object loggedMsg = msg instanceof ByteBuf ? ByteBufUtil.hexDump((ByteBuf) msg) : msg;
            logger.log(Level.FINE, "Unexpected channelRead()->{0} reached end of pipeline {1}",
                    new Object[] { loggedMsg, ctx.pipeline().names() });
        }
        exceptionCaught(ctx,
                Status.INTERNAL.withDescription("channelRead() missed by ProtocolNegotiator handler: " + msg)
                        .asRuntimeException());
    } finally {
        ReferenceCountUtil.safeRelease(msg);
    }
}