List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:org.dcache.xrootd.pool.XrootdPoolRequestHandler.java
License:Open Source License
@Override protected XrootdResponse<LoginRequest> doOnLogin(ChannelHandlerContext ctx, LoginRequest msg) { XrootdSessionIdentifier sessionId = new XrootdSessionIdentifier(); /*/*from www . j a va 2 s .c o m*/ * It is only necessary to tell the client to observe the unix protocol * if security is on and signed hashes are being enforced. * * We also need to swap the decoder. */ String sec; if (signingPolicy.isSigningOn() && signingPolicy.isForceSigning()) { sec = "&P=unix"; ctx.pipeline().addAfter("decoder", "sigverDecoder", new XrootdSigverDecoder(signingPolicy, null)); ctx.pipeline().remove("decoder"); _log.debug("swapped decoder for sigverDecoder."); } else { sec = ""; } return new LoginResponse(msg, sessionId, sec); }
From source file:org.dcache.xrootd.tpc.TpcClientConnectHandler.java
License:Open Source License
@Override protected void doOnLoginResponse(ChannelHandlerContext ctx, InboundLoginResponse response) throws XrootdException { int status = response.getStatus(); ChannelId id = ctx.channel().id();/* w ww . ja v a 2s . c o m*/ int streamId = client.getStreamId(); XrootdTpcInfo tpcInfo = client.getInfo(); LOGGER.trace("Login response on {}, channel {}, stream {}," + " received; sessionId {}, status {}.", tpcInfo.getSrc(), id, streamId, response.getSessionId(), status); if (status == kXR_ok) { client.setSessionId(response.getSessionId()); List<SecurityInfo> protocols = response.getProtocols(); Map<String, ChannelHandler> handlers = client.getAuthnHandlers(); /* * Name of this handler */ String last = "connect"; ChannelPipeline pipeline = ctx.pipeline(); for (SecurityInfo protocol : protocols) { String name = protocol.getProtocol(); ChannelHandler handler = handlers.get(name); if (handler != null) { pipeline.addAfter(last, name, handler); } LOGGER.trace( "Login to {}, channel {}, stream {}, sessionId {}, " + "adding {} handler to pipeline.", tpcInfo.getSrc(), id, streamId, client.getSessionId(), name); last = name; } LOGGER.trace("Login to {}, channel {}, stream {}," + " succeeded; sessionId {}; " + "passing to next handler.", tpcInfo.getSrc(), id, streamId, client.getSessionId()); ctx.fireChannelRead(response); } else { String error = String.format("Login to %s failed: status %d.", tpcInfo.getSrc(), status); throw new XrootdException(kXR_error, error); } }
From source file:org.eclipse.milo.opcua.stack.client.handlers.UaTcpClientAcknowledgeHandler.java
License:Open Source License
private void onAcknowledge(ChannelHandlerContext ctx, ByteBuf buffer) { if (helloTimeout != null && !helloTimeout.cancel()) { helloTimeout = null;/*from ww w . j av a 2s .c om*/ handshakeFuture.completeExceptionally( new UaException(StatusCodes.Bad_Timeout, "timed out waiting for acknowledge")); ctx.close(); return; } logger.debug("Received Acknowledge message on channel={}.", ctx.channel()); buffer.skipBytes(3 + 1 + 4); // Skip messageType, chunkType, and messageSize AcknowledgeMessage acknowledge = AcknowledgeMessage.decode(buffer); long remoteProtocolVersion = acknowledge.getProtocolVersion(); long remoteReceiveBufferSize = acknowledge.getReceiveBufferSize(); long remoteSendBufferSize = acknowledge.getSendBufferSize(); long remoteMaxMessageSize = acknowledge.getMaxMessageSize(); long remoteMaxChunkCount = acknowledge.getMaxChunkCount(); if (PROTOCOL_VERSION > remoteProtocolVersion) { logger.warn("Client protocol version ({}) does not match server protocol version ({}).", PROTOCOL_VERSION, remoteProtocolVersion); } ChannelConfig config = client.getChannelConfig(); /* Our receive buffer size is determined by the remote send buffer size. */ long localReceiveBufferSize = Math.min(remoteSendBufferSize, config.getMaxChunkSize()); /* Our send buffer size is determined by the remote receive buffer size. */ long localSendBufferSize = Math.min(remoteReceiveBufferSize, config.getMaxChunkSize()); /* Max message size the remote can send us; not influenced by remote configuration. */ long localMaxMessageSize = config.getMaxMessageSize(); /* Max chunk count the remote can send us; not influenced by remote configuration. */ long localMaxChunkCount = config.getMaxChunkCount(); ChannelParameters parameters = new ChannelParameters(Ints.saturatedCast(localMaxMessageSize), Ints.saturatedCast(localReceiveBufferSize), Ints.saturatedCast(localSendBufferSize), Ints.saturatedCast(localMaxChunkCount), Ints.saturatedCast(remoteMaxMessageSize), Ints.saturatedCast(remoteReceiveBufferSize), Ints.saturatedCast(remoteSendBufferSize), Ints.saturatedCast(remoteMaxChunkCount)); ctx.channel().attr(KEY_AWAITING_HANDSHAKE).set(awaitingHandshake); ctx.executor().execute(() -> { int maxArrayLength = client.getChannelConfig().getMaxArrayLength(); int maxStringLength = client.getChannelConfig().getMaxStringLength(); SerializationQueue serializationQueue = new SerializationQueue(client.getConfig().getExecutor(), parameters, maxArrayLength, maxStringLength); UaTcpClientMessageHandler handler = new UaTcpClientMessageHandler(client, secureChannel, serializationQueue, handshakeFuture); ctx.pipeline().addLast(handler); }); }
From source file:org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientAcknowledgeHandler.java
License:Open Source License
private void onAcknowledge(ChannelHandlerContext ctx, ByteBuf buffer) { if (helloTimeout != null && !helloTimeout.cancel()) { helloTimeout = null;//from w ww.java 2s .c o m handshakeFuture.completeExceptionally( new UaException(StatusCodes.Bad_Timeout, "timed out waiting for acknowledge")); ctx.close(); return; } logger.debug("Received Acknowledge message on channel={}.", ctx.channel()); buffer.skipBytes(3 + 1 + 4); // Skip messageType, chunkType, and messageSize AcknowledgeMessage acknowledge = AcknowledgeMessage.decode(buffer); long remoteProtocolVersion = acknowledge.getProtocolVersion(); long remoteReceiveBufferSize = acknowledge.getReceiveBufferSize(); long remoteSendBufferSize = acknowledge.getSendBufferSize(); long remoteMaxMessageSize = acknowledge.getMaxMessageSize(); long remoteMaxChunkCount = acknowledge.getMaxChunkCount(); if (PROTOCOL_VERSION > remoteProtocolVersion) { logger.warn("Client protocol version ({}) does not match server protocol version ({}).", PROTOCOL_VERSION, remoteProtocolVersion); } MessageLimits messageLimits = config.getMessageLimits(); /* Our receive buffer size is determined by the remote send buffer size. */ long localReceiveBufferSize = Math.min(remoteSendBufferSize, messageLimits.getMaxChunkSize()); /* Our send buffer size is determined by the remote receive buffer size. */ long localSendBufferSize = Math.min(remoteReceiveBufferSize, messageLimits.getMaxChunkSize()); /* Max message size the remote can send us; not influenced by remote configuration. */ long localMaxMessageSize = messageLimits.getMaxMessageSize(); /* Max chunk count the remote can send us; not influenced by remote configuration. */ long localMaxChunkCount = messageLimits.getMaxChunkCount(); ChannelParameters parameters = new ChannelParameters(Ints.saturatedCast(localMaxMessageSize), Ints.saturatedCast(localReceiveBufferSize), Ints.saturatedCast(localSendBufferSize), Ints.saturatedCast(localMaxChunkCount), Ints.saturatedCast(remoteMaxMessageSize), Ints.saturatedCast(remoteReceiveBufferSize), Ints.saturatedCast(remoteSendBufferSize), Ints.saturatedCast(remoteMaxChunkCount)); ctx.channel().attr(KEY_AWAITING_HANDSHAKE).set(awaitingHandshake); ctx.executor().execute(() -> { SerializationQueue serializationQueue = new SerializationQueue(config.getExecutor(), parameters, config.getEncodingLimits()); UascClientMessageHandler handler = new UascClientMessageHandler(config, secureChannel, serializationQueue, handshakeFuture); ctx.pipeline().addLast(handler); }); }
From source file:org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler.java
License:Open Source License
private void installSecurityToken(ChannelHandlerContext ctx, OpenSecureChannelResponse response) { ChannelSecurity.SecurityKeys newKeys = null; if (response.getServerProtocolVersion().longValue() < PROTOCOL_VERSION) { throw new UaRuntimeException(StatusCodes.Bad_ProtocolVersionUnsupported, "server protocol version unsupported: " + response.getServerProtocolVersion()); }/*from w w w.j av a2 s . c o m*/ ChannelSecurityToken newToken = response.getSecurityToken(); if (secureChannel.isSymmetricSigningEnabled()) { secureChannel.setRemoteNonce(response.getServerNonce()); newKeys = ChannelSecurity.generateKeyPair(secureChannel, secureChannel.getLocalNonce(), secureChannel.getRemoteNonce()); } ChannelSecurity oldSecrets = secureChannel.getChannelSecurity(); ChannelSecurity.SecurityKeys oldKeys = oldSecrets != null ? oldSecrets.getCurrentKeys() : null; ChannelSecurityToken oldToken = oldSecrets != null ? oldSecrets.getCurrentToken() : null; secureChannel.setChannelSecurity(new ChannelSecurity(newKeys, newToken, oldKeys, oldToken)); DateTime createdAt = response.getSecurityToken().getCreatedAt(); long revisedLifetime = response.getSecurityToken().getRevisedLifetime().longValue(); if (revisedLifetime > 0) { long renewAt = (long) (revisedLifetime * 0.75); renewFuture = ctx.executor().schedule( () -> sendOpenSecureChannelRequest(ctx, SecurityTokenRequestType.Renew), renewAt, TimeUnit.MILLISECONDS); } else { logger.warn("Server revised secure channel lifetime to 0; renewal will not occur."); } ctx.executor().execute(() -> { // SecureChannel is ready; remove the acknowledge handler. if (ctx.pipeline().get(UascClientAcknowledgeHandler.class) != null) { ctx.pipeline().remove(UascClientAcknowledgeHandler.class); } }); ChannelSecurity channelSecurity = secureChannel.getChannelSecurity(); long currentTokenId = channelSecurity.getCurrentToken().getTokenId().longValue(); long previousTokenId = channelSecurity.getPreviousToken().map(t -> t.getTokenId().longValue()).orElse(-1L); logger.debug("SecureChannel id={}, currentTokenId={}, previousTokenId={}, lifetime={}ms, createdAt={}", secureChannel.getChannelId(), currentTokenId, previousTokenId, revisedLifetime, createdAt); }
From source file:org.eclipse.milo.opcua.stack.client.transport.websocket.OpcClientWebSocketBinaryFrameCodec.java
License:Open Source License
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception { if (event instanceof ClientHandshakeStateEvent) { logger.debug("WebSocket handshake event: " + event); if (event == ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) { ctx.pipeline().addLast(new UascClientAcknowledgeHandler(config, handshake)); }//from w w w . j a v a2 s . c o m } }
From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerAsymmetricHandler.java
License:Open Source License
private void sendOpenSecureChannelResponse(ChannelHandlerContext ctx, long requestId, OpenSecureChannelRequest request) { serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.pooledBuffer(); try {//from ww w . j av a 2 s .c om OpenSecureChannelResponse response = openSecureChannel(ctx, request); binaryEncoder.setBuffer(messageBuffer); binaryEncoder.writeMessage(null, response); checkMessageSize(messageBuffer); chunkEncoder.encodeAsymmetric(secureChannel, requestId, messageBuffer, MessageType.OpenSecureChannel, new ChunkEncoder.Callback() { @Override public void onEncodingError(UaException ex) { logger.error("Error encoding OpenSecureChannelResponse: {}", ex.getMessage(), ex); ctx.fireExceptionCaught(ex); } @Override public void onMessageEncoded(List<ByteBuf> messageChunks, long requestId) { if (!symmetricHandlerAdded) { UascServerSymmetricHandler symmetricHandler = new UascServerSymmetricHandler( stackServer, serializationQueue, secureChannel); ctx.pipeline().addBefore(ctx.name(), null, symmetricHandler); symmetricHandlerAdded = true; } CompositeByteBuf chunkComposite = BufferUtil.compositeBuffer(); for (ByteBuf chunk : messageChunks) { chunkComposite.addComponent(chunk); chunkComposite .writerIndex(chunkComposite.writerIndex() + chunk.readableBytes()); } ctx.writeAndFlush(chunkComposite, ctx.voidPromise()); logger.debug("Sent OpenSecureChannelResponse."); } }); } catch (UaException e) { logger.error("Error installing security token: {}", e.getStatusCode(), e); ctx.close(); } catch (UaSerializationException e) { ctx.fireExceptionCaught(e); } finally { messageBuffer.release(); } }); }
From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerHelloHandler.java
License:Open Source License
private void onHello(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { logger.debug("[remote={}] Received Hello message.", ctx.channel().remoteAddress()); receivedHello = true;/*from w w w . j a v a 2 s. com*/ final HelloMessage hello = TcpMessageDecoder.decodeHello(buffer); String endpointUrl = hello.getEndpointUrl(); boolean endpointMatch = stackServer.getEndpointDescriptions().stream().anyMatch(endpoint -> Objects .equals(EndpointUtil.getPath(endpointUrl), EndpointUtil.getPath(endpoint.getEndpointUrl()))); if (!endpointMatch) { throw new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid, "unrecognized endpoint url: " + endpointUrl); } ctx.channel().attr(ENDPOINT_URL_KEY).set(endpointUrl); long remoteProtocolVersion = hello.getProtocolVersion(); long remoteReceiveBufferSize = hello.getReceiveBufferSize(); long remoteSendBufferSize = hello.getSendBufferSize(); long remoteMaxMessageSize = hello.getMaxMessageSize(); long remoteMaxChunkCount = hello.getMaxChunkCount(); if (remoteProtocolVersion < PROTOCOL_VERSION) { throw new UaException(StatusCodes.Bad_ProtocolVersionUnsupported, "unsupported protocol version: " + remoteProtocolVersion); } MessageLimits config = stackServer.getConfig().getMessageLimits(); /* Our receive buffer size is determined by the remote send buffer size. */ long localReceiveBufferSize = Math.min(remoteSendBufferSize, config.getMaxChunkSize()); /* Our send buffer size is determined by the remote receive buffer size. */ long localSendBufferSize = Math.min(remoteReceiveBufferSize, config.getMaxChunkSize()); /* Max chunk count the remote can send us; not influenced by remote configuration. */ long localMaxChunkCount = config.getMaxChunkCount(); /* Max message size the remote can send us. Determined by our max chunk count and receive buffer size. */ long localMaxMessageSize = Math.min(localReceiveBufferSize * localMaxChunkCount, config.getMaxMessageSize()); ChannelParameters parameters = new ChannelParameters(Ints.saturatedCast(localMaxMessageSize), Ints.saturatedCast(localReceiveBufferSize), Ints.saturatedCast(localSendBufferSize), Ints.saturatedCast(localMaxChunkCount), Ints.saturatedCast(remoteMaxMessageSize), Ints.saturatedCast(remoteReceiveBufferSize), Ints.saturatedCast(remoteSendBufferSize), Ints.saturatedCast(remoteMaxChunkCount)); SerializationQueue serializationQueue = new SerializationQueue(stackServer.getConfig().getExecutor(), parameters, stackServer.getConfig().getEncodingLimits()); ctx.pipeline().addLast(new UascServerAsymmetricHandler(stackServer, transportProfile, serializationQueue)); ctx.pipeline().remove(this); logger.debug("[remote={}] Removed HelloHandler, added AsymmetricHandler.", ctx.channel().remoteAddress()); AcknowledgeMessage acknowledge = new AcknowledgeMessage(PROTOCOL_VERSION, localReceiveBufferSize, localSendBufferSize, localMaxMessageSize, localMaxChunkCount); ByteBuf messageBuffer = TcpMessageEncoder.encode(acknowledge); // Using ctx.executor() is necessary to ensure this handler is removed // before the message can be written and another response arrives. ctx.executor().execute(() -> ctx.writeAndFlush(messageBuffer)); logger.debug("[remote={}] Sent Acknowledge message.", ctx.channel().remoteAddress()); }
From source file:org.eclipse.moquette.server.netty.NettyUtils.java
License:Open Source License
public static void setIdleTime(ChannelHandlerContext channel, int idleTime) { if (channel.pipeline().names().contains("idleStateHandler")) { channel.pipeline().remove("idleStateHandler"); }/*from ww w . jav a 2 s . c om*/ if (channel.pipeline().names().contains("idleEventHandler")) { channel.pipeline().remove("idleEventHandler"); } channel.pipeline().addFirst("idleStateHandler", new IdleStateHandler(0, 0, idleTime)); channel.pipeline().addAfter("idleStateHandler", "idleEventHandler", new MoquetteIdleTimoutHandler()); }
From source file:org.enderstone.server.packet.NetworkManager.java
License:Open Source License
public void setupEncryption(final SecretKey key) throws IOException { final Cipher decrypter = generateKey(2, key); final Cipher encrypter = generateKey(1, key); ctx.pipeline().addBefore("packet_rw_converter", "decrypt", new MessageToMessageDecoder<ByteBuf>() { NetworkEncrypter chipper = new NetworkEncrypter(decrypter); @Override/*from w ww.j av a 2 s. c o m*/ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws ShortBufferException { System.out.println("Decrypting " + in.readableBytes()); this.chipper.decrypt(ctx, in); } }); ctx.pipeline().addBefore("packet_rw_converter", "encrypt", new MessageToByteEncoder<ByteBuf>() { NetworkEncrypter chipper = new NetworkEncrypter(encrypter); @Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception { System.out.println("Encrypting " + msg.readableBytes()); this.chipper.encrypt(msg, out); } }); }