Example usage for io.netty.channel ChannelHandlerContext attr

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

Introduction

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

Prototype

@Deprecated
@Override
<T> Attribute<T> attr(AttributeKey<T> key);

Source Link

Usage

From source file:de.ruedigermoeller.reallive.client.wsgate.WebSocketGateChannelHandler.java

License:Open Source License

/**
 * Calls {@link io.netty.channel.ChannelHandlerContext#fireChannelRead(Object)} to forward
 * to the next {@link io.netty.channel.ChannelInboundHandler} in the {@link io.netty.channel.ChannelPipeline}.
 * <p/>/*from   w  w  w .  j  av a  2 s .  c  o  m*/
 * Sub-classes may override this method to change behavior.
 *
 * @param ctx
 * @param msg
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // Check for closing frame
    if (msg instanceof CloseWebSocketFrame) {
        webSocketGate.getHandshaker().close(ctx.channel(), (CloseWebSocketFrame) msg);
        return;
    }
    if (msg instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(((PingWebSocketFrame) msg).content()));
        return;
    }
    if (!(msg instanceof TextWebSocketFrame)) {
        throw new UnsupportedOperationException(
                String.format("%s frame types not supported", msg.getClass().getName()));
    }
    if (msg instanceof TextWebSocketFrame) {
        WSGSession wsgs = ctx.attr(webSocketGate.session).get();
        TextWebSocketFrame wf = (TextWebSocketFrame) msg;
        BasicDsonMsg dsonMsg = null;
        try {
            System.out.println(wf.text());
            dsonMsg = (BasicDsonMsg) Dson.getInstance().readObject(wf.text());
            dsonMsg.setCtx(ctx);
        } catch (Exception ex) {
            ctx.writeAndFlush(new TextWebSocketFrame(
                    new ErrorMsg(1, "failed to parse request:" + ex.getMessage(), 0, 0).toDson()));
            ex.printStackTrace();
            return;
        }

        if (dsonMsg instanceof AuthReq == false && !wsgs.isAuthenticated()) {
            ctx.writeAndFlush(new TextWebSocketFrame(
                    new ErrorMsg(2, "not authenticated", 0, dsonMsg.getReqId()).toDson()));
        } else {
            wsgs.processRequest(dsonMsg);
            //                    ChannelFuture channelFuture = ctx.writeAndFlush(new TextWebSocketFrame("Hello from java"));
            //                    channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
            //                        @Override
            //                        public void operationComplete(ChannelFuture future) throws Exception {
            //                            System.out.println("send success");
            //                        }
            //                    });
        }
    } else
        System.out.println("read " + msg);
    super.channelRead(ctx, msg);
}

From source file:de.unipassau.isl.evs.ssh.core.messaging.IncomingDispatcher.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object in) throws Exception {
    if (in instanceof Message.AddressedMessage) {
        final DeviceID peerID = ctx.attr(ATTR_PEER_ID).get();
        if (peerID == null) {
            ctx.close();//from  w w  w .ja v  a  2s .  c  o m
            throw new IllegalStateException("Unauthenticated peer");
        }
        final Message.AddressedMessage msg = (Message.AddressedMessage) in;
        if (!Objects.equals(msg.getFromID(), peerID)) { //signature is already verified by SignatureChecker
            ctx.close();
            throw new SignatureException("Connected to Device with ID " + peerID + " but received message "
                    + "seemingly from " + msg.getFromID());
        }
        if (dispatch(msg))
            return; //if no Handler can handle the Message, forward it in the pipeline
    }
    super.channelRead(ctx, in);
}

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}.//from  ww w.j  a v  a 2  s.  c om
 */
@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. j a v  a2s  .c o 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

private void handleServerAuthenticationResponse(ChannelHandlerContext ctx,
        HandshakePacket.ServerAuthenticationResponse msg)
        throws HandshakeException, CertificateException, NoSuchAlgorithmException, KeyStoreException {
    setState(State.EXPECT_STATE, State.STATE_RECEIVED);

    final NamingManager namingManager = container.require(NamingManager.KEY);
    if (msg.isAuthenticated) {
        if (!namingManager.isMasterIDKnown()) {
            Log.i(TAG, "Got State: authenticated from unverified Master, checking token");
            if (checkSentPassiveRegistrationToken(msg)) {
                Log.i(TAG, "Master sent correct token, saving MasterID and Certificate");
                namingManager.setMasterCertificate(ctx.attr(ATTR_PEER_CERT).get());
            } else {
                setState(State.STATE_RECEIVED, State.FAILED);
                handshakeFailed(ctx, "Master is not verified yet sent invalid token");
                return;
            }//w w  w .jav  a 2  s.c  o m
        }
        if (!namingManager.isMasterKnown()) {
            setState(State.STATE_RECEIVED, State.FAILED);
            handshakeFailed(ctx, "Master did not authenticate itself (and is not known yet)");
            return;
        }

        setState(State.STATE_RECEIVED, State.FINISHED);
        ctx.attr(ATTR_HANDSHAKE_FINISHED).set(true);
        ctx.attr(ATTR_LOCAL_CONNECTION).set(msg.isConnectionLocal);
        Log.i(TAG, "Got State: authenticated, handshake successful");
        handshakeSuccessful(ctx);
    } else {
        final byte[] token = container.require(Client.KEY).getActiveRegistrationTokenBytes();
        final boolean canRegister = !triedRegister && token.length == DeviceConnectInformation.TOKEN_LENGTH;
        if (canRegister) {
            triedRegister = true;
            setState(State.STATE_RECEIVED, State.EXPECT_STATE);
            Log.i(TAG, "Got State: unauthenticated, trying Registration");

            ctx.writeAndFlush(new HandshakePacket.ActiveRegistrationRequest(token))
                    .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
        } else {
            setState(State.STATE_RECEIVED, State.FAILED);
            Log.w(TAG, "Got State: unauthenticated and registration is not possible, handshake failed");
            handshakeFailed(ctx, msg.message);
        }
    }
}

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

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Log.v(TAG, "channelActive " + ctx);
    super.channelActive(ctx);
    assert container.require(NamingManager.KEY).isMaster();
    setState(ctx, null, State.EXPECT_HELLO);
    final boolean isLocal = ((InetSocketAddress) ctx.channel().localAddress()).getPort() == server
            .getLocalPort();//from w w w. j  av  a  2s .  c om
    ctx.attr(ATTR_LOCAL_CONNECTION).set(isLocal);
    Log.v(TAG, "Channel to " + (isLocal ? "local" : "internet") + " device open, waiting for Client Hello");
    setChapChallenge(ctx, new byte[HandshakePacket.CHAP.CHALLENGE_LENGTH]);
}

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

private void checkAuthentication(ChannelHandlerContext ctx) throws HandshakeException {
    setState(ctx, State.CHECK_AUTH, State.CHECK_AUTH);

    final DeviceID deviceID = ctx.attr(CoreConstants.NettyConstants.ATTR_PEER_ID).get();
    final Slave slave = container.require(SlaveController.KEY).getSlave(deviceID);
    final UserDevice userDevice = container.require(UserManagementController.KEY).getUserDevice(deviceID);
    if (slave != null || userDevice != null) {
        setState(ctx, State.CHECK_AUTH, State.FINISHED);
        Log.i(TAG, "Device " + deviceID + " is registered as "
                + (slave != null ? "Slave " + slave : "UserDevice " + userDevice));

        final byte[] passiveRegistrationToken = slave == null ? null : slave.getPassiveRegistrationToken();
        final boolean isConnectionLocal = ctx.attr(ATTR_LOCAL_CONNECTION).get() == Boolean.TRUE;
        ctx.writeAndFlush(// ww  w .j a va 2  s.co m
                ServerAuthenticationResponse.authenticated(null, passiveRegistrationToken, isConnectionLocal))
                .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);

        handshakeSuccessful(ctx);
    } else {
        setState(ctx, State.CHECK_AUTH, State.EXPECT_REGISTER);
        Log.i(TAG, "Device " + deviceID + " is not registered, requesting registration");

        ctx.writeAndFlush(ServerAuthenticationResponse.unauthenticated("Unknown Client, please register."))
                .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
    }
}

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

License:Open Source License

private void handleActiveRegistrationRequest(ChannelHandlerContext ctx,
        HandshakePacket.ActiveRegistrationRequest msg) throws HandshakeException {
    setState(ctx, State.EXPECT_REGISTER, State.CHECK_AUTH);

    // send client register info to handler
    boolean success = container.require(MasterRegisterDeviceHandler.KEY).registerDevice(
            ctx.attr(CoreConstants.NettyConstants.ATTR_PEER_CERT).get(), msg.activeRegistrationToken);

    if (success) {
        Log.v(TAG, "Accepted registration request from "
                + ctx.attr(CoreConstants.NettyConstants.ATTR_PEER_ID).get());
        checkAuthentication(ctx);// w w  w.j a v  a 2s .c o m
    } else {
        setState(ctx, State.CHECK_AUTH, State.EXPECT_REGISTER);
        Log.v(TAG, "Rejected registration request from "
                + ctx.attr(CoreConstants.NettyConstants.ATTR_PEER_ID).get());

        ctx.writeAndFlush(ServerAuthenticationResponse
                .unauthenticated("Client registration rejected, closing connection."))
                .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
    }
}

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);
    }//from  ww  w  .  ja v  a  2 s.co  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());
    }
}