Example usage for io.netty.buffer ByteBuf release

List of usage examples for io.netty.buffer ByteBuf release

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf release.

Prototype

boolean release();

Source Link

Document

Decreases the reference count by 1 and deallocates this object if the reference count reaches at 0 .

Usage

From source file:com.difference.historybook.proxy.littleproxy.LittleProxyResponse.java

License:Apache License

@Override
public byte[] getContent() {
    ByteBuf buf = response.content();
    byte[] bytes;
    int length = buf.readableBytes();

    if (buf.hasArray()) {
        bytes = buf.array();/*from  www.  j av a  2  s .c om*/
    } else {
        bytes = new byte[length];
        buf.getBytes(buf.readerIndex(), bytes);
    }
    buf.release();
    return bytes;
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAsymmetricHandler.java

License:Apache License

private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize

    long secureChannelId = buffer.readUnsignedInt();

    secureChannel.setChannelId(secureChannelId);

    AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer);
    if (!headerRef.compareAndSet(null, securityHeader)) {
        if (!securityHeader.equals(headerRef.get())) {
            throw new UaRuntimeException(StatusCodes.Bad_SecurityChecksFailed,
                    "subsequent AsymmetricSecurityHeader did not match");
        }/*from w w w . java 2s  .co m*/
    }

    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));
    }

    char chunkType = (char) buffer.getByte(3);

    if (chunkType == 'A' || chunkType == 'F') {
        final List<ByteBuf> buffersToDecode = chunkBuffers;
        chunkBuffers = new ArrayList<>(maxChunkCount);

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf decodedBuffer = null;

            try {
                decodedBuffer = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode);

                UaResponseMessage responseMessage = binaryDecoder.setBuffer(decodedBuffer).decodeMessage(null);

                StatusCode serviceResult = responseMessage.getResponseHeader().getServiceResult();

                if (serviceResult.isGood()) {
                    OpenSecureChannelResponse response = (OpenSecureChannelResponse) responseMessage;

                    secureChannel.setChannelId(response.getSecurityToken().getChannelId().longValue());
                    logger.debug("Received OpenSecureChannelResponse.");

                    installSecurityToken(ctx, response);
                } else {
                    ServiceFault serviceFault = (responseMessage instanceof ServiceFault)
                            ? (ServiceFault) responseMessage
                            : new ServiceFault(responseMessage.getResponseHeader());

                    throw new UaServiceFaultException(serviceFault);
                }
            } catch (MessageAbortedException e) {
                logger.error("Received message abort chunk; error={}, reason={}", e.getStatusCode(),
                        e.getMessage());
                ctx.close();
            } catch (Throwable t) {
                logger.error("Error decoding OpenSecureChannelResponse: {}", t.getMessage(), t);
                ctx.close();
            } finally {
                if (decodedBuffer != null) {
                    decodedBuffer.release();
                }
                buffersToDecode.clear();
            }
        });
    }
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAsymmetricHandler.java

License:Apache License

private void sendOpenSecureChannelRequest(ChannelHandlerContext ctx, OpenSecureChannelRequest request) {
    serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
        ByteBuf messageBuffer = BufferUtil.buffer();

        try {//from w  ww  .  ja v  a2s.  co  m
            binaryEncoder.setBuffer(messageBuffer);
            binaryEncoder.encodeMessage(null, request);

            List<ByteBuf> chunks = chunkEncoder.encodeAsymmetric(secureChannel, MessageType.OpenSecureChannel,
                    messageBuffer, requestId.getAndIncrement());

            ctx.executor().execute(() -> {
                chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
                ctx.flush();
            });

            ChannelSecurity channelSecurity = secureChannel.getChannelSecurity();

            long currentTokenId = channelSecurity != null
                    ? channelSecurity.getCurrentToken().getTokenId().longValue()
                    : -1L;

            long previousTokenId = channelSecurity != null
                    ? channelSecurity.getPreviousToken().map(t -> t.getTokenId().longValue()).orElse(-1L)
                    : -1L;

            logger.debug("Sent OpenSecureChannelRequest ({}, id={}, currentToken={}, previousToken={}).",
                    request.getRequestType(), secureChannel.getChannelId(), currentTokenId, previousTokenId);
        } catch (UaException e) {
            logger.error("Error encoding OpenSecureChannelRequest: {}", e.getMessage(), e);
            ctx.close();
        } finally {
            messageBuffer.release();
        }
    });
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAsymmetricHandler.java

License:Apache License

private void sendCloseSecureChannelRequest(ChannelHandlerContext ctx, CloseSecureChannelRequest request) {
    serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
        ByteBuf messageBuffer = BufferUtil.buffer();

        try {/* ww  w  . j  a va2s .c om*/
            binaryEncoder.setBuffer(messageBuffer);
            binaryEncoder.encodeMessage(null, request);

            List<ByteBuf> chunks = chunkEncoder.encodeSymmetric(secureChannel, MessageType.CloseSecureChannel,
                    messageBuffer, requestId.getAndIncrement());

            ctx.executor().execute(() -> {
                chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
                ctx.flush();
                ctx.close();
            });

            secureChannel.setChannelId(0);

            logger.debug("Sent CloseSecureChannelRequest.");
        } catch (UaException e) {
            logger.error("Error Encoding CloseSecureChannelRequest: {}", e.getMessage(), e);
            ctx.close();
        } finally {
            messageBuffer.release();
        }
    });
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java

License:Apache License

private CompletableFuture<Tuple2<Long, List<ByteBuf>>> encodeMessage(UaRequestMessage request,
        MessageType messageType) {/* w  ww  .  ja v a  2 s  .c  o m*/

    CompletableFuture<Tuple2<Long, List<ByteBuf>>> future = new CompletableFuture<>();

    serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
        ByteBuf messageBuffer = null;

        try {
            messageBuffer = BufferUtil.buffer();
            binaryEncoder.setBuffer(messageBuffer);
            binaryEncoder.encodeMessage(null, request);

            List<ByteBuf> chunks;

            if (messageType == MessageType.OpenSecureChannel) {
                chunks = chunkEncoder.encodeAsymmetric(secureChannel, messageType, messageBuffer,
                        requestIdSequence.getAndIncrement());
            } else {
                chunks = chunkEncoder.encodeSymmetric(secureChannel, messageType, messageBuffer,
                        requestIdSequence.getAndIncrement());
            }

            future.complete(new Tuple2<>(chunkEncoder.getLastRequestId(), chunks));
        } catch (UaException ex) {
            logger.error("Error encoding {}: {}", request, ex.getMessage(), ex);

            future.completeExceptionally(ex);
        } finally {
            if (messageBuffer != null) {
                messageBuffer.release();
            }
        }
    });

    return future;
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java

License:Apache License

private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    if (secureChannelTimeout != null) {
        if (secureChannelTimeout.cancel()) {
            logger.debug("OpenSecureChannel timeout canceled");

            secureChannelTimeout = null;
        } else {/*from   w w w. j  a  v a2s  .  co m*/
            logger.warn("timed out waiting for secure channel");

            handshakeFuture.completeExceptionally(
                    new UaException(StatusCodes.Bad_Timeout, "timed out waiting for secure channel"));
            ctx.close();
            return;
        }
    }

    buffer.skipBytes(3 + 1 + 4 + 4); // skip messageType, chunkType, messageSize, secureChannelId

    AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer);
    if (!headerRef.compareAndSet(null, securityHeader)) {
        if (!securityHeader.equals(headerRef.get())) {
            throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                    "subsequent AsymmetricSecurityHeader did not match");
        }
    }

    if (accumulateChunk(buffer)) {
        final List<ByteBuf> buffersToDecode = ImmutableList.copyOf(chunkBuffers);
        chunkBuffers = new LinkedList<>();

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf decodedBuffer = null;

            try {
                decodedBuffer = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode);

                UaResponseMessage responseMessage = binaryDecoder.setBuffer(decodedBuffer).decodeMessage(null);

                StatusCode serviceResult = responseMessage.getResponseHeader().getServiceResult();

                if (serviceResult.isGood()) {
                    OpenSecureChannelResponse response = (OpenSecureChannelResponse) responseMessage;

                    secureChannel.setChannelId(response.getSecurityToken().getChannelId().longValue());
                    logger.debug("Received OpenSecureChannelResponse.");

                    installSecurityToken(ctx, response);

                    handshakeFuture.complete(secureChannel);
                } else {
                    ServiceFault serviceFault = (responseMessage instanceof ServiceFault)
                            ? (ServiceFault) responseMessage
                            : new ServiceFault(responseMessage.getResponseHeader());

                    throw new UaServiceFaultException(serviceFault);
                }
            } catch (MessageAbortedException e) {
                logger.error("Received message abort chunk; error={}, reason={}", e.getStatusCode(),
                        e.getMessage());
                ctx.close();
            } catch (Throwable t) {
                logger.error("Error decoding OpenSecureChannelResponse: {}", t.getMessage(), t);
                ctx.close();
            } finally {
                if (decodedBuffer != null) {
                    decodedBuffer.release();
                }
            }
        });
    }
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java

License:Apache License

private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize

    long secureChannelId = buffer.readUnsignedInt();
    if (secureChannelId != secureChannel.getChannelId()) {
        throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid,
                "invalid secure channel id: " + secureChannelId);
    }/* ww w  . j  a  va  2s.  co m*/

    if (accumulateChunk(buffer)) {
        final List<ByteBuf> buffersToDecode = ImmutableList.copyOf(chunkBuffers);
        chunkBuffers = new LinkedList<>();

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf decodedBuffer = null;

            try {
                decodedBuffer = chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode);

                binaryDecoder.setBuffer(decodedBuffer);
                UaResponseMessage response = binaryDecoder.decodeMessage(null);

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().complete(response));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (MessageAbortedException e) {
                logger.debug("Received message abort chunk; error={}, reason={}", e.getStatusCode(),
                        e.getMessage());

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().completeExceptionally(e));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (Throwable t) {
                logger.error("Error decoding symmetric message: {}", t.getMessage(), t);
                serializationQueue.pause();
                ctx.close();
            } finally {
                if (decodedBuffer != null) {
                    decodedBuffer.release();
                }
            }
        });
    }
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientSymmetricHandler.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, UaRequestFuture message, ByteBuf out) throws Exception {
    serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
        ByteBuf messageBuffer = BufferUtil.buffer();

        try {// w ww .  j a  v  a  2 s  . c  o m
            binaryEncoder.setBuffer(messageBuffer);
            binaryEncoder.encodeMessage(null, message.getRequest());

            List<ByteBuf> chunks = chunkEncoder.encodeSymmetric(secureChannel, MessageType.SecureMessage,
                    messageBuffer, requestId.getAndIncrement());

            long requestId = chunkEncoder.getLastRequestId();
            pending.put(requestId, message);

            // No matter how we complete, make sure the entry in pending is removed.
            // This covers the case where the request fails due to a timeout in the
            // upper layers as well as normal completion.
            message.getFuture().whenComplete((r, x) -> pending.remove(requestId));

            ctx.executor().execute(() -> {
                chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
                ctx.flush();
            });
        } catch (UaException e) {
            logger.error("Error encoding {}: {}", message.getClass(), e.getMessage(), e);
            ctx.close();
        } finally {
            messageBuffer.release();
        }
    });
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientSymmetricHandler.java

License:Apache License

private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize

    long secureChannelId = buffer.readUnsignedInt();
    if (secureChannelId != secureChannel.getChannelId()) {
        throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid,
                "invalid secure channel id: " + secureChannelId);
    }//from  w w w.j a v  a  2 s  .c o  m

    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));
    }

    char chunkType = (char) buffer.getByte(3);

    if (chunkType == 'A' || chunkType == 'F') {
        final List<ByteBuf> buffersToDecode = chunkBuffers;
        chunkBuffers = new ArrayList<>(maxChunkCount);

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf decodedBuffer = null;

            try {
                validateChunkHeaders(buffersToDecode);

                decodedBuffer = chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode);

                binaryDecoder.setBuffer(decodedBuffer);
                UaResponseMessage response = binaryDecoder.decodeMessage(null);

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().complete(response));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (MessageAbortedException e) {
                logger.debug("Received message abort chunk; error={}, reason={}", e.getStatusCode(),
                        e.getMessage());

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().completeExceptionally(e));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (Throwable t) {
                logger.error("Error decoding symmetric message: {}", t.getMessage(), t);
                ctx.close();
                serializationQueue.pause();
            } finally {
                if (decodedBuffer != null) {
                    decodedBuffer.release();
                }
                buffersToDecode.clear();
            }
        });
    }
}

From source file:com.digitalpetri.opcua.stack.core.channel.ChunkDecoder.java

License:Apache License

private void decryptChunk(Delegate delegate, SecureChannel channel, ByteBuf chunkBuffer) throws UaException {
    int cipherTextBlockSize = delegate.getCipherTextBlockSize(channel);
    int blockCount = chunkBuffer.readableBytes() / cipherTextBlockSize;

    int plainTextBufferSize = cipherTextBlockSize * blockCount;

    ByteBuf plainTextBuffer = BufferUtil.buffer(plainTextBufferSize);

    ByteBuffer plainTextNioBuffer = plainTextBuffer.writerIndex(plainTextBufferSize).nioBuffer();

    ByteBuffer chunkNioBuffer = chunkBuffer.nioBuffer();

    try {/*www.j  a  v a 2 s .co  m*/
        Cipher cipher = delegate.getCipher(channel);

        assert (chunkBuffer.readableBytes() % cipherTextBlockSize == 0);

        if (delegate instanceof AsymmetricDelegate) {
            for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) {
                chunkNioBuffer.limit(chunkNioBuffer.position() + cipherTextBlockSize);

                cipher.doFinal(chunkNioBuffer, plainTextNioBuffer);
            }
        } else {
            cipher.doFinal(chunkNioBuffer, plainTextNioBuffer);
        }
    } catch (GeneralSecurityException e) {
        throw new UaException(StatusCodes.Bad_SecurityChecksFailed, e);
    }

    /* Write plainTextBuffer back into the chunk buffer we decrypted from. */
    plainTextNioBuffer.flip(); // limit = pos, pos = 0

    chunkBuffer.writerIndex(chunkBuffer.readerIndex());
    chunkBuffer.writeBytes(plainTextNioBuffer);

    plainTextBuffer.release();
}