Example usage for io.netty.buffer ByteBuf readerIndex

List of usage examples for io.netty.buffer ByteBuf readerIndex

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readerIndex.

Prototype

public abstract int readerIndex();

Source Link

Document

Returns the readerIndex of this buffer.

Usage

From source file:log.server.handler.EightLengthFieldDecoder.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.//from w  w  w.  ja v a  2  s  .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);
    }
    int m = in.readableBytes(), i = 0;
    while (i < m) {
        short digit = in.getUnsignedByte(i);
        if (digit == ' ')
            break;
        i++;
    }

    if (i == m) {
        byte[] tests = new byte[in.readableBytes()];
        in.readBytes(tests);
        String log = new String(tests);
        logger.info("readablebytes======konggechangdu==" + log);
        return null;
    }
    lengthFieldLength = i;

    if (in.readableBytes() < lengthFieldLength) {
        logger.info("readablebytes<<<<<lengthFieldLength");
        return null;
    }
    initialBytesToStrip = i + lengthAdjustment;
    lengthFieldEndOffset = lengthFieldOffset + lengthFieldLength;
    int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset;
    long frameLength = getUnadjustedFrameLength(in, actualLengthFieldOffset, lengthFieldLength, byteOrder);

    if (frameLength < 0) {
        in.skipBytes(lengthFieldEndOffset);
        byte[] tests = new byte[in.readableBytes()];
        in.readBytes(tests);
        String log = new String(tests);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength + "log" + log);
    }

    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:me.melchor9000.net.resolver.DNSUtils.java

License:Open Source License

static String readName(ByteBuf b) {
    byte bytE = b.readByte();
    if ((bytE & 0xC0) == 0xC0)
        return readName(b, b.readByte(), b.readerIndex());
    else/*from w  ww.  j a  v a2  s.c o  m*/
        return readName(b, b.readerIndex() - 1, -1);
}

From source file:mysql.client.Session_Old.java

public void doHandshake() throws Exception {

    ByteBuf buf = readPacket();
    byte protocolVersion = buf.readByte();
    String serverVersion = readString(buf, "ASCII");
    System.out.println("protocolVersion = " + protocolVersion);
    System.out.println("serverVersion = " + serverVersion);

    long threadId = buf.readUnsignedInt();
    System.out.println("threadId = " + threadId);
    String seed;// w ww . jav a2 s  .c  o  m
    if (protocolVersion > 9) {//fuck ?mysql jdbc ?,,?mysql internal manualV10
        // read auth-plugin-data-part-1 (string[8])
        seed = readString(buf, "ASCII", 8);//????,ssl??
        // read filler ([00])
        buf.readByte();
        System.out.println("seed=" + seed);
    } else {
        // read scramble (string[NUL])
        seed = readString(buf, "ASCII");//v9 handshake?,?
    }

    //v10 ???

    int serverCapabilities = 0;
    // read capability flags (lower 2 bytes)
    if (buf.readerIndex() < buf.capacity()) {
        serverCapabilities = buf.readShort();
    }

    //??,???,??,????,?,?
    //?,???????,??

    //???,?debug,??
    int serverCharsetIndex = buf.readByte();
    int serverStatus = buf.readShort();
    serverCapabilities |= buf.readShort() << 16;//??,??

    int clientParam = 3842703;//??serverCapabilitiesconnection?
    //        clientParam |= 0x00200000;
    clientParam &= ~0x00100000; // ignore connection attributes
    //        if capabilities & CLIENT_PLUGIN_AUTH {
    //            1              length of auth-plugin-data
    //        } else {
    //            1              [00]
    //        }
    int authPluginDataLength = buf.readByte();//length of auth-plugin-data

    // next 10 bytes are reserved (all [00])
    //        buf.setPosition(buf.getPosition() + 10);
    buf.readerIndex(buf.readerIndex() + 10);//10??
    String seed2 = readString(buf, "ASCII", authPluginDataLength - 8);
    seed += seed2;
    System.out.println("seed =" + seed);

    //        if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
    //            proceedHandshakeWithPluggableAuthentication(user, password, database, buf);
    //            return;
    //        }
    //?????,filter-chain??
    //?MysqlOldPasswordPlugin,MysqlNativePasswordPlugin,MysqlClearPasswordPlugin...

    boolean skipPassword = false;
    int passwordLength = 16;
    int userLength = (user != null) ? user.length() : 0;
    int databaseLength = (database != null) ? database.length() : 0;

    int packLength = ((userLength + passwordLength + databaseLength) * 3) + 7 + 4 + 33;

    String pluginName = readString(buf, "ASCII");
    //initial handshake packet ?,??Handshake response packet

    ByteBuf fromServer = buf.alloc().buffer(seed.getBytes().length).writeBytes(seed.getBytes());

    byte[] bytes = Security.scramble411(password, seed, "utf-8");
    ByteBuf authBuf = buf.alloc().buffer(bytes.length).writeBytes(bytes);
    // write Auth Response Packet
    String enc = "utf-8";
    ByteBuf sendBuf = createSendByteBuf(packLength);
    sendBuf = sendBuf.order(ByteOrder.LITTLE_ENDIAN);
    //        last_sent.writeLong(this.clientParam);
    //        last_sent.writeLong(this.maxThreeBytes);
    //0x00100000

    //        "_runtime_version" -> "1.8.0_65"
    //        "_client_version" -> "5.1.38"
    //        "_client_name" -> "MySQL Connector Java"
    //        "_client_license" -> "GPL"
    //        "_runtime_vendor" -> "Oracle Corporation"
    sendBuf.writeInt(clientParam);
    sendBuf.writeInt(16777215);//writeLong(this.maxThreeBytes);
    sendBuf.writeByte(33);//CharsetMapping.MYSQL_COLLATION_INDEX_utf8;
    sendBuf.writeBytes(new byte[23]);

    //user  string<null>
    sendBuf.writeBytes(user.getBytes());
    sendBuf.writeByte(0);

    //wite toserver length
    sendBuf.writeByte(0);

    //write database
    sendBuf.writeBytes(database.getBytes());
    sendBuf.writeByte(0);

    sendBuf.writeBytes("mysql_native_password".getBytes());
    sendBuf.writeByte(0);

    //propertie
    ByteBuf propertieBuf = allocator.heapBuffer(100);
    Properties properties = new Properties();
    properties.setProperty("_runtime_version", "1.8.0_65");
    properties.setProperty("_client_version", "5.1.38");
    properties.setProperty("_client_name", "MySQL Connector Java");
    properties.setProperty("_client_license", "GPL");
    properties.setProperty("_runtime_vendor", "Oracle Corporation");
    Buffer lb = new Buffer(100);
    for (Object p : properties.keySet()) {
        lb.writeLenString((String) p);
        lb.writeLenString(properties.getProperty((String) p));
        //mysql buffer , ?int ,,?251,?65536
    }

    //        sendBuf.writeByte((byte) (lb.getPosition() - 4));
    //        sendBuf.writeBytes(lb.getByteBuffer(), 4, lb.getBufLength() - 4);

    send(sendBuf);
    //      sendBuf.writeBytes(authBuf); //?,fromServertoServer

    //jdbc driver????,,sql

}

From source file:mysql.client.Session_Old.java

final String readString(ByteBuf buf, String encoding) throws Exception {
    int i = buf.readerIndex();
    int len = 0;/* ww  w .j  av  a  2  s.com*/
    int maxLen = buf.writerIndex();

    while ((i < maxLen) && (buf.getByte(i) != 0)) {
        len++;
        i++;
    }

    try {
        return StringUtils.toString(buf.array(), buf.readerIndex(), len, encoding);
    } catch (UnsupportedEncodingException uEE) {
        throw uEE;
    } finally {
        buf.readerIndex(buf.readerIndex() + (len + 1));
    }
}

From source file:mysql.client.Session_Old.java

String readString(ByteBuf buf, String encoding, int expectedLength) throws Exception {
    if (buf.readerIndex() + expectedLength > buf.writerIndex()) {
        throw new RuntimeException();
    }/*from   w ww .j a  v  a  2s. co m*/

    try {
        return StringUtils.toString(buf.array(), buf.readerIndex(), expectedLength, encoding);
    } catch (UnsupportedEncodingException uEE) {
        throw uEE;
    } finally {
        buf.readerIndex(buf.readerIndex() + expectedLength);
    }
}

From source file:nearenough.protocol.RtMessage.java

License:Open Source License

private Map<RtTag, byte[]> extractMultiMapping(ByteBuf msg) {
    // extractOffsets will leave the reader index positioned at the first tag
    int[] offsets = extractOffsets(msg);

    int startOfValues = msg.readerIndex() + (4 * numTags);
    Map<RtTag, byte[]> mapping = new LinkedHashMap<>(numTags);
    RtTag prevTag = null;/*  ww w . ja  v  a 2 s .c o m*/

    for (int i = 0; i < offsets.length; i++) {
        long uintCurrTag = msg.readUnsignedInt();
        RtTag currTag = RtTag.fromUnsignedInt((int) uintCurrTag);

        if ((prevTag != null) && currTag.isLessThan(prevTag)) {
            String exMsg = String.format(
                    "tags not strictly increasing: current '%s' (0x%08x), previous '%s' (0x%08x)", currTag,
                    currTag.valueLE(), prevTag, prevTag.valueLE());
            throw new TagsNotIncreasingException(exMsg);
        }

        int valueIdx = startOfValues + offsets[i];
        int valueLen = ((i + 1) == offsets.length) ? msg.readableBytes() - offsets[i]
                : offsets[i + 1] - offsets[i];
        byte[] valueBytes = new byte[valueLen];
        msg.getBytes(valueIdx, valueBytes);

        mapping.put(currTag, valueBytes);
        prevTag = currTag;
    }

    return Collections.unmodifiableMap(mapping);
}

From source file:net.anyflow.lannister.NettyUtil.java

License:Apache License

public static byte[] copy(ByteBuf buffer) {
    byte[] bytes = new byte[buffer.readableBytes()];

    int readerIndex = buffer.readerIndex();
    buffer.getBytes(readerIndex, bytes);

    return bytes;
}

From source file:net.epsilony.utils.codec.modbus.handler.ModbusMasterResponseDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 6) {
        return;/* ww  w.  j  av a 2s .  c  o  m*/
    }
    int adupLength = in.getUnsignedShort(in.readerIndex() + 4);
    int wholeLength = adupLength + 6 + (withCheckSum ? 2 : 0);
    if (wholeLength > in.readableBytes()) {
        return;
    }
    if (withCheckSum) {
        checkSum(in, wholeLength);
    }
    int transectionId = in.readUnsignedShort();
    ModbusRequest request = transectingRequestRetriever.apply(transectionId);
    if (null == request) {
        in.readerIndex(in.readerIndex() + wholeLength - 2);
        out.add(new MissMatchResponse(transectionId));
        return;
    }
    in.readerIndex(in.readerIndex() + 4);
    int unitId = in.readUnsignedByte();
    if (unitId != request.getUnitId()) {
        throw new DecoderException();
    }
    int functionCode = in.readUnsignedByte();
    if ((functionCode & 0x7F) != request.getFunction().getCode()) {
        throw new DecoderException();
    }

    ModbusResponse response;

    if ((functionCode & 0x80) == 0) {
        switch (functionCode) {
        case 0x01: {
            ReadBooleanRegistersResponse bResponse = new ReadBooleanRegistersResponse();
            bResponse.setRegisterType(ModbusRegisterType.COIL);
            response = bResponse;
        }
            break;
        case 0x02: {
            ReadBooleanRegistersResponse bResponse = new ReadBooleanRegistersResponse();
            bResponse.setRegisterType(ModbusRegisterType.DISCRETE_INPUT);
            response = bResponse;
        }
            break;
        case 0x03: {
            ReadWordRegistersResponse rResponse = new ReadWordRegistersResponse();
            rResponse.setRegisterType(ModbusRegisterType.HOLDING);
            response = rResponse;
            break;
        }
        case 0x04: {
            ReadWordRegistersResponse rResponse = new ReadWordRegistersResponse();
            rResponse.setRegisterType(ModbusRegisterType.INPUT);
            response = rResponse;
        }
            break;
        case 0x05:
            response = new WriteCoilResponse();
            break;
        case 0x06:
            response = new WriteHoldingResponse();
            break;
        default:
            throw new UnsupportedFunctionCodeException();
        }
        request.getFunction().decodeResponseData(in, response);
    } else {
        ExceptionResponse exResponse = new ExceptionResponse();
        exResponse.setFunctionCode(functionCode);
        exResponse.setExceptionCode(in.readUnsignedByte());
        response = exResponse;
    }
    response.setTransectionId(transectionId);
    response.setUnitId(unitId);

    out.add(response);

    if (withCheckSum) {
        in.readerIndex(in.readerIndex() + 2);
    }

}

From source file:net.epsilony.utils.codec.modbus.handler.ModbusMasterResponseDecoder.java

License:Open Source License

private void checkSum(ByteBuf in, int wholeLength) {
    int crcGet = in.getUnsignedShort(in.readerIndex() + wholeLength - 2);
    int crcCalc = Utils.crc(in, in.readerIndex(), wholeLength - 2);
    if (crcCalc != crcGet) {
        throw new DecoderException("wrong crc");
    }//w  ww .  j a v  a2 s .  co m

}

From source file:net.epsilony.utils.codec.modbus.handler.ModbusSlaveRequestDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 6) {
        return;//from  ww w. j  a  v a 2 s.co m
    }
    int aduLength = in.getUnsignedShort(in.readerIndex() + 4);
    int wholeLength = 6 + aduLength + (withCheckSum ? 2 : 0);
    if (in.readableBytes() < wholeLength) {
        return;
    }

    if (withCheckSum) {
        checkSum(in, wholeLength);
    }
    int transectionId = in.readUnsignedShort();
    in.readerIndex(in.readerIndex() + 4);
    int unitId = in.readUnsignedByte();
    int functionCode = in.readUnsignedByte();
    ModbusFunction function;
    switch (functionCode) {
    case 0x01:
        function = new ReadBooleanRegistersFunction(ModbusRegisterType.COIL);
        break;
    case 0x02:
        function = new ReadBooleanRegistersFunction(ModbusRegisterType.DISCRETE_INPUT);
        break;
    case 0x03:
        function = new ReadWordRegistersFunction(ModbusRegisterType.HOLDING);
        break;
    case 0x04:
        function = new ReadWordRegistersFunction(ModbusRegisterType.INPUT);
        break;
    case 0x05:
        function = new WriteCoilFunction();
        break;
    case 0x06:
        function = new WriteHoldingFunction();
        break;
    default:
        throw new UnsupportedFunctionCodeException();
    }
    try {
        function.decodeRequestData(in);
    } catch (Throwable ex) {
        if (ex instanceof DecoderException) {
            throw ex;
        } else {
            throw new DecoderException(ex);
        }
    }
    ModbusRequest request = new ModbusRequest(transectionId, unitId, function);
    out.add(request);
    if (withCheckSum) {
        in.readerIndex(in.readerIndex() + 2);
    }
}