List of usage examples for io.netty.buffer ByteBuf readBytes
public abstract ByteBuf readBytes(ByteBuffer dst);
From source file:com.comphenix.protocol.injector.netty.WirePacket.java
License:Open Source License
private static byte[] getBytes(ByteBuf buffer) { byte[] array = new byte[buffer.readableBytes()]; buffer.readBytes(array); return array; }
From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java
License:Apache License
private String readString(ByteBuf frame, int size) { byte[] bytes = new byte[size]; frame.readBytes(bytes); return new String(bytes, CharsetUtil.UTF_8); }
From source file:com.datastax.driver.core.CBUtil.java
License:Apache License
public static byte[] readBytes(ByteBuf cb) { try {/* w w w .ja v a 2 s . c om*/ int length = cb.readUnsignedShort(); byte[] bytes = new byte[length]; cb.readBytes(bytes); return bytes; } catch (IndexOutOfBoundsException e) { throw new DriverInternalError("Not enough bytes to read a byte array preceded by it's 2 bytes length"); } }
From source file:com.datastax.driver.core.CBUtil.java
License:Apache License
public static InetSocketAddress readInet(ByteBuf cb) { int addrSize = cb.readByte(); byte[] address = new byte[addrSize]; cb.readBytes(address); int port = cb.readInt(); try {//ww w. j a v a2 s. c om return new InetSocketAddress(InetAddress.getByAddress(address), port); } catch (UnknownHostException e) { throw new DriverInternalError( String.format("Invalid IP address (%d.%d.%d.%d) while deserializing inet address", address[0], address[1], address[2], address[3])); } }
From source file:com.datastax.driver.core.CBUtil.java
License:Apache License
public static byte[] readRawBytes(ByteBuf cb) { if (cb.hasArray() && cb.readableBytes() == cb.array().length) { // Move the readerIndex just so we consistently consume the input cb.readerIndex(cb.writerIndex()); return cb.array(); }/*from w w w .j a v a2s.c o m*/ // Otherwise, just read the bytes in a new array byte[] bytes = new byte[cb.readableBytes()]; cb.readBytes(bytes); return bytes; }
From source file:com.dempe.chat.common.mqtt.codec.ConnectDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException { in.resetReaderIndex();// w w w . jav a 2 s .c o m //Common decoding part ConnectMessage message = new ConnectMessage(); if (!decodeCommonHeader(message, 0x00, in)) { in.resetReaderIndex(); return; } int remainingLength = message.getRemainingLength(); int start = in.readerIndex(); int protocolNameLen = in.readUnsignedShort(); byte[] encProtoName; String protoName; Attribute<Integer> versionAttr = ctx.attr(MQTTDecoder.PROTOCOL_VERSION); switch (protocolNameLen) { case 6: //MQTT version 3.1 "MQIsdp" //ProtocolName 8 bytes or 6 bytes if (in.readableBytes() < 10) { in.resetReaderIndex(); return; } encProtoName = new byte[6]; in.readBytes(encProtoName); protoName = new String(encProtoName, "UTF-8"); if (!"MQIsdp".equals(protoName)) { in.resetReaderIndex(); throw new CorruptedFrameException("Invalid protoName: " + protoName); } message.setProtocolName(protoName); versionAttr.set((int) Utils.VERSION_3_1); break; case 4: //MQTT version 3.1.1 "MQTT" //ProtocolName 6 bytes if (in.readableBytes() < 8) { in.resetReaderIndex(); return; } encProtoName = new byte[4]; in.readBytes(encProtoName); protoName = new String(encProtoName, "UTF-8"); if (!"MQTT".equals(protoName)) { in.resetReaderIndex(); throw new CorruptedFrameException("Invalid protoName: " + protoName); } message.setProtocolName(protoName); versionAttr.set((int) Utils.VERSION_3_1_1); break; default: //protocol broken throw new CorruptedFrameException("Invalid protoName size: " + protocolNameLen); } //ProtocolVersion 1 byte (value 0x03 for 3.1, 0x04 for 3.1.1) message.setProtocolVersion(in.readByte()); if (message.getProtocolVersion() == Utils.VERSION_3_1_1) { //if 3.1.1, check the flags (dup, retain and qos == 0) if (message.isDupFlag() || message.isRetainFlag() || message.getQos() != AbstractMessage.QOSType.MOST_ONE) { throw new CorruptedFrameException("Received a CONNECT with fixed header flags != 0"); } //check if this is another connect from the same client on the same session Attribute<Boolean> connectAttr = ctx.attr(ConnectDecoder.CONNECT_STATUS); Boolean alreadyConnected = connectAttr.get(); if (alreadyConnected == null) { //never set connectAttr.set(true); } else if (alreadyConnected) { throw new CorruptedFrameException("Received a second CONNECT on the same network connection"); } } //Connection flag byte connFlags = in.readByte(); if (message.getProtocolVersion() == Utils.VERSION_3_1_1) { if ((connFlags & 0x01) != 0) { //bit(0) of connection flags is != 0 throw new CorruptedFrameException("Received a CONNECT with connectionFlags[0(bit)] != 0"); } } boolean cleanSession = ((connFlags & 0x02) >> 1) == 1; boolean willFlag = ((connFlags & 0x04) >> 2) == 1; byte willQos = (byte) ((connFlags & 0x18) >> 3); if (willQos > 2) { in.resetReaderIndex(); throw new CorruptedFrameException("Expected will QoS in range 0..2 but found: " + willQos); } boolean willRetain = ((connFlags & 0x20) >> 5) == 1; boolean passwordFlag = ((connFlags & 0x40) >> 6) == 1; boolean userFlag = ((connFlags & 0x80) >> 7) == 1; //a password is true iff user is true. if (!userFlag && passwordFlag) { in.resetReaderIndex(); throw new CorruptedFrameException( "Expected password flag to true if the user flag is true but was: " + passwordFlag); } message.setCleanSession(cleanSession); message.setWillFlag(willFlag); message.setWillQos(willQos); message.setWillRetain(willRetain); message.setPasswordFlag(passwordFlag); message.setUserFlag(userFlag); //Keep Alive timer 2 bytes //int keepAlive = Utils.readWord(in); int keepAlive = in.readUnsignedShort(); message.setKeepAlive(keepAlive); if ((remainingLength == 12 && message.getProtocolVersion() == Utils.VERSION_3_1) || (remainingLength == 10 && message.getProtocolVersion() == Utils.VERSION_3_1_1)) { out.add(message); return; } //Decode the ClientID String clientID = Utils.decodeString(in); if (clientID == null) { in.resetReaderIndex(); return; } message.setClientID(clientID); //Decode willTopic if (willFlag) { String willTopic = Utils.decodeString(in); if (willTopic == null) { in.resetReaderIndex(); return; } message.setWillTopic(willTopic); } //Decode willMessage if (willFlag) { byte[] willMessage = Utils.readFixedLengthContent(in); if (willMessage == null) { in.resetReaderIndex(); return; } message.setWillMessage(willMessage); } //Compatibility check with v3.0, remaining length has precedence over //the user and password flags int readed = in.readerIndex() - start; if (readed == remainingLength) { out.add(message); return; } //Decode username if (userFlag) { String userName = Utils.decodeString(in); if (userName == null) { in.resetReaderIndex(); return; } message.setUsername(userName); } readed = in.readerIndex() - start; if (readed == remainingLength) { out.add(message); return; } //Decode password if (passwordFlag) { byte[] password = Utils.readFixedLengthContent(in); if (password == null) { in.resetReaderIndex(); return; } message.setPassword(password); } out.add(message); }
From source file:com.dempe.chat.common.mqtt.codec.PublishDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { LOG.debug("decode invoked with buffer {}", in); in.resetReaderIndex();/*w w w . j ava 2 s . c om*/ int startPos = in.readerIndex(); //Common decoding part PublishMessage message = new PublishMessage(); if (!decodeCommonHeader(message, in)) { LOG.debug("decode ask for more data after {}", in); in.resetReaderIndex(); return; } if (Utils.isMQTT3_1_1(ctx)) { if (message.getQos() == AbstractMessage.QOSType.MOST_ONE && message.isDupFlag()) { //bad protocol, if QoS=0 => DUP = 0 throw new CorruptedFrameException("Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation"); } if (message.getQos() == AbstractMessage.QOSType.RESERVED) { throw new CorruptedFrameException( "Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation"); } } int remainingLength = message.getRemainingLength(); //Topic name String topic = Utils.decodeString(in); if (topic == null) { in.resetReaderIndex(); return; } //[MQTT-3.3.2-2] The Topic Name in the PUBLISH Packet MUST NOT contain wildcard characters. if (topic.contains("+") || topic.contains("#")) { throw new CorruptedFrameException( "Received a PUBLISH with topic containing wild card chars, topic: " + topic); } //check topic is at least one char [MQTT-4.7.3-1] if (topic.length() == 0) { throw new CorruptedFrameException("Received a PUBLISH with topic without any character"); } message.setTopicName(topic); if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) { message.setMessageID(in.readUnsignedShort()); } int stopPos = in.readerIndex(); //read the payload int payloadSize = remainingLength - (stopPos - startPos - 2) + (Utils.numBytesToEncode(remainingLength) - 1); if (in.readableBytes() < payloadSize) { in.resetReaderIndex(); return; } ByteBuf bb = Unpooled.buffer(payloadSize); in.readBytes(bb); message.setPayload(bb.nioBuffer()); out.add(message); }
From source file:com.dempe.chat.common.mqtt.codec.Utils.java
License:Open Source License
/** * Read a byte array from the buffer, use two bytes as length information followed by length bytes. *///from w w w.jav a 2s .co m static byte[] readFixedLengthContent(ByteBuf in) throws UnsupportedEncodingException { if (in.readableBytes() < 2) { return null; } int strLen = in.readUnsignedShort(); if (in.readableBytes() < strLen) { return null; } byte[] strRaw = new byte[strLen]; in.readBytes(strRaw); return strRaw; }
From source file:com.digisky.outerproxy.server.OuterProxyHttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { LogMgr.debug("channelRead0()", "channelRead0"); if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);//from w w w .j a v a 2 s. c o m } } if (msg instanceof HttpContent) { String type = request.getUri().split("/")[1]; if (type.equals("email_activate") == true) { // GET? String[] tmp = request.getUri().split("="); String acode = tmp[tmp.length - 1]; LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + acode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}"); return; } else if (type.equals("email_pwd_reset") == true) { //? String[] tmp = request.getUri().split("="); String vcode = tmp[tmp.length - 1]; LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + vcode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"vcode\":\"" + vcode + "\"}"); return; } //email_active email_pwd_reset, //??? HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request); InterfaceHttpData postData = decoder.getBodyHttpData("val"); if (postData instanceof FileUpload == false) {//outerProxy???? ctx.close(); return; } FileUpload binData = (FileUpload) postData; ByteBuf content = null; try { content = binData.getByteBuf(); } catch (IOException e) { e.printStackTrace(); } //content??. , 0. ?(head)?id, json?, ?. ??, ???. //?content?head int index = content.bytesBefore((byte) 0); if (index < 0) { LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "ellegal request."); ctx.channel().close(); return; } byte[] head = new byte[index]; content.readBytes(head); String strHead = new String(head); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "head:" + strHead); JSONObject jo = JSONObject.parseObject(strHead); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "jo::app_id:" + jo.getString("app_id") + " jo::version:" + jo.getString("version")); content.readByte();//0 //?content?tail byte[] tail = new byte[content.readableBytes()]; content.readBytes(tail); String sjsonmsg = null; if (jo.getString("version").equals("0")) { //?0 byte[] bjsonmsg = XXTEA.decrypt(tail, key); int data_len = bjsonmsg.length; for (int i = bjsonmsg.length - 1; i != 0; --i) { if (bjsonmsg[i] == 0) { data_len--; continue; } else { break; } } try { sjsonmsg = new String(bjsonmsg, 0, data_len, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { //TODO?0, app_id. ??? LogMgr.error(OuterProxyHttpServerHandler.class.getName(), "?0, ??"); ctx.close(); return; } sjsonmsg = sjsonmsg.substring(sjsonmsg.indexOf('{'), sjsonmsg.indexOf('}') + 1);//? LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "sjson:" + sjsonmsg); //debug code //JSONObject jsonObj = JSONObject.parseObject(sjsonmsg); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "tmp.get:" + jsonObj.getString("model")); /* debug code //b.getBytes(n+1, tail, 0, b.g-n-1); for(int i=0; i< tail.length; ++i) { System.out.print(String.format("%x ", tail[i])); } */ //debug code //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "uri:" + request.getUri()); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"method:" + request.getMethod()); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"type:" + type); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "json:" + sjsonmsg); // ProcessServerManager.getInstance().process(ctx.channel(), type, sjsonmsg); } }
From source file:com.digitalpetri.opcua.sdk.client.api.identity.UsernameProvider.java
License:Open Source License
@Override public Tuple2<UserIdentityToken, SignatureData> getIdentityToken(EndpointDescription endpoint, ByteString serverNonce) throws Exception { UserTokenPolicy tokenPolicy = Arrays.stream(endpoint.getUserIdentityTokens()) .filter(t -> t.getTokenType() == UserTokenType.UserName).findFirst() .orElseThrow(() -> new Exception("no username token policy found")); String policyId = tokenPolicy.getPolicyId(); SecurityPolicy securityPolicy = SecurityPolicy.None; String securityPolicyUri = tokenPolicy.getSecurityPolicyUri(); try {// w w w. j a v a 2 s .c om if (securityPolicyUri != null && !securityPolicyUri.isEmpty()) { securityPolicy = SecurityPolicy.fromUri(securityPolicyUri); } else { securityPolicyUri = endpoint.getSecurityPolicyUri(); securityPolicy = SecurityPolicy.fromUri(securityPolicyUri); } } catch (Throwable t) { logger.warn("Error parsing SecurityPolicy for uri={}, falling back to no security.", securityPolicyUri); } byte[] passwordBytes = password.getBytes("UTF-8"); byte[] nonceBytes = Optional.ofNullable(serverNonce.bytes()).orElse(new byte[0]); ByteBuf buffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN); if (securityPolicy == SecurityPolicy.None) { buffer.writeBytes(passwordBytes); } else { buffer.writeInt(passwordBytes.length + nonceBytes.length); buffer.writeBytes(passwordBytes); buffer.writeBytes(nonceBytes); ByteString bs = endpoint.getServerCertificate(); X509Certificate certificate = CertificateUtil.decodeCertificate(bs.bytes()); int plainTextBlockSize = getPlainTextBlockSize(certificate, securityPolicy); int blockCount = (buffer.readableBytes() + plainTextBlockSize - 1) / plainTextBlockSize; Cipher cipher = getAndInitializeCipher(certificate, securityPolicy); ByteBuffer plainTextNioBuffer = buffer.nioBuffer(); ByteBuffer cipherTextNioBuffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN).nioBuffer(); for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) { int position = blockNumber * plainTextBlockSize; int limit = (blockNumber + 1) * plainTextBlockSize; plainTextNioBuffer.position(position).limit(limit); cipher.doFinal(plainTextNioBuffer, cipherTextNioBuffer); } cipherTextNioBuffer.flip(); buffer = Unpooled.wrappedBuffer(cipherTextNioBuffer); } byte[] bs = new byte[buffer.readableBytes()]; buffer.readBytes(bs); UserNameIdentityToken token = new UserNameIdentityToken(policyId, username, ByteString.of(bs), securityPolicy.getAsymmetricEncryptionAlgorithm().getUri()); return new Tuple2<>(token, new SignatureData()); }