List of usage examples for io.netty.channel ChannelHandlerContext channel
Channel channel();
From source file:com.digitalpetri.modbus.slave.ModbusTcpSlave.java
License:Apache License
private void onExceptionCaught(ChannelHandlerContext ctx, Throwable cause) { logger.error("Exception caught on channel: {}", ctx.channel(), cause); ctx.close();/* w w w. j a v a 2s .c o m*/ }
From source file:com.digitalpetri.opcua.stack.client.fsm.states.Connected.java
License:Apache License
@Override public CompletableFuture<Void> activate(ConnectionEvent event, ConnectionStateFsm fsm) { inactivityListener = new ChannelInboundHandlerAdapter() { @Override// w ww. j a va 2 s. c om public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.warn("Channel went inactive: {}", ctx.channel()); fsm.handleEvent(ConnectionEvent.ConnectionLost); super.channelInactive(ctx); } }; secureChannel.getChannel().pipeline().addLast(inactivityListener); channelFuture.complete(secureChannel); return CF_VOID_COMPLETED; }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAcknowledgeHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { secureChannel.setChannel(ctx.channel()); HelloMessage hello = new HelloMessage(PROTOCOL_VERSION, client.getChannelConfig().getMaxChunkSize(), client.getChannelConfig().getMaxChunkSize(), client.getChannelConfig().getMaxMessageSize(), client.getChannelConfig().getMaxChunkCount(), client.getEndpointUrl()); ByteBuf messageBuffer = TcpMessageEncoder.encode(hello); ctx.writeAndFlush(messageBuffer);/*from w w w .j av a 2s .c o m*/ logger.debug("Sent Hello message on channel={}.", ctx.channel()); super.channelActive(ctx); }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAcknowledgeHandler.java
License:Apache License
private void onAcknowledge(ChannelHandlerContext ctx, ByteBuf buffer) { 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); }// w w w .j a va 2s. c om 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); UaTcpClientAsymmetricHandler handler = new UaTcpClientAsymmetricHandler(client, serializationQueue, secureChannel, handshakeFuture); ctx.pipeline().addLast(handler); }); }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientSymmetricHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { List<UaMessage> awaitingHandshake = ctx.channel().attr(UaTcpClientAcknowledgeHandler.KEY_AWAITING_HANDSHAKE) .get();//from w w w. j ava 2 s . c o m if (awaitingHandshake != null) { logger.debug("{} message(s) queued before handshake completed; sending now.", awaitingHandshake.size()); awaitingHandshake.forEach(m -> ctx.pipeline().write(m)); ctx.flush(); ctx.channel().attr(UaTcpClientAcknowledgeHandler.KEY_AWAITING_HANDSHAKE).remove(); } client.getExecutorService().execute(() -> handshakeFuture.complete(secureChannel)); }
From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerAsymmetricHandler.java
License:Apache License
private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { buffer.skipBytes(3); // Skip messageType char chunkType = (char) buffer.readByte(); if (chunkType == 'A') { chunkBuffers.forEach(ByteBuf::release); chunkBuffers.clear();/*from w w w. ja va 2 s. c o m*/ headerRef.set(null); } else { buffer.skipBytes(4); // Skip messageSize long secureChannelId = buffer.readUnsignedInt(); AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer); if (secureChannelId == 0) { // Okay, this is the first OpenSecureChannelRequest... carry on. String endpointUrl = ctx.channel().attr(UaTcpServerHelloHandler.ENDPOINT_URL_KEY).get(); String securityPolicyUri = securityHeader.getSecurityPolicyUri(); EndpointDescription endpointDescription = Arrays.stream(server.getEndpointDescriptions()) .filter(e -> { String s1 = pathOrUrl(endpointUrl); String s2 = pathOrUrl(e.getEndpointUrl()); boolean uriMatch = s1.equals(s2); boolean policyMatch = e.getSecurityPolicyUri().equals(securityPolicyUri); return uriMatch && policyMatch; }).findFirst().orElse(null); if (endpointDescription == null && !server.getConfig().isStrictEndpointUrlsEnabled()) { endpointDescription = Arrays.stream(server.getEndpointDescriptions()) .filter(e -> e.getSecurityPolicyUri().equals(securityPolicyUri)).findFirst() .orElse(null); } if (endpointDescription == null) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "SecurityPolicy URI did not match"); } secureChannel = server.openSecureChannel(); secureChannel.setEndpointDescription(endpointDescription); } else { secureChannel = server.getSecureChannel(secureChannelId); if (secureChannel == null) { throw new UaException(StatusCodes.Bad_TcpSecureChannelUnknown, "unknown secure channel id: " + secureChannelId); } if (!secureChannel.getRemoteCertificateBytes().equals(securityHeader.getSenderCertificate())) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "certificate requesting renewal did not match existing certificate."); } Channel boundChannel = secureChannel.attr(UaTcpStackServer.BoundChannelKey).get(); if (boundChannel != null && boundChannel != ctx.channel()) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "received a renewal request from channel other than the bound channel."); } } if (!headerRef.compareAndSet(null, securityHeader)) { if (!securityHeader.equals(headerRef.get())) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "subsequent AsymmetricSecurityHeader did not match"); } } SecurityPolicy securityPolicy = SecurityPolicy.fromUri(securityHeader.getSecurityPolicyUri()); secureChannel.setSecurityPolicy(securityPolicy); if (!securityHeader.getSenderCertificate().isNull() && securityPolicy != SecurityPolicy.None) { secureChannel.setRemoteCertificate(securityHeader.getSenderCertificate().bytes()); try { CertificateValidator certificateValidator = server.getCertificateValidator(); certificateValidator.validate(secureChannel.getRemoteCertificate()); certificateValidator.verifyTrustChain(secureChannel.getRemoteCertificate(), secureChannel.getRemoteCertificateChain()); } catch (UaException e) { try { UaException cause = new UaException(e.getStatusCode(), "security checks failed"); ErrorMessage errorMessage = ExceptionHandler.sendErrorMessage(ctx, cause); logger.debug("[remote={}] {}.", ctx.channel().remoteAddress(), errorMessage.getReason(), cause); } catch (Exception ignored) { } } } if (!securityHeader.getReceiverThumbprint().isNull()) { CertificateManager certificateManager = server.getCertificateManager(); Optional<X509Certificate> localCertificate = certificateManager .getCertificate(securityHeader.getReceiverThumbprint()); Optional<KeyPair> keyPair = certificateManager.getKeyPair(securityHeader.getReceiverThumbprint()); if (localCertificate.isPresent() && keyPair.isPresent()) { secureChannel.setLocalCertificate(localCertificate.get()); secureChannel.setKeyPair(keyPair.get()); } else { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "no certificate for provided thumbprint"); } } int chunkSize = buffer.readerIndex(0).readableBytes(); if (chunkSize > maxChunkSize) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk size exceeded (%s)", maxChunkSize)); } chunkBuffers.add(buffer.retain()); if (chunkBuffers.size() > maxChunkCount) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk count exceeded (%s)", maxChunkCount)); } if (chunkType == 'F') { final List<ByteBuf> buffersToDecode = chunkBuffers; chunkBuffers = new ArrayList<>(maxChunkCount); headerRef.set(null); serializationQueue.decode((binaryDecoder, chunkDecoder) -> { ByteBuf messageBuffer = null; try { messageBuffer = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode); OpenSecureChannelRequest request = binaryDecoder.setBuffer(messageBuffer) .decodeMessage(null); logger.debug("Received OpenSecureChannelRequest ({}, id={}).", request.getRequestType(), secureChannelId); long requestId = chunkDecoder.getLastRequestId(); installSecurityToken(ctx, request, requestId); } catch (UaException e) { logger.error("Error decoding asymmetric message: {}", e.getMessage(), e); ctx.close(); } finally { if (messageBuffer != null) { messageBuffer.release(); } buffersToDecode.clear(); } }); } } }
From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerAsymmetricHandler.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { chunkBuffers.forEach(ByteBuf::release); chunkBuffers.clear();/* www. ja v a 2s .com*/ if (cause instanceof IOException) { ctx.close(); logger.debug("[remote={}] IOException caught; channel closed"); } else { ErrorMessage errorMessage = ExceptionHandler.sendErrorMessage(ctx, cause); if (cause instanceof UaException) { logger.debug("[remote={}] UaException caught; sent {}", ctx.channel().remoteAddress(), errorMessage, cause); } else { logger.error("[remote={}] Exception caught; sent {}", ctx.channel().remoteAddress(), errorMessage, cause); } } }
From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerHelloHandler.java
License:Apache License
private void onHello(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { logger.debug("[remote={}] Received Hello message.", ctx.channel().remoteAddress()); HelloMessage hello = TcpMessageDecoder.decodeHello(buffer); UaTcpStackServer server = socketServer.getServer(hello.getEndpointUrl()); if (server == null) { throw new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid, "unrecognized endpoint url: " + hello.getEndpointUrl()); }// w ww . j a v a 2 s .com ctx.channel().attr(ENDPOINT_URL_KEY).set(hello.getEndpointUrl()); 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); } ChannelConfig config = server.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 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)); int maxArrayLength = config.getMaxArrayLength(); int maxStringLength = config.getMaxStringLength(); SerializationQueue serializationQueue = new SerializationQueue(server.getConfig().getExecutor(), parameters, maxArrayLength, maxStringLength); ctx.pipeline().addLast(new UaTcpServerAsymmetricHandler(server, 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); ctx.executor().execute(() -> ctx.writeAndFlush(messageBuffer)); logger.debug("[remote={}] Sent Acknowledge message.", ctx.channel().remoteAddress()); }
From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerHelloHandler.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof IOException) { ctx.close();/*from w ww .ja v a 2 s .c o m*/ logger.debug("[remote={}] IOException caught; channel closed"); } else { ErrorMessage errorMessage = ExceptionHandler.sendErrorMessage(ctx, cause); if (cause instanceof UaException) { logger.debug("[remote={}] UaException caught; sent {}", ctx.channel().remoteAddress(), errorMessage, cause); } else { logger.error("[remote={}] Exception caught; sent {}", ctx.channel().remoteAddress(), errorMessage, cause); } } }
From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerSymmetricHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (secureChannel != null) { secureChannel.attr(UaTcpStackServer.BoundChannelKey).set(ctx.channel()); }/*www . ja v a 2s .c o m*/ super.channelActive(ctx); }