Example usage for io.netty.channel ChannelHandlerContext alloc

List of usage examples for io.netty.channel ChannelHandlerContext alloc

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext alloc.

Prototype

ByteBufAllocator alloc();

Source Link

Document

Return the assigned ByteBufAllocator which will be used to allocate ByteBuf s.

Usage

From source file:org.diorite.impl.connection.ByteToMessageCodec.java

License:Open Source License

/**
 * Allocate a {@link ByteBuf} which will be used as argument of {@link #encode(ChannelHandlerContext, Object, ByteBuf)}.
 * Sub-classes may override this method to returna {@link ByteBuf} with a perfect matching {@code initialCapacity}.
 *
 * @param ctx          the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param msg          the message to encode
 * @param preferDirect if it should prefer direct buffer.
 *
 * @return created ByteBuf./*from   w ww .  j  a  v a 2  s  .  com*/
 *
 * @throws Exception if allocating buffer fail.
 */
protected ByteBuf allocateBuffer(final ChannelHandlerContext ctx, final I msg, final boolean preferDirect)
        throws Exception {
    if (preferDirect) {
        return ctx.alloc().ioBuffer();
    } else {
        return ctx.alloc().heapBuffer();
    }
}

From source file:org.diorite.impl.connection.packets.PacketCompression.java

License:Open Source License

@Override
protected ByteBuf allocateBuffer(final ChannelHandlerContext ctx, final ByteBuf msg, final boolean preferDirect)
        throws Exception {
    // TODO: keep this in valid values, to keep byte buffers not extends when writing, but also don't crate 2 000 000 byte buffers for 50 000 bytes data.
    final int i = msg.readableBytes();
    final int sizesKey = getKey(i);
    int size = getSize(sizesKey);
    if (size == -1) {
        throw new AssertionError();
    }/*from  www . ja  v a  2  s  .c  o m*/
    if (size == 0) {
        size = msg.readableBytes() + 10;
    } else if (size > msg.readableBytes()) {
        size = msg.readableBytes();
    }
    if (preferDirect) {
        return ctx.alloc().ioBuffer(size);
    } else {
        return ctx.alloc().heapBuffer(size);
    }
}

From source file:org.dna.mqtt.moquette.parser.netty.SubAckEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext chc, SubAckMessage message, ByteBuf out) {
    if (message.types().isEmpty()) {
        throw new IllegalArgumentException("Found a suback message with empty topics");
    }//  w  ww  .j  a v a  2s .c  o m

    int variableHeaderSize = 2 + message.types().size();
    ByteBuf buff = chc.alloc().buffer(6 + variableHeaderSize);
    try {
        buff.writeByte(AbstractMessage.SUBACK << 4);
        buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
        buff.writeShort(message.getMessageID());
        for (QOSType c : message.types()) {
            int qosValue = (c == QOSType.FAILURE) ? qosValue = 0x80 : c.ordinal();
            buff.writeByte(qosValue);
        }

        out.writeBytes(buff);
    } finally {
        buff.release();
    }
}

From source file:org.eclipse.neoscada.protocol.iec60870.apci.MessageChannel.java

License:Open Source License

private ByteBuf encode(final ChannelHandlerContext ctx, final Object msg) {
    ByteBuf buf = ctx.alloc().buffer(255);
    try {/* w  w w. java2s. c o  m*/
        this.manager.encodeMessage(msg, buf);
        if (buf.isReadable()) {
            // copy away the reference so it does not get released
            final ByteBuf buf2 = buf;
            buf = null;
            return buf2;
        }
    } finally {
        ReferenceCountUtil.release(buf);
    }
    return null;
}

From source file:org.eclipse.scada.protocol.relp.FrameCodec.java

License:Open Source License

protected void processFrame(final ChannelHandlerContext ctx, final Frame frame, final ChannelPromise promise) {
    final int length = frame.getData() == null ? 0 : frame.getData().readableBytes();

    final ByteBuf data = ctx.alloc().buffer();
    data.writeBytes(String.format("%s", frame.getTransactionId()).getBytes(TXNR_CHARSET));
    data.writeByte(Constants.SP);//w  w  w.  j av a2  s.c  o m
    data.writeBytes(frame.getCommand().getBytes(COMMAND_CHARSET));
    data.writeByte(Constants.SP);
    data.writeBytes(String.format("%s", length).getBytes(LENGTH_CHARSET));

    if (length > 0) {
        data.writeByte(Constants.SP);
        data.writeBytes(frame.getData());
    }

    if (frame.getData() != null) {
        frame.getData().release();
    }

    data.writeByte(Constants.LF);

    ctx.write(data);
}

From source file:org.enderstone.server.packet.NetworkEncrypter.java

License:Open Source License

protected ByteBuf decrypt(ChannelHandlerContext ctx, ByteBuf inbytes) throws ShortBufferException {
    int readableBytes = inbytes.readableBytes();
    byte[] byteArray = fillInBuffer(inbytes);
    ByteBuf localByteBuf = ctx.alloc().heapBuffer(this.cipher.getOutputSize(readableBytes));
    localByteBuf.writerIndex(/*  w  w w .j  a v  a 2 s . c o m*/
            this.cipher.update(byteArray, 0, readableBytes, localByteBuf.array(), localByteBuf.arrayOffset()));
    return localByteBuf;
}

From source file:org.ethereum.net.rlpx.HandshakeHandler.java

License:Open Source License

public void initiate(ChannelHandlerContext ctx) throws Exception {

    loggerNet.debug("RLPX protocol activated");

    nodeId = myKey.getNodeId();//from  w ww .ja v  a2s  .co  m

    handshake = new EncryptionHandshake(ECKey.fromNodeId(this.remoteId).getPubKeyPoint());

    Object msg;
    if (config.eip8()) {
        AuthInitiateMessageV4 initiateMessage = handshake.createAuthInitiateV4(myKey);
        initiatePacket = handshake.encryptAuthInitiateV4(initiateMessage);
        msg = initiateMessage;
    } else {
        AuthInitiateMessage initiateMessage = handshake.createAuthInitiate(null, myKey);
        initiatePacket = handshake.encryptAuthMessage(initiateMessage);
        msg = initiateMessage;
    }

    final ByteBuf byteBufMsg = ctx.alloc().buffer(initiatePacket.length);
    byteBufMsg.writeBytes(initiatePacket);
    ctx.writeAndFlush(byteBufMsg).sync();

    channel.getNodeStatistics().rlpxAuthMessagesSent.add();

    if (loggerNet.isDebugEnabled())
        loggerNet.debug("To:   {}    Send:  {}", ctx.channel().remoteAddress(), msg);
}

From source file:org.ethereum.net.rlpx.HandshakeHandler.java

License:Open Source License

private void decodeHandshake(final ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {

    if (handshake.isInitiator()) {
        if (frameCodec == null) {

            byte[] responsePacket = new byte[AuthResponseMessage.getLength() + ECIESCoder.getOverhead()];
            if (!buffer.isReadable(responsePacket.length))
                return;
            buffer.readBytes(responsePacket);

            try {

                // trying to decode as pre-EIP-8

                AuthResponseMessage response = handshake.handleAuthResponse(myKey, initiatePacket,
                        responsePacket);
                loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), response);

            } catch (Throwable t) {

                // it must be format defined by EIP-8 then

                responsePacket = readEIP8Packet(buffer, responsePacket);

                if (responsePacket == null)
                    return;

                AuthResponseMessageV4 response = handshake.handleAuthResponseV4(myKey, initiatePacket,
                        responsePacket);
                loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), response);
            }//from   www .j  av  a 2s.c o m

            EncryptionHandshake.Secrets secrets = this.handshake.getSecrets();
            this.frameCodec = new FrameCodec(secrets);

            loggerNet.debug("auth exchange done");
            channel.sendHelloMessage(ctx, frameCodec, Hex.toHexString(nodeId));
        } else {
            loggerWire.info("MessageCodec: Buffer bytes: " + buffer.readableBytes());
            List<Frame> frames = frameCodec.readFrames(buffer);
            if (frames == null || frames.isEmpty())
                return;
            Frame frame = frames.get(0);
            byte[] payload = ByteStreams.toByteArray(frame.getStream());
            if (frame.getType() == P2pMessageCodes.HELLO.asByte()) {
                HelloMessage helloMessage = new HelloMessage(payload);
                if (loggerNet.isDebugEnabled())
                    loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), helloMessage);
                isHandshakeDone = true;
                this.channel.publicRLPxHandshakeFinished(ctx, frameCodec, helloMessage);
            } else {
                DisconnectMessage message = new DisconnectMessage(payload);
                if (loggerNet.isDebugEnabled())
                    loggerNet.debug("From: {}    Recv:  {}", channel, message);
                channel.getNodeStatistics().nodeDisconnectedRemote(message.getReason());
            }
        }
    } else {
        loggerWire.debug("Not initiator.");
        if (frameCodec == null) {
            loggerWire.debug("FrameCodec == null");
            byte[] authInitPacket = new byte[AuthInitiateMessage.getLength() + ECIESCoder.getOverhead()];
            if (!buffer.isReadable(authInitPacket.length))
                return;
            buffer.readBytes(authInitPacket);

            this.handshake = new EncryptionHandshake();

            byte[] responsePacket;

            try {

                // trying to decode as pre-EIP-8
                AuthInitiateMessage initiateMessage = handshake.decryptAuthInitiate(authInitPacket, myKey);
                loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), initiateMessage);

                AuthResponseMessage response = handshake.makeAuthInitiate(initiateMessage, myKey);
                loggerNet.debug("To:   {}    Send:  {}", ctx.channel().remoteAddress(), response);
                responsePacket = handshake.encryptAuthResponse(response);

            } catch (Throwable t) {

                // it must be format defined by EIP-8 then
                try {

                    authInitPacket = readEIP8Packet(buffer, authInitPacket);

                    if (authInitPacket == null)
                        return;

                    AuthInitiateMessageV4 initiateMessage = handshake.decryptAuthInitiateV4(authInitPacket,
                            myKey);
                    loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), initiateMessage);

                    AuthResponseMessageV4 response = handshake.makeAuthInitiateV4(initiateMessage, myKey);
                    loggerNet.debug("To:   {}    Send:  {}", ctx.channel().remoteAddress(), response);
                    responsePacket = handshake.encryptAuthResponseV4(response);

                } catch (InvalidCipherTextException ce) {
                    loggerNet.warn("Can't decrypt AuthInitiateMessage from " + ctx.channel().remoteAddress()
                            + ". Most likely the remote peer used wrong public key (NodeID) to encrypt message.");
                    return;
                }
            }

            handshake.agreeSecret(authInitPacket, responsePacket);

            EncryptionHandshake.Secrets secrets = this.handshake.getSecrets();
            this.frameCodec = new FrameCodec(secrets);

            ECPoint remotePubKey = this.handshake.getRemotePublicKey();

            byte[] compressed = remotePubKey.getEncoded();

            this.remoteId = new byte[compressed.length - 1];
            System.arraycopy(compressed, 1, this.remoteId, 0, this.remoteId.length);

            final ByteBuf byteBufMsg = ctx.alloc().buffer(responsePacket.length);
            byteBufMsg.writeBytes(responsePacket);
            ctx.writeAndFlush(byteBufMsg).sync();
        } else {
            List<Frame> frames = frameCodec.readFrames(buffer);
            if (frames == null || frames.isEmpty())
                return;
            Frame frame = frames.get(0);

            Message message = new P2pMessageFactory().create((byte) frame.getType(),
                    ByteStreams.toByteArray(frame.getStream()));
            loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), message);

            if (frame.getType() == P2pMessageCodes.DISCONNECT.asByte()) {
                loggerNet.debug("Active remote peer disconnected right after handshake.");
                return;
            }

            if (frame.getType() != P2pMessageCodes.HELLO.asByte()) {
                throw new RuntimeException("The message type is not HELLO or DISCONNECT: " + message);
            }

            final HelloMessage inboundHelloMessage = (HelloMessage) message;

            // now we know both remote nodeId and port
            // let's set node, that will cause registering node in NodeManager
            channel.initWithNode(remoteId, inboundHelloMessage.getListenPort());

            // Secret authentication finish here
            channel.sendHelloMessage(ctx, frameCodec, Hex.toHexString(nodeId));
            isHandshakeDone = true;
            this.channel.publicRLPxHandshakeFinished(ctx, frameCodec, inboundHelloMessage);
            channel.getNodeStatistics().rlpxInHello.add();
        }
    }
}

From source file:org.evilco.network.rcon.common.codec.FrameCodec.java

License:Apache License

/**
 * {@inheritDoc}/*from   w  w  w . j a v a  2s  .c o  m*/
 */
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> objects)
        throws Exception {
    // set order
    byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);

    // read all available packets
    while (byteBuf.readableBytes() >= 4) {
        // log
        getLogger().trace("Decoding frame with maximal size of " + byteBuf.readableBytes() + " bytes.");

        // mark reader index
        byteBuf.markReaderIndex();

        // read length
        int length = byteBuf.readInt();

        // log
        getLogger().trace("Detected frame length of " + length + " bytes.");

        // check whether enough data is available
        if (length > byteBuf.readableBytes()) {
            // log
            getLogger().debug("There are only " + byteBuf.readableBytes() + " out of " + length
                    + " bytes available. Skipping frame until more data is available.");

            // reset buffer
            byteBuf.resetReaderIndex();

            // exit loop
            break;
        }

        // log
        getLogger().trace("Frame seems to be complete reading data.");

        // construct buffer
        ByteBuf packetBuffer = channelHandlerContext.alloc().buffer(length);

        // read data
        byteBuf.readBytes(packetBuffer, length);

        // add to list
        objects.add(packetBuffer);

        // log
        getLogger().trace("Frame decoded. " + byteBuf.readableBytes() + " bytes left in buffer.");
    }
}

From source file:org.evilco.network.rcon.common.codec.RconCodec.java

License:Apache License

/**
 * {@inheritDoc}//from w w w .  j  a v  a 2s  .  com
 */
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, PacketWrapper packetWrapper, ByteBuf byteBuf)
        throws Exception {
    // set order
    byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);

    // fire event
    PacketSendEvent event = new PacketSendEvent(packetWrapper);
    this.eventBus.post(event);

    // cancel
    if (event.isCancelled())
        return;
    packetWrapper = event.getPacket();

    // find packetID
    int packetID = this.configuration.getOutboundRegistry().findPacketID(packetWrapper.getPacket());

    // log
    getLogger().debug("Encoding packet of type " + packetWrapper.getPacket().getClass().getName()
            + " (packetID: " + packetID + ") with identifier " + packetWrapper.getIdentifier() + ".");

    // write identifier
    byteBuf.writeInt(packetWrapper.getIdentifier());

    // write packet identifier
    byteBuf.writeInt(packetID);

    // allocate buffer
    ByteBuf buffer = channelHandlerContext.alloc().buffer();

    // write body
    packetWrapper.getPacket().write(buffer);

    // write data
    byteBuf.writeBytes(buffer);

    // write terminator
    buffer.writeBytes(new byte[] { 0x00, 0x00 });

    // fire event
    this.eventBus.post(new PacketSentEvent(packetWrapper));
}