List of usage examples for io.netty.buffer ByteBuf readUnsignedInt
public abstract long readUnsignedInt();
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();//www . j a v a 2s .co 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 va 2s . c om*/ } 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.magnet.yak.load.XMPPHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println("CHANNEL READ CALLED"); ByteBuf m = (ByteBuf) msg; // (1) try {/*from w w w . j a v a 2s . com*/ long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L; System.out.println(new Date(currentTimeMillis)); ctx.close(); } finally { m.release(); } }
From source file:com.streamsets.pipeline.lib.parser.net.netflow.v5.NetflowV5Decoder.java
License:Apache License
@Override public List<NetflowV5Message> parse(int netflowVersion, int packetLength, boolean packetLengthCheck, ByteBuf buf, InetSocketAddress sender, InetSocketAddress recipient) throws OnRecordErrorException { if (!readHeader) { // 2-3/*from w w w . j a v a 2s . co m*/ count = buf.readUnsignedShort(); if (count <= 0) { throw new OnRecordErrorException(Errors.NETFLOW_01, Utils.format("Count is invalid: {}", count)); } else if (packetLengthCheck && packetLength < V5_HEADER_SIZE + count * V5_FLOW_SIZE) { String msg = Utils.format("Readable bytes {} too small for count {} (max {})", packetLength, count, (V5_HEADER_SIZE + count * V5_FLOW_SIZE)); throw new OnRecordErrorException(Errors.NETFLOW_01, msg); } readerId = String.valueOf(recipient); // 4-7 uptime = buf.readUnsignedInt(); // 8-11 seconds = buf.readUnsignedInt(); // 12-15 nanos = buf.readUnsignedInt(); millis = nanos / 1000000; // java timestamp, which is milliseconds timestamp = (seconds * 1000L) + millis; packetId = UUIDs.startOfJavaTimestamp(timestamp); // 16-19 flowSequence = buf.readUnsignedInt(); // 20 engineType = buf.readUnsignedByte(); // 21 engineId = buf.readUnsignedByte(); // the first 2 bits are the sampling mode, the remaining 14 the interval // 22-23 sampling = buf.readUnsignedShort(); samplingInterval = sampling & 0x3FFF; samplingMode = sampling >> 14; readHeader = true; parentDecoder.doCheckpoint(); } while (readIndex < count) { //ByteBuf flowBuf = buf.slice(V5_HEADER_SIZE + (readIndex * V5_FLOW_SIZE), V5_FLOW_SIZE); NetflowV5Message msg = new NetflowV5Message(); msg.setSeconds(seconds); msg.setNanos(nanos); msg.setCount(count); // 0 int srcaddr = (int) buf.readUnsignedInt(); // 4 int dstaddr = (int) buf.readUnsignedInt(); // 8 int nexthop = (int) buf.readUnsignedInt(); // 12 msg.setSnmpInput(buf.readUnsignedShort()); // 14 msg.setSnmpOnput(buf.readUnsignedShort()); msg.setPacketId(packetId.toString()); msg.setSender((sender == null) ? "unknown" : sender.getAddress().toString()); msg.setLength(packetLength); msg.setUptime(uptime); msg.setTimestamp(timestamp); msg.setFlowSequence(flowSequence); msg.setEngineId(engineId); msg.setEngineType(engineType); msg.setRawSampling(sampling); msg.setSamplingInterval(samplingInterval); msg.setSamplingMode(samplingMode); msg.setReaderId(readerId); // 16 long packets = buf.readUnsignedInt(); // 20 long octets = buf.readUnsignedInt(); // 24 long first = buf.readUnsignedInt(); msg.setRawFirst(first); if (first > 0) { msg.setFirst(timestamp - uptime + first); } else { msg.setFirst(0L); } // 28 long last = buf.readUnsignedInt(); msg.setRawLast(last); if (last > 0) { msg.setLast(timestamp - uptime + last); } else { msg.setLast(0L); } msg.setId(UUIDs.timeBased().toString()); msg.setSrcAddr(srcaddr); msg.setDstAddr(dstaddr); msg.setNextHop(nexthop); msg.setSrcAddrString(NetflowCommonDecoder.ipV4ToString(srcaddr)); msg.setDstAddrString(NetflowCommonDecoder.ipV4ToString(dstaddr)); msg.setNexthopString(NetflowCommonDecoder.ipV4ToString(nexthop)); // 32 msg.setSrcPort(buf.readUnsignedShort()); // 34 msg.setDstPort(buf.readUnsignedShort()); // 36 is "pad1" (unused zero bytes) buf.readByte(); // 37 msg.setTcpFlags(buf.readUnsignedByte()); // 38 msg.setProto(buf.readUnsignedByte()); // 39 msg.setTos(buf.readUnsignedByte()); // 40 msg.setSrcAs(buf.readUnsignedShort()); // 42 msg.setDstAs(buf.readUnsignedShort()); // 44 msg.setSrcMask(buf.readUnsignedByte()); // 45 msg.setDstMask(buf.readUnsignedByte()); msg.setdPkts(packets); msg.setdOctets(octets); // 46-47 is "pad2" (unused zero bytes) buf.skipBytes(2); result.add(msg); readIndex++; parentDecoder.doCheckpoint(); } // if we reached this point without any further Signal errors, we have finished consuming //checkpoint(); LinkedList<NetflowV5Message> returnResults = new LinkedList<>(result); resetState(); return returnResults; }
From source file:com.streamsets.pipeline.lib.parser.net.netflow.v9.NetflowV9Decoder.java
License:Apache License
private long readUnsignedIntAndCheckpoint(ByteBuf buf) { final long val = buf.readUnsignedInt(); parentDecoder.doCheckpoint();/* w w w. ja va 2s . c o m*/ return val; }
From source file:com.tesora.dve.db.mysql.common.MysqlAPIUtils.java
License:Open Source License
/** * Methods to read and write length coded dates in the Binary Protocol * // ww w.jav a 2s. co m * if year, month, day, hour, minutes, seconds and micro_seconds are all 0, * length is 0 and no other field is sent if hour, minutes, seconds and * micro_seconds are all 0, length is 4 and no other field is sent if * micro_seconds is 0, length is 7 and micro_seconds is not sent otherwise * length is 11 * * Fields * length (1) -- number of bytes following (valid values: 0, 4, 7, 11) * year (2) -- year * month (1) -- month * day (1) -- day * hour (1) -- hour * minute (1) -- minutes * second (1) -- seconds * micro_second (4) -- micro-seconds * */ public static Date getLengthCodedDate(ByteBuf cb) throws PEException { final Calendar cal = Calendar.getInstance(); cal.clear(); short length = cb.readUnsignedByte(); if (length >= 4) { cal.set(Calendar.YEAR, cb.readUnsignedShort()); cal.set(Calendar.MONTH, cb.readByte() - 1); // MONTH is zero based cal.set(Calendar.DAY_OF_MONTH, cb.readByte()); if (length >= 7) { cal.set(Calendar.HOUR_OF_DAY, cb.readByte()); cal.set(Calendar.MINUTE, cb.readByte()); cal.set(Calendar.SECOND, cb.readByte()); } if (length == 11) { long microSeconds = cb.readUnsignedInt(); cal.set(Calendar.MILLISECOND, (int) (microSeconds / 1000)); } if (length > 11) { throw new PEException("Invalid length specified to date type (" + length + ")"); } return cal.getTime(); } return null; }
From source file:com.tesora.dve.db.mysql.common.MysqlAPIUtils.java
License:Open Source License
/** * Methods to read and write length coded times in the Binary Protocol * // w w w . j a v a 2 s .c om * if days, hours, minutes, seconds and micro_seconds are all 0, length is 0 * and no other field is sent * * if micro_seconds is 0, length is 8 and micro_seconds is not sent * otherwise length is 12 * * Fields * length (1) -- number of bytes following (valid values: 0, 8, 12) * is_negative (1) -- (1 if minus, 0 for plus) * days (4) -- days * hours (1) -- hours * minutes (1) -- minutes * seconds (1) -- seconds * micro_seconds (4) -- micro-seconds */ public static Time getLengthCodedTime(ByteBuf cb) throws PEException { Calendar cal = Calendar.getInstance(); cal.clear(); short length = cb.readUnsignedByte(); if (length == 0) return null; Time ret = null; if (length >= 8) { cb.skipBytes(1); // this is the sign - we are ignoring this for now cb.skipBytes(4); // this is "days" - we are ignoring this for now cal.set(Calendar.HOUR_OF_DAY, cb.readByte()); cal.set(Calendar.MINUTE, cb.readByte()); cal.set(Calendar.SECOND, cb.readByte()); if (length == 12) { long microSeconds = cb.readUnsignedInt(); cal.set(Calendar.MILLISECOND, (int) (microSeconds / 1000)); } if (length > 12) { throw new PEException("Invalid length specified to date type (" + length + ")"); } ret = new Time(cal.getTimeInMillis()); } return ret; }
From source file:com.tesora.dve.db.mysql.libmy.MyLoginRequest.java
License:Open Source License
@Override public void unmarshallMessage(ByteBuf cb) { clientCapabilities = cb.readUnsignedInt(); boolean hasConnectDatabase = ((clientCapabilities & ClientCapabilities.CLIENT_CONNECT_WITH_DB) == ClientCapabilities.CLIENT_CONNECT_WITH_DB); maxPacketSize = cb.readInt();/*from www . ja v a2 s . co m*/ clientCharset = cb.readByte(); cb.skipBytes(23); // login request has a 23 byte filler username = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8); cb.skipBytes(1); // skip the NULL terminator byte passwordLength = cb.readByte(); byte[] passwordBytes = new byte[passwordLength]; cb.getBytes(cb.readerIndex(), passwordBytes, 0, passwordLength); password = new String(passwordBytes, CharsetUtil.ISO_8859_1); cb.skipBytes(passwordLength); // if the clientCapabilities flag has the CLIENT_CONNECT_WITH_DB bit set, // then this message contains an initial database to connect to if (hasConnectDatabase) { database = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8); if (database.length() < 1) { database = null; } } }
From source file:com.tesora.dve.db.mysql.portal.protocol.MSPAuthenticateV10MessageMessage.java
License:Open Source License
@Override protected ParsedData unmarshall(ByteBuf source) { ParsedData parseValues = new ParsedData(); parseValues.caps = new ClientCapabilities(source.readUnsignedInt()); parseValues.maxPacketSize = source.readInt(); parseValues.charsetID = source.readByte(); source.skipBytes(23); // login request has a 23 byte filler parseValues.username = source.readSlice(source.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8); source.skipBytes(1); // skip the NULL terminator byte passwordLength = source.readByte(); parseValues.password = source.readSlice(passwordLength).toString(CharsetUtil.ISO_8859_1); // if the clientCapabilities flag has the CLIENT_CONNECT_WITH_DB bit set, // then this message contains an initial database to connect to if (parseValues.caps.connectWithDB()) { parseValues.initialDatabase = source.readSlice(source.bytesBefore((byte) 0)) .toString(CharsetUtil.UTF_8); source.skipBytes(1); // skip the NULL terminator } else {/*from w ww . j av a 2s . com*/ parseValues.initialDatabase = ""; } return parseValues; }
From source file:com.tesora.dve.db.mysql.portal.protocol.MSPComStmtExecuteRequestMessage.java
License:Open Source License
@Override protected ParsedData unmarshall(ByteBuf source) { ParsedData parseValues = new ParsedData(); source.skipBytes(1);//skip the type identifier. parseValues.statementID = source.readUnsignedInt(); parseValues.flags = source.readByte(); parseValues.iterationCount = source.readUnsignedInt(); parseValues.metadataOffset = source.readerIndex(); //we don't actually unmarshall the metadata and values here, since we don't know how many parameters there are. parseValues.metadata = null;// w w w .j a v a 2 s. co m parseValues.values = null; return parseValues; }