List of usage examples for io.netty.buffer ByteBuf readByte
public abstract byte readByte();
From source file:com.digitalpetri.opcua.stack.core.channel.headers.SecureMessageHeader.java
License:Apache License
public static SecureMessageHeader decode(ByteBuf buffer) throws UaException { return new SecureMessageHeader(MessageType.fromMediumInt(buffer.readMedium()), (char) buffer.readByte(), buffer.readUnsignedInt(), buffer.readUnsignedInt()); }
From source file:com.digitalpetri.opcua.stack.core.channel.messages.TcpMessageDecoder.java
License:Apache License
public static HelloMessage decodeHello(ByteBuf buffer) throws UaException { MessageType messageType = MessageType.fromMediumInt(buffer.readMedium()); char chunkType = (char) buffer.readByte(); buffer.skipBytes(4); // length assert (messageType == MessageType.Hello && chunkType == 'F'); return HelloMessage.decode(buffer); }
From source file:com.digitalpetri.opcua.stack.core.channel.messages.TcpMessageDecoder.java
License:Apache License
public static AcknowledgeMessage decodeAcknowledge(ByteBuf buffer) throws UaException { MessageType messageType = MessageType.fromMediumInt(buffer.readMedium()); char chunkType = (char) buffer.readByte(); buffer.skipBytes(4); // length assert (messageType == MessageType.Acknowledge && chunkType == 'F'); return AcknowledgeMessage.decode(buffer); }
From source file:com.digitalpetri.opcua.stack.core.channel.messages.TcpMessageDecoder.java
License:Apache License
public static ErrorMessage decodeError(ByteBuf buffer) throws UaException { MessageType messageType = MessageType.fromMediumInt(buffer.readMedium()); char chunkType = (char) buffer.readByte(); buffer.skipBytes(4); // length assert (messageType == MessageType.Error && chunkType == 'F'); return ErrorMessage.decode(buffer); }
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 ww. j ava 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.UaTcpServerSymmetricHandler.java
License:Apache License
private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) 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 . j a va2 s. c o m*/ } else { buffer.skipBytes(4); // Skip messageSize long secureChannelId = buffer.readUnsignedInt(); if (secureChannelId != secureChannel.getChannelId()) { throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid, "invalid secure channel id: " + secureChannelId); } 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); serializationQueue.decode((binaryDecoder, chunkDecoder) -> { try { validateChunkHeaders(buffersToDecode); ByteBuf messageBuffer = chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode); binaryDecoder.setBuffer(messageBuffer); UaRequestMessage request = binaryDecoder.decodeMessage(null); ServiceRequest<UaRequestMessage, UaResponseMessage> serviceRequest = new ServiceRequest<>( request, chunkDecoder.getLastRequestId(), server, secureChannel); server.getExecutorService().execute(() -> server.receiveRequest(serviceRequest)); messageBuffer.release(); buffersToDecode.clear(); } catch (UaException e) { logger.error("Error decoding symmetric message: {}", e.getMessage(), e); ctx.close(); } }); } } }
From source file:com.ebay.jetstream.messaging.transport.netty.serializer.StreamMessageDecoder.java
License:MIT License
@SuppressWarnings("resource") @Override//from ww w. j a v a2s .co m protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf frame = (ByteBuf) super.decode(ctx, in); if (frame == null) { return null; } int readerIndex = frame.readerIndex(); byte version = frame.readByte(); frame.readerIndex(readerIndex); if (version == KRYO_STREAM_VERSION) { return decodeAsKryo(frame); } else { return new CompactObjectInputStream(new ByteBufInputStream(frame), classResolver).readObject(); } }
From source file:com.eightkdata.mongowp.bson.netty.DefaultNettyBsonLowLevelReader.java
License:Open Source License
@Override BsonArray readArray(@Loose @ModifiesIndexes ByteBuf byteBuf) throws NettyBsonReaderException { int length = byteBuf.readInt(); int significantLenght = length - 4 - 1; ByteBuf significantSlice = byteBuf.readSlice(significantLenght); byte b = byteBuf.readByte(); assert b == 0x00; ArrayList<BsonValue<?>> list = new ArrayList<>(); while (significantSlice.readableBytes() > 0) { list.add(readArrayEntry(significantSlice)); }//from w w w . ja v a 2s . com return new ListBsonArray(list); }
From source file:com.eightkdata.mongowp.bson.netty.DefaultNettyBsonLowLevelReader.java
License:Open Source License
@Override BsonBinary readBinary(@Loose @ModifiesIndexes ByteBuf byteBuf) { int length = byteBuf.readInt(); byte subtype = byteBuf.readByte(); byte[] content = new byte[length]; byteBuf.readBytes(content);/* w ww .j a v a2s . c o m*/ return new ByteArrayBsonBinary(ParsingTools.getBinarySubtype(subtype), subtype, content); }
From source file:com.eightkdata.mongowp.bson.netty.DefaultNettyBsonLowLevelReader.java
License:Open Source License
@Override BsonDocument readDocument(@Loose @ModifiesIndexes ByteBuf byteBuf) throws NettyBsonReaderException { int length = byteBuf.readInt(); int significantLenght = length - 4 - 1; ByteBuf significantSlice = byteBuf.readSlice(significantLenght); byte b = byteBuf.readByte(); assert b == 0x00; LinkedHashMap<String, BsonValue<?>> values = new LinkedHashMap<>(); while (significantSlice.readableBytes() > 0) { Entry<?> entry = readDocumentEntry(significantSlice); values.put(entry.getKey(), entry.getValue()); }/*from w ww . j av a2 s . c o m*/ return new MapBasedBsonDocument(values); }