Example usage for io.netty.channel ChannelHandlerContext fireChannelRead

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

Introduction

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

Prototype

@Override
    ChannelHandlerContext fireChannelRead(Object msg);

Source Link

Usage

From source file:divconq.net.ByteToMessageDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof ByteBuf) {
        RecyclableArrayList out = RecyclableArrayList.newInstance();

        try {/*from  ww  w  .  ja  v a  2  s. c  om*/
            ByteBuf data = (ByteBuf) msg;
            this.first = this.cumulation == null;

            if (this.first) {
                this.cumulation = data;
            } else {
                if (this.cumulation.writerIndex() > this.cumulation.maxCapacity() - data.readableBytes()
                        || this.cumulation.refCnt() > 1) {
                    // Expand cumulation (by replace it) when either there is not more room in the buffer
                    // or if the refCnt is greater then 1 which may happen when the user use slice().retain() or
                    // duplicate().retain().
                    //
                    // See:
                    // - https://github.com/netty/netty/issues/2327
                    // - https://github.com/netty/netty/issues/1764
                    this.expandCumulation(ctx, data.readableBytes());
                }

                this.cumulation.writeBytes(data);
                data.release();
            }

            this.callDecode(ctx, this.cumulation, out);
        } catch (DecoderException e) {
            throw e;
        } catch (Throwable t) {
            throw new DecoderException(t);
        } finally {
            if (this.cumulation != null && !this.cumulation.isReadable()) {
                this.cumulation.release();
                this.cumulation = null;
            }
            int size = out.size();
            this.decodeWasNull = size == 0;

            for (int i = 0; i < size; i++) {
                ctx.fireChannelRead(out.get(i));
            }
            out.recycle();
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:divconq.net.ByteToMessageDecoder.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    RecyclableArrayList out = RecyclableArrayList.newInstance();
    try {/* w w  w  .  j  a va 2s  . co  m*/
        if (this.cumulation != null) {
            callDecode(ctx, this.cumulation, out);
            decodeLast(ctx, this.cumulation, out);
        } else {
            decodeLast(ctx, Unpooled.EMPTY_BUFFER, out);
        }
    } catch (DecoderException e) {
        throw e;
    } catch (Exception e) {
        throw new DecoderException(e);
    } finally {
        try {
            if (this.cumulation != null) {
                this.cumulation.release();
                this.cumulation = null;
            }
            int size = out.size();
            for (int i = 0; i < size; i++) {
                ctx.fireChannelRead(out.get(i));
            }
            if (size > 0) {
                // Something was read, call fireChannelReadComplete()
                ctx.fireChannelReadComplete();
            }
            ctx.fireChannelInactive();
        } finally {
            // recycle in all cases
            out.recycle();
        }
    }
}

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

License:Apache License

private void unwrap(ChannelHandlerContext ctx, ByteBuffer packet, int initialOutAppBufCapacity)
        throws SSLException {

    // If SSLEngine expects a heap buffer for unwrapping, do the conversion.
    final ByteBuffer oldPacket;
    final ByteBuf newPacket;
    final int oldPos = packet.position();
    if (wantsInboundHeapBuffer && packet.isDirect()) {
        newPacket = ctx.alloc().heapBuffer(packet.limit() - oldPos);
        newPacket.writeBytes(packet);/* w w  w .  j a va 2 s  .  c o  m*/
        oldPacket = packet;
        packet = newPacket.nioBuffer();
    } else {
        oldPacket = null;
        newPacket = null;
    }

    boolean wrapLater = false;
    ByteBuf decodeOut = allocate(ctx, initialOutAppBufCapacity);
    try {
        for (;;) {
            final SSLEngineResult result = unwrap(engine, packet, decodeOut);
            final Status status = result.getStatus();
            final HandshakeStatus handshakeStatus = result.getHandshakeStatus();
            final int produced = result.bytesProduced();
            final int consumed = result.bytesConsumed();

            if (status == Status.CLOSED) {
                // notify about the CLOSED state of the SSLEngine. See #137
                sslCloseFuture.trySuccess(ctx.channel());
                break;
            }

            switch (handshakeStatus) {
            case NEED_UNWRAP:
                break;
            case NEED_WRAP:
                wrapNonAppData(ctx, true);
                break;
            case NEED_TASK:
                runDelegatedTasks();
                break;
            case FINISHED:
                setHandshakeSuccess();
                wrapLater = true;
                continue;
            case NOT_HANDSHAKING:
                if (setHandshakeSuccessIfStillHandshaking()) {
                    wrapLater = true;
                    continue;
                }
                if (flushedBeforeHandshakeDone) {
                    // We need to call wrap(...) in case there was a flush done before the handshake completed.
                    //
                    // See https://github.com/netty/netty/pull/2437
                    flushedBeforeHandshakeDone = false;
                    wrapLater = true;
                }

                break;
            default:
                throw new IllegalStateException("Unknown handshake status: " + handshakeStatus);
            }

            if (status == Status.BUFFER_UNDERFLOW || consumed == 0 && produced == 0) {
                break;
            }
        }

        if (wrapLater) {
            wrap(ctx, true);
        }
    } catch (SSLException e) {
        setHandshakeFailure(e);
        throw e;
    } finally {
        // If we converted packet into a heap buffer at the beginning of this method,
        // we should synchronize the position of the original buffer.
        if (newPacket != null) {
            oldPacket.position(oldPos + packet.position());
            newPacket.release();
        }

        if (decodeOut.isReadable()) {
            ctx.fireChannelRead(decodeOut);
        } else {
            decodeOut.release();
        }
    }
}

From source file:eu.jangos.realm.network.handler.CharacterHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    // Let's refuse any packed for non-authed clients.
    if (ctx.channel().attr(AUTH).get() != AuthStep.STEP_AUTHED) {
        return;//  www. j ava  2 s.c om
    }

    AbstractRealmClientPacket request = (AbstractRealmClientPacket) msg;

    AbstractRealmServerPacket response = null;

    logger.info(msg.toString());

    switch (request.getOpcode()) {
    case CMSG_PING:
        response = new SMSG_PING(Opcodes.SMSG_PING);

        int ping = ((CMSG_PING) request).getPing();

        ((SMSG_PING) response).setPing(ping);

        break;
    case CMSG_CHAR_ENUM:
        response = new SMSG_CHAR_ENUM(Opcodes.SMSG_CHAR_ENUM);

        // Adding character list.
        ((SMSG_CHAR_ENUM) response)
                .addCharacters(characterService.getCharactersForAccount(ctx.channel().attr(ACCOUNT).get()));

        break;
    case CMSG_CHAR_CREATE:
        response = new SMSG_CHAR_CREATE(Opcodes.SMSG_CHAR_CREATE);

        ((SMSG_CHAR_CREATE) response).setResult(characterService.createChar(
                ((CMSG_CHAR_CREATE) request).getName(), ((CMSG_CHAR_CREATE) request).getRace(),
                ((CMSG_CHAR_CREATE) request).getCharClass(), ((CMSG_CHAR_CREATE) request).getGender(),
                ((CMSG_CHAR_CREATE) request).getSkin(), ((CMSG_CHAR_CREATE) request).getFace(),
                ((CMSG_CHAR_CREATE) request).getHairStyle(), ((CMSG_CHAR_CREATE) request).getHairColor(),
                ((CMSG_CHAR_CREATE) request).getFacialHair(),
                ctx.pipeline().get(RealmAuthHandler.class).getAccount()));

        break;
    case CMSG_CHAR_DELETE:
        response = new SMSG_CHAR_DELETE(Opcodes.SMSG_CHAR_DELETE);

        ((SMSG_CHAR_DELETE) response)
                .setResult(characterService.deleteChar(((CMSG_CHAR_DELETE) request).getId(),
                        ctx.pipeline().get(RealmAuthHandler.class).getAccount(), false));

        break;

    case CMSG_PLAYER_LOGIN:
        if (characterService.loginChar(((CMSG_PLAYER_LOGIN) request).getId(),
                ctx.pipeline().get(RealmAuthHandler.class).getAccount())) {
            SMSG_LOGIN_VERIFY_WORLD packet = new SMSG_LOGIN_VERIFY_WORLD();

            /**packet.setMap(characterService.getLoggedCharacter().getFkDbcMap());
            packet.setPosX(characterService.getLoggedCharacter().getPositionX());
            packet.setPosY(characterService.getLoggedCharacter().getPositionY());
            packet.setPosZ(characterService.getLoggedCharacter().getPositionZ());
            packet.setOrientation(characterService.getLoggedCharacter().getOrientation());*/

            ctx.write(packet);

            SMSG_ACCOUNT_DATA_TIMES data = new SMSG_ACCOUNT_DATA_TIMES();

            ctx.write(data);

        } else {
            // Kick unknown client.                    
            ctx.close();
        }

        break;

    default:
        logger.error("Packet received, opcode not handled: " + request.getOpcode());
        break;
    }

    if (response != null) {
        ctx.writeAndFlush(response);
    } else {
        // Let pass this to other handlers.
        ctx.fireChannelRead(msg);
    }
}

From source file:eu.jangos.realm.network.handler.RealmAuthHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    AbstractRealmClientPacket request = (AbstractRealmClientPacket) msg;

    // By default, response is no access for a login activity.
    AbstractRealmServerPacket response = new SMSG_AUTH_RESPONSE(Opcodes.SMSG_AUTH_RESPONSE);

    logger.info(msg.toString());//from w w w. j  av  a2s.  c  o  m

    switch (request.getOpcode()) {
    case CMSG_AUTH_SESSION:
        if (ctx.channel().attr(AUTH).get() != AuthStep.STEP_AUTHING) {
            logger.error("Client is sending a CMSG_AUTH_SESSION packet again while being authenticating.");
            ctx.close();
            return;
        }

        this.cAuthSession = (CMSG_AUTH_SESSION) request;

        // Checking build number.
        if (this.cAuthSession.getBuild() < Integer.parseInt(parameterService.getParameter("minSupportedBuild"))
                || this.cAuthSession.getBuild() > Integer
                        .parseInt(parameterService.getParameter("maxSupportedBuild"))) {
            logger.debug("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount()
                    + " : Build is not supported.");
            ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_VERSION_INVALID);
            break;
        }

        // Checking account existence.
        if (!this.accountService.checkExistence(this.cAuthSession.getAccount().toUpperCase())) {
            logger.debug("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount()
                    + " : Account does not exist.");
            ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_UNKNOWN_ACCOUNT);
            break;
        }

        account = this.accountService.getAccount(this.cAuthSession.getAccount());

        // Checking if this account is the one logging into the authentication server.
        if (!account.getLastIp()
                .equals(((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress())) {
            logger.debug("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount()
                    + " : IP is not the same one than the one used to authenticate.");
            ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_FAIL_NOACCESS);
            break;
        }

        // Checking if account is locked.
        if (account.isLocked()) {
            logger.debug("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount()
                    + " : Account is locked.");
            ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_BANNED);
            break;
        }

        // Checking if account is banned -- Includes IP & Account.
        if (this.accountService.isBanned(account,
                ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress())) {
            logger.debug("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount()
                    + " : Account is banned.");
            ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_BANNED);
            break;
        }

        // At this step, we can start making the calculation.
        try {
            BigNumber K = new BigNumber(account.getSessionkey(), 16);

            if (AuthUtils.checkClientDigest(this.cAuthSession.getAccount(), seed, this.cAuthSession.getSeed(),
                    K, this.cAuthSession.getDigest())) {
                // We are happy that client could login.
                logger.info("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount()
                        + " : Account is logged in.");

                worldService.addSession(account.getId(), ctx);

                // Initializing the crypt.
                ctx.channel().attr(CRYPT).get().init(K.asByteArray());
                ctx.channel().attr(AUTH).set(AuthStep.STEP_AUTHED);
                ctx.channel().attr(ACCOUNT).set(account);

                ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_SUCCESS);

                // We send add-on data as well.
                SMSG_ADDON_INFO packet = new SMSG_ADDON_INFO();
                packet.setListAddons(((CMSG_AUTH_SESSION) request).getListAddon());
                ctx.write(packet);
            } else {
                // Well, the calculation went wrong.
                logger.info("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount()
                        + " : Can't verify the hash.");
                ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_FAIL_NOACCESS);
                break;
            }
        } catch (NoSuchAlgorithmException nsa) {
            // Something went wrong, aborting connection.
            logger.info("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount()
                    + " : Problem  to find an algorithm.");
            ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_FAIL_NOACCESS);
            break;
        }

        break;
    default:
        logger.error("Packet received, opcode not handled: " + request.getOpcode());
        response = null;
        break;
    }

    if (response != null) {
        ctx.writeAndFlush(response);
    } else {
        // Let pass this to other handlers.
        ctx.fireChannelRead(msg);
    }
}

From source file:eu.stratosphere.runtime.io.network.netty.InboundEnvelopeDecoder.java

License:Apache License

/**
 * Decodes all Envelopes contained in a Netty ByteBuf and forwards them in the pipeline.
 * Returns true and releases the buffer, if it was fully consumed. Otherwise, returns false and retains the buffer.
 * </p>/*from   w w w .  j  a va 2 s  .  c  om*/
 * In case of no buffer availability (returns false), a buffer availability listener is registered and the input
 * buffer is staged for later consumption.
 *
 * @return <code>true</code>, if buffer fully consumed, <code>false</code> otherwise
 * @throws IOException
 */
private boolean decodeBuffer(ByteBuf in, ChannelHandlerContext ctx) throws IOException {

    DecoderState decoderState;
    while ((decoderState = decodeEnvelope(in)) != DecoderState.PENDING) {
        if (decoderState == DecoderState.COMPLETE) {
            ctx.fireChannelRead(this.currentEnvelope);
            this.currentEnvelope = null;
        } else if (decoderState == DecoderState.NO_BUFFER_AVAILABLE) {
            switch (this.currentBufferProvider.registerBufferAvailabilityListener(this)) {
            case SUCCEEDED_REGISTERED:
                if (ctx.channel().config().isAutoRead()) {
                    ctx.channel().config().setAutoRead(false);

                    if (LOG.isDebugEnabled()) {
                        LOG.debug(String.format("Set channel %s auto read to false.", ctx.channel()));
                    }
                }

                this.stagedBuffer = in;
                this.stagedBuffer.retain();
                return false;

            case FAILED_BUFFER_AVAILABLE:
                continue;

            case FAILED_BUFFER_POOL_DESTROYED:
                this.bytesToSkip = skipBytes(in, this.currentBufferRequestSize);

                this.currentBufferRequestSize = 0;
                this.currentEventsBuffer = null;
                this.currentEnvelope = null;
            }
        }
    }

    if (in.isReadable()) {
        throw new IllegalStateException("Every buffer should have been fully"
                + "consumed after *successfully* decoding it (if it was not successful, "
                + "the buffer will be staged for later consumption).");
    }

    in.release();
    return true;
}

From source file:eu.xworlds.util.raknet.ConnectionHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    for (final RaknetServerListener listener : this.listeners) {
        if (listener.isBlocked(ctx, msg)) {
            ctx.fireChannelReadComplete();
        } else {//from w w w  .ja v  a2  s  .  c  o m
            ctx.fireChannelRead(msg);
        }
    }
}

From source file:eu.xworlds.util.raknet.RaknetTrace.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, RaknetMessage msg) throws Exception {
    if (msg instanceof InvalidRaknetMessage) {
        final InvalidRaknetMessage inv = (InvalidRaknetMessage) msg;
        if (inv.getEx() == null) {
            RaknetServer.LOGGER.finest("invalid/unknown raknet code from from " + inv.getSender() + " to " //$NON-NLS-1$//$NON-NLS-2$
                    + inv.getReceiver() + ": " + msg); //$NON-NLS-1$                
        } else {//from   w  w w . ja  va 2s.  c  om
            RaknetServer.LOGGER.log(Level.FINEST, "exception analyzing raknet message from " + inv.getSender() //$NON-NLS-1$
                    + " to " + inv.getReceiver() + ": " + msg, inv.getEx()); //$NON-NLS-1$//$NON-NLS-2$
        }
    } else if (msg instanceof TargetedMessage) {
        final TargetedMessage tmsg = (TargetedMessage) msg;
        RaknetServer.LOGGER
                .finest("incoming data from " + tmsg.getSender() + " to " + tmsg.getReceiver() + ": " + msg); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
    } else {
        RaknetServer.LOGGER.finest("Incoming data package " + msg); //$NON-NLS-1$
    }
    ctx.fireChannelRead(msg);
}

From source file:example.http2.helloworld.server.Http2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0
 */// ww  w.j  a va 2s .c  o  m
private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();
    final HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec,
            upgradeCodecFactory);
    final CleartextHttp2ServerUpgradeHandler cleartextHttp2ServerUpgradeHandler = new CleartextHttp2ServerUpgradeHandler(
            sourceCodec, upgradeHandler, new HelloWorldHttp2HandlerBuilder().build());

    p.addLast(cleartextHttp2ServerUpgradeHandler);
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)");
            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null,
                    new HelloWorldHttp1Handler("Direct. No Upgrade Attempted."));
            pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
            ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
        }
    });

    p.addLast(new UserEventLogger());
}

From source file:gedi.oml.remote.Pipeline.Receiver.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof RemotePipelineData)) {
        ctx.fireChannelRead(msg);
        return;//  w w  w .  j av  a 2s  . com
    }

    RemotePipelineData data = (RemotePipelineData) msg;

    boolean release = true;
    try {

        synchronized (location) {
            if (data.getId().equals(id))
                answer.offer(data);
            else {
                release = false;
                ctx.fireChannelRead(msg);
            }

        }

    } finally {
        if (release) {
            ReferenceCountUtil.release(msg);
        }
    }
}