List of usage examples for io.netty.buffer ByteBuf order
@Deprecated public abstract ByteBuf order(ByteOrder endianness);
From source file:eu.xworlds.util.raknet.RaknetDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception { final ByteBuf buf = msg.content(); buf.order(ByteOrder.BIG_ENDIAN); final byte id = buf.readByte(); final Constructor<? extends RaknetMessage> ctor = this.messages.get(Byte.valueOf(id)); if (ctor == null) { final RaknetMessage result = new InvalidRaknetMessage(id, buf, msg.sender(), msg.recipient()); out.add(result);/*from w w w .jav a 2s . c o m*/ } else { try { final RaknetMessage result = ctor.newInstance(buf, msg.sender(), msg.recipient()); out.add(result); } catch (Exception ex) { final RaknetMessage result = new InvalidRaknetMessage(id, buf, msg.sender(), msg.recipient(), ex); out.add(result); } } }
From source file:gwlpr.protocol.handshake.HandshakeHandler.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { ByteBuf buf = in.order(ByteOrder.LITTLE_ENDIAN); switch (server) { case LoginServer: // client version: {/*from ww w . j a va 2 s . c o m*/ // lengthcheck if (buf.readableBytes() < (P000_ClientVersion.getLength() + P000_ClientSeed.getLength())) { return; } // get the header P000_ClientVersion.Header header = P000_ClientVersion.serializeHeader(buf); // check the header if (header == null || !P000_ClientVersion.check(header)) { return; } // get the data P000_ClientVersion.Payload payload = P000_ClientVersion.serializePayload(buf); LOGGER.debug(String.format("Got the client version: %d", payload.ClientVersion)); } break; case GameServer: // verify client: { // lengthcheck if (buf.readableBytes() < (P000_VerifyClient.getLength() + P000_ClientSeed.getLength())) { return; } // get the header P000_VerifyClient.Header header = P000_VerifyClient.serializeHeader(buf); // check the header if (header == null || !P000_VerifyClient.check(header)) { return; } // get the data verifyClient = P000_VerifyClient.serializePayload(buf); LOGGER.debug(String.format("Got the verify client packet.")); } break; } // client seed: // get the header P000_ClientSeed.Header header = P000_ClientSeed.serializeHeader(buf); // check the header if (header == null || !P000_ClientSeed.check(header)) { return; } // get the data P000_ClientSeed.Payload payload = P000_ClientSeed.serializePayload(buf); LOGGER.debug("Got the client seed packet."); // INITIALIZE ENCRYPTION WITH THE CLIENT SEED PAYLOAD // generate the shared key byte[] sharedKeyBytes = EncryptionUtils.generateSharedKey(payload.ClientPublicKey); // start RC4 key generation byte[] randomBytes = new byte[20]; new SecureRandom().nextBytes(randomBytes); final byte[] rc4Key = EncryptionUtils.hash(randomBytes); // encrypt the RC4 key before sending it to the client byte[] xoredRandomBytes = EncryptionUtils.XOR(randomBytes, sharedKeyBytes); // INITIALIZATION OF ENCRYPTION DONE // we can set the RC4 decoder now... if encryption is enabled if (encryption == EncryptionOptions.Enable) { RC4Codec.Decoder decoder = new RC4Codec.Decoder(rc4Key); ctx.pipeline().addFirst(decoder); LOGGER.debug("RC4Decoder added to pipeline."); } // now send the server seed packet P001_ServerSeed serverSeed = new P001_ServerSeed(); serverSeed.setEncryptedRC4Key(xoredRandomBytes); buf = ctx.alloc().buffer(70).order(ByteOrder.LITTLE_ENDIAN); serverSeed.serializeInto(buf); ChannelFuture cf = ctx.writeAndFlush(buf); // also remove this handler ctx.pipeline().remove(this); // set the RC4 encoder only after the serverseed packet has been send! cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (encryption == EncryptionOptions.Enable) { // add the rc4 codec if encryption is enabled RC4Codec.Encoder encoder = new RC4Codec.Encoder(rc4Key); ctx.pipeline().addFirst(encoder); LOGGER.debug("RC4Encoder added to pipeline."); } // tell the channel's context that handshake has been done ctx.channel().attr(GameAppContextKey.KEY).get() .trigger(new HandShakeDoneEvent(ctx.channel(), verifyClient)); } }); }
From source file:gwlpr.protocol.NettyGWCodec.java
License:Open Source License
@Override public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> result) { ByteBuf buf = in.order(ByteOrder.LITTLE_ENDIAN); while (buf.isReadable()) { buf.markReaderIndex();/* w w w. jav a 2 s . co m*/ // get the header failsafe int header = buf.readableBytes() >= 2 ? buf.readShort() : -1; // failcheck if (header == -1) { return; } // try get the message class Class<? extends GWMessage> messageClazz = getByHeader(header); // failcheck if (messageClazz == null) { buf.resetReaderIndex(); return; } // try retrieve the serialization filter NettySerializationFilter filter = GWMessageSerializationRegistry.getFilter(messageClazz); // failcheck if (filter == null) { buf.resetReaderIndex(); return; } // try create the message Message message; try { message = messageClazz.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { LOGGER.error("Could not create an instance of an message.", ex); buf.resetReaderIndex(); return; } // dont forget to initialize the message message.init(ctx.channel()); // try serialize the message if (!filter.deserialize(buf, message)) { buf.resetReaderIndex(); return; } // finally add the message result.add(message); LOGGER.debug("Got: {}", message.toString()); } }
From source file:gwlpr.protocol.NettyGWCodec.java
License:Open Source License
@Override public void encode(ChannelHandlerContext ctx, GWMessage message, ByteBuf out) { ByteBuf result = out.order(ByteOrder.LITTLE_ENDIAN); LOGGER.debug("Put: {}", message.toString()); GWMessage gwact = message;/* w ww . ja va 2 s. co m*/ int header = gwact.getHeader(); // try retrieve the serialization filter NettySerializationFilter filter = GWMessageSerializationRegistry.getFilter(gwact.getClass()); if (filter == null) { LOGGER.error("Could not find a filter for given message."); return; } // write the header result.writeShort(header); // serialize the message filter.serialize(result, message); }
From source file:impl.underdark.transport.bluetooth.BtLink.java
License:Open Source License
private void inputLoop() { // Input I/O thread. sendHelloFrame();//from w w w . j a v a2 s . c o m int bufferSize = 4096; ByteBuf inputData = Unpooled.buffer(bufferSize); inputData.order(ByteOrder.BIG_ENDIAN); try { int len; while (true) { inputData.ensureWritable(bufferSize, true); len = inputStream.read(inputData.array(), inputData.writerIndex(), bufferSize); if (len <= 0) break; inputData.writerIndex(inputData.writerIndex() + len); if (!formFrames(inputData)) break; inputData.discardReadBytes(); inputData.capacity(inputData.writerIndex() + bufferSize); } // while } catch (InterruptedIOException ex) { Logger.warn("bt input timeout: {}", ex); try { inputStream.close(); } catch (IOException ioex) { } notifyDisconnect(); return; } catch (Exception ex) { Logger.warn("bt input read failed.", ex); try { inputStream.close(); } catch (IOException ioex) { } notifyDisconnect(); return; } Logger.debug("bt input read end."); notifyDisconnect(); }
From source file:impl.underdark.transport.bluetooth.discovery.ble.transport.central.BleCentralLink.java
License:Open Source License
public void sendFrameInternal(byte[] frameData) { if (!connected) return;/*from w w w.ja v a2s. com*/ ByteBuf frameBuf = Unpooled.buffer(); frameBuf.order(ByteOrder.BIG_ENDIAN); frameBuf.writeInt(frameData.length); frameBuf.writeBytes(frameData); if (outputBuffer == null) { outputBuffer = frameBuf; return; } outputQueue.offer(frameBuf); }
From source file:impl.underdark.transport.bluetooth.discovery.ble.transport.peripheral.BlePeripheral.java
License:Open Source License
void onCharacteristicReadRequest(final BluetoothDevice device, final int requestId, final int offset, final BluetoothGattCharacteristic characteristic) { //Logger.debug("ble peripheral onCharacteristicReadRequest"); if (BleConfig.charactNodeIdUuid.equals(characteristic.getUuid())) { ByteBuf buffer = Unpooled.buffer(); buffer.order(ByteOrder.BIG_ENDIAN); buffer.writeLong(this.nodeId); if (offset >= buffer.readableBytes()) { Logger.warn("ble peripheral read nodeId failed - invalid offset {}", offset); gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_INVALID_OFFSET, offset, null); return; }/* w w w .j av a 2s . c om*/ byte[] value = Arrays.copyOfRange(buffer.array(), offset, Math.min(buffer.readableBytes() - offset, BleConfig.charactValueSizeMax)); gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value); return; } // nodeId if (BleConfig.charactAddressUuid.equals(characteristic.getUuid())) { byte[] address = BtUtils.getBytesFromAddress(this.adapter.getAddress()); if (address == null) { gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, offset, null); return; } onAddressReadRequest(address, device, requestId, offset); return; } // address gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED, offset, null); }
From source file:impl.underdark.transport.bluetooth.discovery.ble.transport.peripheral.BlePeripheral.java
License:Open Source License
private void onAddressReadRequest(byte[] address, BluetoothDevice device, int requestId, int offset) { if (address == null) { gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, offset, null); return;/*from w ww . j av a 2s . c o m*/ } ByteBuf buffer = Unpooled.buffer(); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.writeBytes(address); if (offset >= buffer.readableBytes()) { Logger.warn("ble peripheral read address failed - invalid offset {}", offset); gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_INVALID_OFFSET, offset, null); return; } byte[] value = Arrays.copyOfRange(buffer.array(), offset, Math.min(buffer.readableBytes() - offset, BleConfig.charactValueSizeMax)); gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value); }
From source file:impl.underdark.transport.bluetooth.discovery.ble.transport.peripheral.BlePeripheral.java
License:Open Source License
private void describeCharacteristic(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) { String description = ""; if (BleConfig.charactAddressUuid.equals(descriptor.getCharacteristic().getUuid())) description = "address"; if (BleConfig.charactNodeIdUuid.equals(descriptor.getCharacteristic().getUuid())) description = "nodeId"; if (BleConfig.charactJackUuid.equals(descriptor.getCharacteristic().getUuid())) description = "jack"; if (BleConfig.charactStreamUuid.equals(descriptor.getCharacteristic().getUuid())) description = "stream"; ByteBuf buffer = Unpooled.buffer(); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.writeBytes(description.getBytes(Charset.forName("utf-8"))); if (offset >= buffer.readableBytes()) { Logger.warn("ble peripheral describe charact '{}' failed - invalid offset {}", description, offset); gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_INVALID_OFFSET, offset, null); return;// w w w.j a v a 2 s. c om } byte[] value = Arrays.copyOfRange(buffer.array(), offset, Math.min(buffer.readableBytes() - offset, BleConfig.charactValueSizeMax)); gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value); }
From source file:impl.underdark.transport.bluetooth.discovery.ble.transport.peripheral.BlePeripheral.java
License:Open Source License
private void describeCharacteristicFormat(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) { // https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml // https://developer.mbed.org/teams/Bluetooth-Low-Energy/code/BLE_API/file/ecbc3405c66e/public/GattCharacteristic.h byte format = 10; if (BleConfig.charactAddressUuid.equals(descriptor.getCharacteristic().getUuid())) format = 25;/*from ww w. j a va2s . co m*/ if (BleConfig.charactNodeIdUuid.equals(descriptor.getCharacteristic().getUuid())) format = 18; ByteBuf buffer = Unpooled.buffer(); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.writeByte(format); // format buffer.writeByte(0); // exponent buffer.writeShort(0x2700); // unit buffer.writeByte(1); // namespace buffer.writeShort(0); // description if (offset >= buffer.readableBytes()) { Logger.warn("ble peripheral format charact failed - invalid offset {}", offset); gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_INVALID_OFFSET, offset, null); return; } byte[] value = Arrays.copyOfRange(buffer.array(), offset, Math.min(buffer.readableBytes() - offset, BleConfig.charactValueSizeMax)); gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value); }