Example usage for io.netty.buffer ByteBuf readBytes

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

Introduction

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

Prototype

public abstract ByteBuf readBytes(ByteBuffer dst);

Source Link

Document

Transfers this buffer's data to the specified destination starting at the current readerIndex until the destination's position reaches its limit, and increases the readerIndex by the number of the transferred bytes.

Usage

From source file:com.openddal.server.mysql.MySQLProtocolDecoder.java

License:Apache License

/**
 * @param in/*from   w  ww  . j  a va2  s . co m*/
 * @return
 */
private int readLength(ByteBuf in) {
    byte[] lens = new byte[4];
    in.readBytes(lens);
    int size = Packet.getSize(lens);
    return size;
}

From source file:com.openddal.server.mysql.MySQLServerHandler.java

License:Apache License

private void authenticate(ChannelHandlerContext ctx, ByteBuf buf) {
    Privilege privilege = server.getPrivilege();
    HandshakeResponse authReply = null;// w w w.j av a  2  s  .  c  o  m
    try {
        byte[] packet = new byte[buf.readableBytes()];
        buf.readBytes(packet);
        authReply = HandshakeResponse.loadFromPacket(packet);
        this.sequenceId = authReply.sequenceId;
        ACCESSLOGGER.seqId(this.sequenceId).command(authReply.toString());
        if (!authReply.hasCapabilityFlag(Flags.CLIENT_PROTOCOL_41)) {
            sendError(ctx, ErrorCode.ER_NOT_SUPPORTED_AUTH_MODE, "We do not support Protocols under 4.1");
            return;
        }
        if (!privilege.userExists(authReply.username)) {
            sendError(ctx, ErrorCode.ER_ACCESS_DENIED_ERROR,
                    "Access denied for user '" + authReply.username + "'");
            return;
        }
        if (!StringUtil.isEmpty(authReply.schema)
                && !privilege.schemaExists(authReply.username, authReply.schema)) {
            String s = "Access denied for user '" + authReply.username + "' to database '" + authReply.schema
                    + "'";
            sendError(ctx, ErrorCode.ER_DBACCESS_DENIED_ERROR, s);
            return;
        }
        String seed = session.getAttachment("seed");
        if (!privilege.checkPassword(authReply.username, authReply.authResponse, seed)) {
            sendError(ctx, ErrorCode.ER_ACCESS_DENIED_ERROR,
                    "Access denied for user '" + authReply.username + "'");
            return;
        }
        session.setUser(authReply.username);
        session.setSchema(authReply.schema);
        session.setPassword(authReply.authResponse);
        session.bind(ctx.channel());
        session.setAttachment("remoteAddress", ctx.channel().remoteAddress().toString());
        session.setAttachment("localAddress", ctx.channel().localAddress().toString());
        success(ctx);
    } catch (Exception e) {
        String errMsg = authReply == null ? e.getMessage()
                : "Access denied for user '" + authReply.username + "' to database '" + authReply.schema + "'";
        LOGGER.error("Authorize failed. " + errMsg, e);
        sendError(ctx, ErrorCode.ER_DBACCESS_DENIED_ERROR, errMsg);
    }
}

From source file:com.openddal.server.mysql.MySQLServerHandler.java

License:Apache License

private void despatchCommand(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {
    byte[] data = new byte[buf.readableBytes()];
    buf.readBytes(data);
    this.sequenceId = Packet.getSequenceId(data);
    Packet packet = null;//from   w  ww  . j a  v a 2  s  . c om

    byte type = Packet.getType(data);
    switch (type) {
    case Flags.COM_INIT_DB:
        packet = ComInitdb.loadFromPacket(data);
        init(ctx, (ComInitdb) packet);
        break;
    case Flags.COM_QUERY:
        packet = ComQuery.loadFromPacket(data);
        query(ctx, (ComQuery) packet);
        break;
    case Flags.COM_PING:
        packet = ComPing.loadFromPacket(data);
        ping(ctx, (ComPing) packet);
        break;
    case Flags.COM_QUIT:
        packet = ComQuit.loadFromPacket(data);
        close(ctx, (ComQuit) packet);
        break;
    case Flags.COM_PROCESS_KILL:
        packet = ComProcesskill.loadFromPacket(data);
        processKill(ctx, (ComProcesskill) packet);
        break;
    case Flags.COM_STMT_PREPARE:
        packet = ComStmtPrepare.loadFromPacket(data);
        stmtPrepare(ctx, (ComStmtPrepare) packet);
        break;
    case Flags.COM_STMT_SEND_LONG_DATA:
        packet = ComStmtSendLongData.loadFromPacket(data);
        stmtPrepareLongData(ctx, (ComStmtSendLongData) packet);
        break;
    case Flags.COM_STMT_EXECUTE:
        packet = ComStmtExecute.loadFromPacket(data);
        stmtExecute(ctx, (ComStmtExecute) packet);
        break;
    case Flags.COM_STMT_CLOSE:
        packet = ComStmtClose.loadFromPacket(data);
        stmtClose(ctx, (ComStmtClose) packet);
        break;
    case Flags.COM_SHUTDOWN:
        packet = ComShutdown.loadFromPacket(data);
        shutdown(ctx, (ComShutdown) packet);
        break;
    case Flags.COM_STMT_RESET:
        packet = ComStmtReset.loadFromPacket(data);
        stmtReset(ctx, (ComStmtReset) packet);
        break;
    case Flags.COM_FIELD_LIST:
        packet = ComFieldlist.loadFromPacket(data);
        fieldList(ctx, (ComFieldlist) packet);
        break;
    case Flags.COM_STATISTICS:
        packet = ComStatistics.loadFromPacket(data);
        statistics(ctx, (ComStatistics) packet);
        break;
    default:
        throw ServerException.get(ErrorCode.ER_UNKNOWN_COM_ERROR, "Unknown command " + type);
    }
}

From source file:com.phei.netty.protocol.netty.codec.NettyMessageDecoder.java

License:Apache License

@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    //LengthFieldBasedFrameDecoder??
    //???/*from ww w  . j a  v a 2 s. c  o m*/
    //i/o????
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
        return null;
    }

    NettyMessage message = new NettyMessage();
    Header header = new Header();
    header.setCrcCode(frame.readInt());
    header.setLength(frame.readInt());
    header.setSessionID(frame.readLong());
    header.setType(frame.readByte());
    header.setPriority(frame.readByte());

    int size = frame.readInt();
    if (size > 0) {
        Map<String, Object> attch = new HashMap<String, Object>(size);
        int keySize = 0;
        byte[] keyArray = null;
        String key = null;
        for (int i = 0; i < size; i++) {
            keySize = frame.readInt();
            keyArray = new byte[keySize];
            frame.readBytes(keyArray);
            key = new String(keyArray, "UTF-8");
            attch.put(key, marshallingDecoder.decode(frame));
        }
        keyArray = null;
        key = null;
        header.setAttachment(attch);
    }
    //body??body
    if (frame.readableBytes() > 4) {
        message.setBody(marshallingDecoder.decode(frame));
    }
    message.setHeader(header);
    return message;
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.ConnectDecoder.java

License:Open Source License

@Override
public AbstractMessage decode(AttributeMap ctx, ByteBuf in) throws UnsupportedEncodingException {
    in.resetReaderIndex();//from w  w  w. j av  a 2 s.  c  o m
    //Common decoding part
    ConnectMessage message = new ConnectMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();
        return null;
    }
    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 null;
        }

        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) VERSION_3_1);
        break;
    case 4:
        //MQTT version 3.1.1 "MQTT"
        //ProtocolName 6 bytes
        if (in.readableBytes() < 8) {
            in.resetReaderIndex();
            return null;
        }
        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) 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.setProcotolVersion(in.readByte());
    if (message.getProcotolVersion() == 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");
        }
    }

    //PKMPConnection flag
    byte connFlags = in.readByte();
    if (message.getProcotolVersion() == 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.getProcotolVersion() == VERSION_3_1)
            || (remainingLength == 10 && message.getProcotolVersion() == VERSION_3_1_1)) {
        return message;
    }

    //Decode the ClientID
    String clientID = Utils.decodeString(in);
    if (clientID == null) {
        in.resetReaderIndex();
        return null;
    }
    message.setClientID(clientID);

    //Decode willTopic
    if (willFlag) {
        String willTopic = Utils.decodeString(in);
        if (willTopic == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setWillTopic(willTopic);
    }

    //Decode willMessage
    if (willFlag) {
        String willMessage = Utils.decodeString(in);
        if (willMessage == null) {
            in.resetReaderIndex();
            return null;
        }
        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) {
        return message;
    }

    //Decode username
    if (userFlag) {
        String userName = Utils.decodeString(in);
        if (userName == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setUsername(userName);
    }

    readed = in.readerIndex() - start;
    if (readed == remainingLength) {
        return message;
    }

    //Decode password
    if (passwordFlag) {
        String password = Utils.decodeString(in);
        if (password == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setPassword(password);
    }
    return message;
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.PublishDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    LOG.info("decode invoked with buffer {}", in);
    in.resetReaderIndex();/* w  w  w. j  a  v  a2  s .com*/
    int startPos = in.readerIndex();

    //Common decoding part
    PublishMessage message = new PublishMessage();
    if (!decodeCommonHeader(message, in)) {
        LOG.info("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;
    }
    if (topic.contains("+") || topic.contains("#")) {
        throw new CorruptedFrameException(
                "Received a PUBLISH with topic containting wild card chars, topic: " + topic);
    }

    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;
    }
    //        byte[] b = new byte[payloadSize];
    ByteBuf bb = Unpooled.buffer(payloadSize);
    in.readBytes(bb);
    message.setPayload(bb.nioBuffer());

    out.add(message);
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.Utils.java

License:Open Source License

/**
 * Load a string from the given buffer, reading first the two bytes of len
 * and then the UTF-8 bytes of the string.
 * /*from   ww w.j a va  2  s.c  o m*/
 * @return the decoded string or null if NEED_DATA
 */
static String decodeString(ByteBuf in) throws UnsupportedEncodingException {
    if (in.readableBytes() < 2) {
        return null;
    }
    //int strLen = Utils.readWord(in);
    int strLen = in.readUnsignedShort();
    if (in.readableBytes() < strLen) {
        return null;
    }
    byte[] strRaw = new byte[strLen];
    in.readBytes(strRaw);

    return new String(strRaw, "UTF-8");
}

From source file:com.qualys.jserf.SerfClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
    byte[] bytes = new byte[byteBuf.readableBytes()];
    byteBuf.readBytes(bytes);
    InputStream inputStream = new ByteArrayInputStream(bytes);

    Map<String, Value> headerValues = messagePack.read(inputStream, templateMap);
    log.trace("Response header was {}", headerValues);
    Map<String, Value> bodyValues = Collections.emptyMap();
    if (inputStream.available() != 0) {
        bodyValues = messagePack.read(inputStream, templateMap);
    }//from   w  w w  . ja  va  2 s.  co m
    log.trace("Response body was {}", bodyValues);

    int sequence = headerValues.get("Seq").asIntegerValue().getInt();
    String errorMessage = headerValues.get("Error").asRawValue().getString();
    ResponseHeader header = new ResponseHeader(errorMessage, sequence);

    Pair<Command, SerfResponseCallBack> commandCallBackPair = callBacksBySequence.getIfPresent(sequence);
    if (commandCallBackPair == null) {
        log.debug(
                "Couldn't find corresponding Command/SerfResponseCallBack pair for sequence={}. Maybe it was already stopped?",
                sequence);
        return;
    }

    Command command = commandCallBackPair.getLeft();

    if (StringUtils.isNotEmpty(errorMessage)) {
        log.debug("Received error message '{}' with response for command={} and sequence={}", errorMessage,
                command, sequence);
    }

    Optional<ResponseBodyExtractor> extractor = extractorManager.getExtractor(command);
    if (!extractor.isPresent()) {
        log.warn("Couldn't find extractor for command={}", command);
        return;
    }
    SerfResponse response = new SerfResponse<>(header,
            extractor.get().extractBody(bodyValues, extractorManager));

    if (Command.QUERY.equals(command)) {
        QueryResponseBody queryResponseBody = (QueryResponseBody) response.getBody();
        if (QueryResponseBody.Type.DONE.equals(queryResponseBody.getType())) {
            log.trace(
                    "Removing Command/SerfResponseCallBack pair for sequence={} because it query command and the returned 'type' value was 'done'",
                    sequence);
            callBacksBySequence.invalidate(sequence);
        }
    }

    if (!multipleResponseCommands.contains(command)) {
        log.trace(
                "Removing Command/SerfResponseCallBack pair for sequence={} because it wasn't a command that returns multiple responses (those commands are: {})",
                sequence, multipleResponseCommands);
        callBacksBySequence.invalidate(sequence);
    }

    if (commandCallBackPair.getRight() == null) {
        log.trace("Callback for Command/SerfResponseCallBack pair with sequence={} was null", sequence);
        return;
    }

    log.trace("Invoking callback for command={} with sequence={}", command, sequence);
    commandCallBackPair.getRight().call(response);
    log.trace("Invoked callback for command={} with sequence={}", command, sequence);
}

From source file:com.quavo.osrs.network.protocol.codec.update.UpdateEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, UpdateResponse msg, ByteBuf out) throws Exception {
    int type = msg.getType();
    int id = msg.getId();
    ByteBuf container = msg.getContainer();

    int compression = container.readUnsignedByte();
    int length = container.readInt();

    out.writeByte(type);/*  ww w.  j ava  2 s  .  c  o  m*/
    out.writeShort(id);
    out.writeByte(compression);
    out.writeInt(length);

    int bytes = container.readableBytes();
    if (bytes > 504) {
        bytes = 504;
    }
    out.writeBytes(container.readBytes(bytes));
    while ((bytes = container.readableBytes()) != 0) {
        if (bytes == 0) {
            break;
        } else if (bytes > 511) {
            bytes = 511;
        }
        out.writeByte(0xff);
        out.writeBytes(container.readBytes(bytes));
    }
}

From source file:com.quavo.util.buf.ByteBufUtils.java

License:Open Source License

/**
 * Encrypts a {@link ByteBuf} using with a exponent and modulus.
 * /*from ww w .  j av  a2s.co m*/
 * @param buffer The {@link ByteBuf} to encrypt.
 * @param exponent The exponent.
 * @param modulus The modulus.
 * @return The encrypted buffer.
 */
public static ByteBuf encipherRSA(ByteBuf buffer, BigInteger exponent, BigInteger modulus) {
    byte[] bytes = new byte[buffer.readShort()];
    buffer.readBytes(bytes);
    return Unpooled.wrappedBuffer(new BigInteger(bytes).modPow(exponent, modulus).toByteArray());
}