Example usage for io.netty.channel ChannelHandlerContext pipeline

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

Introduction

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

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline

Usage

From source file:de.felix_klauke.pegasus.client.handler.PacketHandler.java

License:Apache License

/**
 *
 *  The Method everything is about. All incoming data will be handled by this method.
 *  It will check all received data. When the object containing this data is an instance
 *  of {@link de.felix_klauke.pegasus.protocol.Packet}. If that is true the packet will be
 *  passed to the method that will handle all incoming packets:
 *  {@link de.felix_klauke.pegasus.client.handler.PacketHandler#handlePacket(Channel, Packet)}
 *
 * @param ctx the context of the channel that received the data
 * @param msg the data the channel received
 * @throws Exception the exception that occurs when receiving data fails
 *//*from w  w  w. j  av a  2s  .c o  m*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof Packet) {
        handlePacket(ctx.pipeline().channel(), (Packet) msg);
    }
}

From source file:de.felix_klauke.pegasus.server.handler.PacketHandler.java

License:Apache License

/**
 *
 *  The Method everything is about. All incoming data will be handled by this method.
 *  It will check all received data. When the object containing this data is an instance
 *  of {@link de.felix_klauke.pegasus.protocol.Packet}.
 *
 *  This is the Main Handler for Handshakes.
 *
 *  The other packets will be//from  w w w  .j a  v  a 2  s . c  o  m
 *  passed to the method that will handle all incoming packets:
 *  {@link de.felix_klauke.pegasus.server.handler.PacketHandler#handlePacket(Channel, Packet)}
 *
 * @param ctx the context of the channel that received the data
 * @param msg the data the channel received
 * @throws Exception the exception that occurs when receiving data fails
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    logger.info("Handling incoming data.");

    User user = userManager.getUser(ctx.pipeline().channel());
    if (user == null) {
        System.out.println(msg.getClass());
        if (msg instanceof PacketHandshake) {
            PacketHandshake packetHandshake = (PacketHandshake) msg;

            logger.info("Authenticating: " + packetHandshake.getUsername() + " with password "
                    + packetHandshake.getPassword());

            boolean success = userManager.authUser(packetHandshake.getUsername(),
                    packetHandshake.getPassword());

            PacketHandshakeResponse response = new PacketHandshakeResponse();
            response.setResult(success ? HandshakeResult.SUCCESS : HandshakeResult.FAILURE);
            if (success) {
                userManager.createUser(packetHandshake.getUsername(), ctx.channel());
            }
            ChannelFuture future = ctx.channel().writeAndFlush(response);
            future.addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(Future<? super Void> future) throws Exception {
                    if (!future.isSuccess()) {
                        future.cause().printStackTrace();
                    }
                }
            });
            return;
        }
        ctx.pipeline().channel().close();
        return;
    }

    if (msg instanceof Packet) {
        handlePacket(ctx.pipeline().channel(), (Packet) msg);
    }
}

From source file:de.jpaw.bonaparte.netty.testServer.TestServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, BonaPortable request) throws Exception {
    // String cipher;
    SslHandler sslH = ctx.pipeline().get(SslHandler.class);
    if (sslH != null) {
        SSLSession session = sslH.engine().getSession();
        // cipher = " (with cipher " + session.getCipherSuite() + ")";
        SessionInfo.logSessionInfo(session, "Client");
    } else {//from  w  ww.j a  v  a2s . com
        // cipher = " (unencrypted)";
    }
    // logger.info("Received an object of type " + request.getClass().getCanonicalName() + cipher);
    Request myRequest = (Request) request;
    Response myResponse = new Response();

    myResponse.setSerialNo(myRequest.getSerialNo());
    myResponse.setUniqueId(myRequest.getUniqueId());
    myResponse.setThreadNo(thisThreadId);
    myResponse.setSerialInThread(0); // counterInThread.incrementAndGet());  => locking issue!
    myResponse.setWhenReceiced(new LocalDateTime());

    if (myRequest.getDuration() > 0) {
        Thread.sleep(myRequest.getDuration());
    }

    ctx.write(myResponse);
    ctx.flush();
}

From source file:de.unipassau.isl.evs.ssh.core.network.ClientHandshakeHandler.java

License:Open Source License

/**
 * Called once the TCP connection is established.
 * Configures the per-connection pipeline that is responsible for handling incoming and outgoing data.
 * After an incoming packet is decrypted, decoded and verified,
 * it will be sent to its target {@link de.unipassau.isl.evs.ssh.core.handler.MessageHandler}
 * by the {@link IncomingDispatcher}./* ww  w . j  a va 2s  . co m*/
 */
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    Log.v(TAG, "channelRegistered " + ctx);
    ctx.attr(ATTR_HANDSHAKE_FINISHED).set(false);

    // Add (de-)serialization Handlers before this Handler
    ctx.pipeline().addBefore(ctx.name(), ObjectEncoder.class.getSimpleName(), new ObjectEncoder());
    ctx.pipeline().addBefore(ctx.name(), ObjectDecoder.class.getSimpleName(),
            new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(getClass().getClassLoader())));
    ctx.pipeline().addBefore(ctx.name(), LoggingHandler.class.getSimpleName(),
            new LoggingHandler(LogLevel.TRACE));

    // Timeout Handler
    ctx.pipeline().addBefore(ctx.name(), IdleStateHandler.class.getSimpleName(),
            new IdleStateHandler(READER_IDLE_TIME, WRITER_IDLE_TIME, ALL_IDLE_TIME));
    ctx.pipeline().addBefore(ctx.name(), TimeoutHandler.class.getSimpleName(), new TimeoutHandler());

    // Add exception handler
    ctx.pipeline().addAfter(ctx.name(), PipelinePlug.class.getSimpleName(), new PipelinePlug());

    super.channelRegistered(ctx);
    Log.v(TAG, "Pipeline after register: " + ctx.pipeline());
}

From source file:de.unipassau.isl.evs.ssh.core.network.ClientHandshakeHandler.java

License:Open Source License

private void handleHello(ChannelHandlerContext ctx, HandshakePacket.Hello msg) throws GeneralSecurityException {
    setState(State.EXPECT_HELLO, State.EXPECT_CHAP);
    Log.v(TAG, "Got Server Hello, sending 1. CHAP and awaiting 2. CHAP as response");
    assert msg.isMaster;

    // import data from Hello packet
    final NamingManager namingManager = container.require(NamingManager.KEY);
    final DeviceID certID = DeviceID.fromCertificate(msg.certificate);
    // verify the data if the Master is already known, otherwise the registration token will be checked later
    if (namingManager.isMasterIDKnown()) {
        final DeviceID masterID = namingManager.getMasterID();
        if (!masterID.equals(certID)) {
            throw new HandshakeException(
                    "Server DeviceID " + certID + " did not match my MasterID " + masterID);
        }/*from   w  w  w.ja  v a2 s . co m*/
        if (!namingManager.isMasterKnown()) {
            // first connection to master, register certificate for already known DeviceID
            namingManager.setMasterCertificate(msg.certificate);
        }
    }

    // set channel attributes
    ctx.attr(ATTR_PEER_CERT).set(msg.certificate);
    ctx.attr(ATTR_PEER_ID).set(certID);

    // add Security handlers
    final PublicKey remotePublicKey = msg.certificate.getPublicKey();
    final PrivateKey localPrivateKey = container.require(KeyStoreController.KEY).getOwnPrivateKey();
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), Encrypter.class.getSimpleName(),
            new Encrypter(remotePublicKey));
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), Decrypter.class.getSimpleName(),
            new Decrypter(localPrivateKey));
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), SignatureChecker.class.getSimpleName(),
            new SignatureChecker(remotePublicKey));
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), SignatureGenerator.class.getSimpleName(),
            new SignatureGenerator(localPrivateKey));

    // and send the initial CHAP packet to the master
    new SecureRandom().nextBytes(chapChallenge);
    ctx.writeAndFlush(new HandshakePacket.CHAP(chapChallenge, null))
            .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}

From source file:de.unipassau.isl.evs.ssh.core.network.ClientHandshakeHandler.java

License:Open Source License

protected void handshakeSuccessful(ChannelHandlerContext ctx) {
    if (state != State.FINISHED) {
        throw new IllegalStateException("Handshake not finished: " + state);
    }// w w  w .  jav a2s . co  m

    // allow pings
    TimeoutHandler.setPingEnabled(ctx.channel(), true);
    // add Dispatcher
    ctx.pipeline().addBefore(ctx.name(), IncomingDispatcher.class.getSimpleName(),
            container.require(IncomingDispatcher.KEY));
    // Logging is handled by IncomingDispatcher and OutgoingRouter
    ctx.pipeline().remove(LoggingHandler.class.getSimpleName());
    // remove HandshakeHandler
    ctx.pipeline().remove(this);

    Log.v(TAG, "Handshake successful, current Pipeline: " + ctx.pipeline());
    container.require(Client.KEY).notifyClientConnected();
}

From source file:de.unipassau.isl.evs.ssh.master.network.ServerHandshakeHandler.java

License:Open Source License

/**
 * Configures the per-connection pipeline that is responsible for handling incoming and outgoing data.
 * After an incoming packet is decrypted, decoded and verified,
 * it will be sent to its target {@link MessageHandler}
 * by the {@link IncomingDispatcher}./*  ww  w .  j av a  2  s  .  c  om*/
 */
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    Log.v(TAG, "channelRegistered " + ctx);
    if (container == null) {
        //Do not accept new connections after the Server has been shut down
        Log.v(TAG, "channelRegistered:closed");
        ctx.close();
        return;
    }

    // Add (de-)serialization Handlers before this Handler
    ctx.pipeline().addBefore(ctx.name(), ObjectEncoder.class.getSimpleName(), new ObjectEncoder());
    ctx.pipeline().addBefore(ctx.name(), ObjectDecoder.class.getSimpleName(),
            new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(getClass().getClassLoader())));
    ctx.pipeline().addBefore(ctx.name(), LoggingHandler.class.getSimpleName(),
            new LoggingHandler(LogLevel.TRACE));

    // Timeout Handler
    ctx.pipeline().addBefore(ctx.name(), IdleStateHandler.class.getSimpleName(),
            new IdleStateHandler(READER_IDLE_TIME, WRITER_IDLE_TIME, ALL_IDLE_TIME));
    ctx.pipeline().addBefore(ctx.name(), TimeoutHandler.class.getSimpleName(), new TimeoutHandler());

    // Add exception handler
    ctx.pipeline().addLast(PipelinePlug.class.getSimpleName(), new PipelinePlug());

    super.channelRegistered(ctx);
    Log.v(TAG, "Pipeline after register: " + ctx.pipeline());
}

From source file:de.unipassau.isl.evs.ssh.master.network.ServerHandshakeHandler.java

License:Open Source License

private void handleHello(ChannelHandlerContext ctx, HandshakePacket.Hello msg) throws GeneralSecurityException {
    setState(ctx, State.EXPECT_HELLO, State.EXPECT_INITIAL_CHAP);
    Log.v(TAG, "Got Client Hello, sending Server Hello and awaiting 1. CHAP as response");

    assert !msg.isMaster;
    final X509Certificate deviceCertificate = msg.certificate;
    ctx.attr(CoreConstants.NettyConstants.ATTR_PEER_CERT).set(deviceCertificate);
    final DeviceID deviceID = DeviceID.fromCertificate(deviceCertificate);
    ctx.attr(CoreConstants.NettyConstants.ATTR_PEER_ID).set(deviceID);
    Log.v(TAG, "Client " + deviceID + " connected, checking authentication");

    final X509Certificate masterCert = container.require(NamingManager.KEY).getMasterCertificate();
    final boolean isMaster = container.require(NamingManager.KEY).isMaster();
    ctx.writeAndFlush(new HandshakePacket.Hello(masterCert, isMaster))
            .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);

    // add Security handlers
    final PublicKey remotePublicKey = deviceCertificate.getPublicKey();
    final PrivateKey localPrivateKey = container.require(KeyStoreController.KEY).getOwnPrivateKey();
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), Encrypter.class.getSimpleName(),
            new Encrypter(remotePublicKey));
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), Decrypter.class.getSimpleName(),
            new Decrypter(localPrivateKey));
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), SignatureChecker.class.getSimpleName(),
            new SignatureChecker(remotePublicKey));
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), SignatureGenerator.class.getSimpleName(),
            new SignatureGenerator(localPrivateKey));
}

From source file:de.unipassau.isl.evs.ssh.master.network.ServerHandshakeHandler.java

License:Open Source License

protected void handshakeSuccessful(ChannelHandlerContext ctx) {
    final State state = getState(ctx);
    if (state != State.FINISHED) {
        throw new IllegalStateException("Handshake not finished: " + state);
    }//w  w  w  .  j  av  a 2  s  .c  o  m
    final DeviceID deviceID = ctx.channel().attr(ATTR_PEER_ID).get();

    // allow pings
    TimeoutHandler.setPingEnabled(ctx.channel(), true);
    // add Dispatcher
    ctx.pipeline().addBefore(ctx.name(), IncomingDispatcher.class.getSimpleName(),
            container.require(IncomingDispatcher.KEY));
    // Logging is handled by IncomingDispatcher and OutgoingRouter
    ctx.pipeline().remove(LoggingHandler.class.getSimpleName());
    // remove HandshakeHandler
    ctx.pipeline().remove(this);

    // Register connection
    server.getActiveChannels().add(ctx.channel());
    Log.i(TAG, "Handshake with " + deviceID + " successful, current Pipeline: " + ctx.pipeline());

    Message message = new Message(
            new DeviceConnectedPayload(deviceID, ctx.channel(), ctx.attr(ATTR_LOCAL_CONNECTION).get()));
    container.require(OutgoingRouter.KEY).sendMessageLocal(RoutingKeys.MASTER_DEVICE_CONNECTED, message);

    ctx.channel().closeFuture().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            for (Server.ServerConnectionListener listener : server.listeners) {
                listener.onClientConnected(future.channel());
            }
        }
    });

    for (Server.ServerConnectionListener listener : server.listeners) {
        listener.onClientConnected(ctx.channel());
    }
}

From source file:diskCacheV111.doors.NettyLineBasedDoor.java

License:Open Source License

protected void start(ChannelHandlerContext ctx) throws Exception {
    LineWriter writer = ctx::writeAndFlush;

    clientAddress = remoteAddress.getAddress().getHostAddress();
    LOGGER.debug("Client host: {}", clientAddress);

    interpreter = factory.create(this, getNucleus().getThisAddress(), remoteAddress, proxyAddress, localAddress,
            writer, executor, poolManager, idResolverFactory, spaceDescriptionCache, spaceLookupCache);
    if (interpreter instanceof CellCommandListener) {
        addCommandListener(interpreter);
    }//from  w w w.  ja  v a  2 s .c om
    if (interpreter instanceof CellMessageReceiver) {
        addMessageListener((CellMessageReceiver) interpreter);
    }
    if (interpreter instanceof TlsStarter) {
        ((TlsStarter) interpreter).setTlsStarter(e -> {
            e.setUseClientMode(false);
            ctx.pipeline().addFirst("tls", new SslHandler(e, true));
        });
    }
    start().get(); // Blocking to prevent that we process any commands before the cell is alive
}