예제 #1
0
  public NettyMessage decode(ByteBuf in) throws Exception {
    NettyMessage message = new NettyMessage();
    Header header = new Header();
    header.setCrcCode(in.readInt());
    header.setLength(in.readInt());
    header.setSessionID(in.readLong());
    header.setType(in.readByte());
    header.setPriority(in.readByte());

    int size = in.readInt();
    if (size > 0) {
      Map<String, Object> attch = new HashMap<String, Object>(size);
      int keySize = 0;
      byte[] keyArray = null;
      String key = null;
      for (int i = 0; i < size; i++) {
        keySize = in.readInt();
        keyArray = new byte[keySize];
        in.readBytes(keyArray);
        key = new String(keyArray, "UTF-8");
        attch.put(key, marshallingDecoder.decode(in));
      }
      keyArray = null;
      key = null;
      header.setAttachment(attch);
    }
    if (in.readableBytes() > 4) {
      message.setBody(marshallingDecoder.decode(in));
    }
    message.setHeader(header);
    return message;
  }
예제 #2
0
  @Override
  protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    // TODO Auto-generated method stub
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
      return null;
    }

    Message message = new Message();
    Header header = new Header();

    header.setSrcCode(in.readInt());
    header.setLength(in.readInt());
    header.setSessionId(in.readLong());
    header.setType(in.readByte());
    header.setPriority(in.readByte());
    int size = in.readInt();
    if (size > 0) {
      Map<String, Object> attch = new HashMap<String, Object>(size);
      int keySize = 0;
      byte[] keyArray = null;
      String key = null;
      for (int i = 0; i < size; i++) {
        keySize = in.readInt();
        keyArray = new byte[keySize];
        in.readBytes(keyArray);
        key = new String(keyArray, "UTF-8");
        attch.put(key, nettyMarshallingDecoder.decode(ctx, in));
      }
      keyArray = null;
      key = null;
      header.setAttachment(attch);
    }
    return message;
  }
예제 #3
0
 @Override
 public SocksRequest decode(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
   switch (state()) {
     case CHECK_PROTOCOL_VERSION:
       {
         version = SocksMessage.ProtocolVersion.fromByte(byteBuf.readByte());
         if (version != SocksMessage.ProtocolVersion.SOCKS5) {
           break;
         }
         checkpoint(State.READ_AUTH_SCHEMES);
       }
     case READ_AUTH_SCHEMES:
       {
         authSchemes.clear();
         authSchemeNum = byteBuf.readByte();
         for (int i = 0; i < authSchemeNum; i++) {
           authSchemes.add(SocksMessage.AuthScheme.fromByte(byteBuf.readByte()));
         }
         msg = new SocksInitRequest(authSchemes);
         break;
       }
   }
   ctx.pipeline().remove(this);
   return msg;
 }
    @Override
    public OFMeterFeaturesStatsReply readFrom(ByteBuf bb) throws OFParseError {
      int start = bb.readerIndex();
      // fixed value property version == 5
      byte version = bb.readByte();
      if (version != (byte) 0x5)
        throw new OFParseError("Wrong version: Expected=OFVersion.OF_14(5), got=" + version);
      // fixed value property type == 19
      byte type = bb.readByte();
      if (type != (byte) 0x13)
        throw new OFParseError("Wrong type: Expected=OFType.STATS_REPLY(19), got=" + type);
      int length = U16.f(bb.readShort());
      if (length != 32) throw new OFParseError("Wrong length: Expected=32(32), got=" + length);
      if (bb.readableBytes() + (bb.readerIndex() - start) < length) {
        // Buffer does not have all data yet
        bb.readerIndex(start);
        return null;
      }
      if (logger.isTraceEnabled()) logger.trace("readFrom - length={}", length);
      long xid = U32.f(bb.readInt());
      // fixed value property statsType == 11
      short statsType = bb.readShort();
      if (statsType != (short) 0xb)
        throw new OFParseError(
            "Wrong statsType: Expected=OFStatsType.METER_FEATURES(11), got=" + statsType);
      Set<OFStatsReplyFlags> flags = OFStatsReplyFlagsSerializerVer14.readFrom(bb);
      // pad: 4 bytes
      bb.skipBytes(4);
      OFMeterFeatures features = OFMeterFeaturesVer14.READER.readFrom(bb);

      OFMeterFeaturesStatsReplyVer14 meterFeaturesStatsReplyVer14 =
          new OFMeterFeaturesStatsReplyVer14(xid, flags, features);
      if (logger.isTraceEnabled()) logger.trace("readFrom - read={}", meterFeaturesStatsReplyVer14);
      return meterFeaturesStatsReplyVer14;
    }
예제 #5
0
 @Override
 protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out)
     throws Exception {
   switch (state()) {
     case CHECK_NULL_BYTE:
       {
         if (byteBuf.readByte() != (byte) 0x00) {
           break;
         }
         checkpoint(State.READ_CMD_HEADER);
       }
     case READ_CMD_HEADER:
       {
         cmdStatus = Socks4CmdStatus.valueOf(byteBuf.readByte());
         checkpoint(State.READ_CMD_ADDRESS);
       }
     case READ_CMD_ADDRESS:
       {
         port = byteBuf.readUnsignedShort();
         host = Socks4CommonUtils.intToIp(byteBuf.readInt());
         msg = new Socks4CmdResponse(cmdStatus, host, port);
       }
   }
   ctx.pipeline().remove(this);
   out.add(msg);
 }
예제 #6
0
  @Override
  public void fromBytes(ByteBuf buf) {
    posX = buf.readInt();
    posY = buf.readInt();
    posZ = buf.readInt();
    int size = buf.readInt();

    data = new ArrayList(size);
    for (int i = 0; i < size; i++) {
      byte tag = buf.readByte();
      if (tag == 0x00) {
        data.add(buf.readChar());
      } else if (tag == 0x01) {
        data.add(readString(buf));
      } else if (tag == 0x02) {
        data.add(buf.readFloat());
      } else if (tag == 0x03) {
        data.add(buf.readDouble());
      } else if (tag == 0x04) {
        data.add(buf.readByte());
      } else if (tag == 0x05) {
        data.add(buf.readLong());
      } else {
        data.add(buf.readInt());
      }
    }
  }
예제 #7
0
 public void applyStates(ISyncedTile tile) throws IOException {
   byte stateCount = state.readByte();
   for (int i = 0; i < stateCount; i++) {
     byte stateId = state.readByte();
     tile.getStateInstance(stateId).readData(state);
     tile.afterStateUpdated(stateId);
   }
 }
예제 #8
0
  public BlockChangeMessage decode(ByteBuf buffer) throws IOException {
    int x = buffer.readInt();
    int y = buffer.readByte();
    int z = buffer.readInt();
    int type = ByteBufUtils.readVarInt(buffer);
    int metadata = buffer.readByte();

    return new BlockChangeMessage(x, y, z, type, metadata);
  }
 @Override
 public void fromBytes(ByteBuf buf) {
   this.x = buf.readInt();
   this.y = buf.readInt();
   this.z = buf.readInt();
   this.orientation = buf.readByte();
   this.state = buf.readByte();
   int customNameLength = buf.readInt();
   this.customName = new String(buf.readBytes(customNameLength).array());
   int ownerLength = buf.readInt();
   this.owner = new String(buf.readBytes(ownerLength).array());
 }
예제 #10
0
 @Override
 public ByteBuf translateFrame(ByteBuf readBuffer)
     throws LimitExedeedException, InvalidDataException {
   while (readBuffer.isReadable()) {
     switch (status) {
       case STATUS_H:
         h = readBuffer.readByte();
         status = STATUS_L;
         break;
       case STATUS_L:
         l = readBuffer.readByte();
         final int blen =
             Protocol.order == ByteOrder.BIG_ENDIAN
                 ? (0x0000ff00 & (h << 8)) | (0x000000ff & l)
                 : (0x0000ff00 & (l << 8)) | (0x000000ff & h);
         if (context != null) {
           if (blen <= 0 || blen > maxFrameSize) {
             throw new LimitExedeedException("帧长度非法:" + h + "/" + l + ":" + blen);
           }
         }
         incompleteframe = PooledByteBufAllocator.DEFAULT.buffer(blen + 16 + 2);
         incompleteframe = incompleteframe.order(Protocol.order);
         incompleteframe.writeShort(blen);
         status = STATUS_C;
         break;
       case STATUS_C:
         int len = incompleteframe.writableBytes() - 16;
         len = len < readBuffer.readableBytes() ? len : readBuffer.readableBytes();
         // incompleteframe.writeBytes(readBuffer, len);
         if (readBuffer.hasMemoryAddress()) {
           PlatformDependent.copyMemory(
               readBuffer.memoryAddress() + readBuffer.readerIndex(),
               incompleteframe.memoryAddress() + incompleteframe.writerIndex(),
               len);
         } else if (readBuffer.hasArray()) {
           PlatformDependent.copyMemory(
               readBuffer.array(),
               readBuffer.arrayOffset() + readBuffer.readerIndex(),
               incompleteframe.memoryAddress() + incompleteframe.writerIndex(),
               len);
         }
         incompleteframe.writerIndex(incompleteframe.writerIndex() + len);
         readBuffer.readerIndex(readBuffer.readerIndex() + len);
         if ((incompleteframe.writableBytes() - 16) <= 0) {
           status = STATUS_H;
           return incompleteframe;
         }
         break;
     }
   }
   return null;
 }
 ClayLump read(ByteBuf in) throws IOException {
   minX = in.readByte();
   minY = in.readByte();
   minZ = in.readByte();
   maxX = in.readByte();
   maxY = in.readByte();
   maxZ = in.readByte();
   icon_id = DataUtil.getBlock(in.readShort());
   icon_md = in.readByte();
   icon_side = in.readByte();
   quat = Quaternion.read(in);
   return this;
 }
예제 #12
0
 @Override
 public void fromBytes(ByteBuf buf) {
   super.fromBytes(buf);
   byte command = buf.readByte();
   if (command == 0) {
     mat = Mats.values()[buf.readByte()];
   } else if (command == 1) {
     enchant = buf.readShort();
   } else if (command == 2) {
   } else {
     throw new InvalidParameterException();
   }
 }
예제 #13
0
  @Override
  public void readBytes(ByteBuf bytes) {
    width = bytes.readByte();
    height = bytes.readByte();

    array = new byte[height][width];

    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {
        array[y][x] = bytes.readByte();
      }
    }
  }
  @Test
  public void testMemcachedRequestEncoder() {

    MemcachedRequest request = new MemcachedRequest(Opcode.SET, "key1", "value1");

    EmbeddedChannel channel = new EmbeddedChannel(new MemcachedRequestEncoder());

    Assert.assertTrue(channel.writeOutbound(request));

    ByteBuf encoded = (ByteBuf) channel.readOutbound();

    Assert.assertNotNull(encoded);

    Assert.assertEquals(request.magic(), encoded.readByte() & 0xFF);

    Assert.assertEquals(request.opCode(), encoded.readByte() & 0xFF);

    Assert.assertEquals(4, encoded.readShort());

    Assert.assertEquals((byte) 0x08, encoded.readByte() & 0xFF);

    Assert.assertEquals((byte) 0, encoded.readByte() & 0xFF);

    Assert.assertEquals(0, encoded.readShort());
    // 注意发送端发的什么位模式这里就收什么位模式。
    // 其实这里也要注意,如果传的刚好是0x8000,解析出来也要注意符号的问题。主要要弄清java是怎么补位和截断,然后保证传的位模式不要被误解。

    Assert.assertEquals(4 + 6 + 8, encoded.readInt());

    Assert.assertEquals(request.id(), encoded.readInt());

    Assert.assertEquals(request.cas(), encoded.readLong());

    Assert.assertEquals(request.flags(), encoded.readInt());

    Assert.assertEquals(request.expires(), encoded.readInt());

    byte[] data = new byte[encoded.readableBytes()];

    encoded.readBytes(data);

    Assert.assertEquals((request.key() + request.body()).getBytes(CharsetUtil.UTF_8), data);

    Assert.assertFalse(encoded.isReadable());

    Assert.assertFalse(channel.finish());

    Assert.assertNull(channel.readInbound());
  }
 public static OFFlowRemovedReason readFrom(ByteBuf bb) throws OFParseError {
   try {
     return ofWireValue(bb.readByte());
   } catch (IllegalArgumentException e) {
     throw new OFParseError(e);
   }
 }
  @Override
  protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    ChannelPipeline p = ctx.pipeline();
    SocksProtocolVersion version = SocksProtocolVersion.valueOf(in.readByte());
    System.out.println(version);
    in.resetReaderIndex();
    switch (version) {
      case SOCKS4a:
        p.addLast(new Socks4CmdRequestDecoder());
        p.addLast(Socks4MessageEncoder.INSTANCE);

        break;
      case SOCKS5:
        p.addLast(new Socks5InitRequestDecoder());
        p.addLast(Socks5MessageEncoder.INSTANCE);

        break;
      case UNKNOWN:
        in.clear();
        ctx.close();
        return;
    }
    p.addLast(SocksServerHandler.INSTANCE);
    p.remove(this);
  }
예제 #17
0
  @Override
  protected void decode(
      ChannelHandlerContext channelHandlerContext, FMLProxyPacket fmlProxyPacket, List<Object> out)
      throws Exception {
    ByteBuf payload = fmlProxyPacket.payload();
    byte discriminator = payload.readByte();
    Class<? extends AbstractPacketOld> clazz = this.packets.get(discriminator);
    if (clazz == null) {
      throw new NullPointerException("No packet registered for discriminator: " + discriminator);
    }

    AbstractPacketOld packet = clazz.newInstance();
    packet.decodeInto(channelHandlerContext, payload.slice());

    EntityPlayer player;
    switch (FMLCommonHandler.instance().getEffectiveSide()) {
      case CLIENT:
        player = PacketHandlerOld.getClientPlayer();
        packet.handleClientSide(player);
        break;

      case SERVER:
        INetHandler netHandler =
            channelHandlerContext.channel().attr(NetworkRegistry.NET_HANDLER).get();
        player = ((NetHandlerPlayServer) netHandler).playerEntity;
        packet.handleServerSide(player);
        break;

      default:
    }
    out.add(packet);
  }
예제 #18
0
 @Override
 public void split(ChannelHandlerContext ctx, ByteBuf input, List<Object> list) throws Exception {
   input.markReaderIndex();
   final byte[] array = new byte[3];
   for (int i = 0; i < array.length; ++i) {
     if (!input.isReadable()) {
       input.resetReaderIndex();
       return;
     }
     array[i] = input.readByte();
     if (array[i] >= 0) {
       final PacketDataSerializer packetDataSerializer =
           new PacketDataSerializer(
               Unpooled.wrappedBuffer(array), ProtocolVersion.MINECRAFT_1_7_10);
       try {
         final int length = packetDataSerializer.readVarInt();
         if (input.readableBytes() < length) {
           input.resetReaderIndex();
           return;
         }
         list.add(input.readBytes(length));
         return;
       } finally {
         packetDataSerializer.release();
       }
     }
   }
   throw new CorruptedFrameException("length wider than 21-bit");
 }
 @Override
 public void fromBytes(ByteBuf buf) {
   data = Unpooled.buffer();
   while (buf.readableBytes() > 0) {
     data.writeByte(buf.readByte());
   }
   this.index = data.readInt();
 }
예제 #20
0
 private byte[] getPayloadFromByteBuf(ByteBuf buf) {
   int length = buf.readableBytes();
   byte[] ret = new byte[length];
   for (int i = 0; i < length; i++) {
     ret[i] = buf.readByte();
   }
   return ret;
 }
 @Override
 public void fromBytes(ByteBuf buf) {
   x = buf.readInt();
   y = buf.readInt();
   z = buf.readInt();
   _freq = buf.readInt();
   _isPublic = buf.readBoolean();
   _state = buf.readByte();
 }
예제 #22
0
  public void handlePacket(ByteBuf buf) {
    int sides = buf.readUnsignedByte();
    enabledSides = (byte) (sides & 15);
    invertedSides = (byte) (sides >> 4);

    for (int i = 0; i <= 3; i++) {
      inputs[i] = outputClient[i] = 0;
      EnumFacing dir = EnumFacing.getFront(i + 2);
      if (getType(dir) != Connection.NONE) {
        if (getType(dir).isInput()) {
          inputs[i] = buf.readByte();
        } else {
          outputClient[i] = buf.readByte();
        }
      }
    }
    markRenderUpdate();
  }
예제 #23
0
 @Override
 public void handlePacket(ByteBuf data) {
   super.handlePacket(data);
   if (type == WireKind.NORMAL) {
     byte d = data.readByte();
     signalLevel = d << 8;
     markRenderUpdate();
   }
 }
 // automatic.
 public PacketMatterCannon(ByteBuf stream) {
   this.x = stream.readFloat();
   this.y = stream.readFloat();
   this.z = stream.readFloat();
   this.dx = stream.readFloat();
   this.dy = stream.readFloat();
   this.dz = stream.readFloat();
   this.len = stream.readByte();
 }
    @Override
    public OFBsnSetPktinSuppressionRequest readFrom(ByteBuf bb) throws OFParseError {
      int start = bb.readerIndex();
      // fixed value property version == 3
      byte version = bb.readByte();
      if (version != (byte) 0x3)
        throw new OFParseError("Wrong version: Expected=OFVersion.OF_12(3), got=" + version);
      // fixed value property type == 4
      byte type = bb.readByte();
      if (type != (byte) 0x4)
        throw new OFParseError("Wrong type: Expected=OFType.EXPERIMENTER(4), got=" + type);
      int length = U16.f(bb.readShort());
      if (length != 32) throw new OFParseError("Wrong length: Expected=32(32), got=" + length);
      if (bb.readableBytes() + (bb.readerIndex() - start) < length) {
        // Buffer does not have all data yet
        bb.readerIndex(start);
        return null;
      }
      if (logger.isTraceEnabled()) logger.trace("readFrom - length={}", length);
      long xid = U32.f(bb.readInt());
      // fixed value property experimenter == 0x5c16c7L
      int experimenter = bb.readInt();
      if (experimenter != 0x5c16c7)
        throw new OFParseError(
            "Wrong experimenter: Expected=0x5c16c7L(0x5c16c7L), got=" + experimenter);
      // fixed value property subtype == 0xbL
      int subtype = bb.readInt();
      if (subtype != 0xb)
        throw new OFParseError("Wrong subtype: Expected=0xbL(0xbL), got=" + subtype);
      boolean enabled = (bb.readByte() != 0);
      // pad: 1 bytes
      bb.skipBytes(1);
      int idleTimeout = U16.f(bb.readShort());
      int hardTimeout = U16.f(bb.readShort());
      int priority = U16.f(bb.readShort());
      U64 cookie = U64.ofRaw(bb.readLong());

      OFBsnSetPktinSuppressionRequestVer12 bsnSetPktinSuppressionRequestVer12 =
          new OFBsnSetPktinSuppressionRequestVer12(
              xid, enabled, idleTimeout, hardTimeout, priority, cookie);
      if (logger.isTraceEnabled())
        logger.trace("readFrom - read={}", bsnSetPktinSuppressionRequestVer12);
      return bsnSetPktinSuppressionRequestVer12;
    }
예제 #26
0
 /** decode stream to object */
 public ResponseSocketBlock decode(ByteBuf buf) throws IOException {
   // * --------------------------------------------------------bytes =13
   // * byte[1]  version                              RSF版本(0x80)
   byte version = buf.readByte();
   // * byte[8]  requestID                            包含的请求ID
   long requestID = buf.readLong();
   // * byte[1]  keepData                             保留区
   buf.skipBytes(1);
   // * byte[3]  contentLength                        内容大小
   buf.skipBytes(3); // .readUnsignedMedium()
   //
   ResponseSocketBlock res = new ResponseSocketBlock();
   res.setVersion(version);
   res.setRequestID(requestID);
   // * --------------------------------------------------------bytes =8
   // * byte[2]  status                               响应状态
   res.setStatus(buf.readShort());
   // * byte[2]  serializeType-(attr-index)           序列化策略
   res.setSerializeType(buf.readShort());
   // * byte[2]  returnType-(attr-index)              返回类型
   res.setReturnType(buf.readShort());
   // * byte[2]  returnData-(attr-index)              返回数据
   res.setReturnData(buf.readShort());
   // * --------------------------------------------------------bytes =1 ~ 1021
   // * byte[1]  optionCount                          选项参数总数
   byte optionCount = buf.readByte();
   for (int i = 0; i < optionCount; i++) {
     // * byte[4]  attr-0-(attr-index,attr-index)   选项参数
     int mergeData = buf.readInt();
     res.addOption(mergeData);
   }
   // * --------------------------------------------------------bytes =6 ~ 8192
   // * byte[2]  attrPool-size (Max = 2047)           池大小
   short attrPoolSize = buf.readShort();
   for (int i = 0; i < attrPoolSize; i++) {
     // * byte[4] att-length                        属性1大小
     int length = buf.readInt();
     res.addPoolData(length);
   }
   // * --------------------------------------------------------bytes =n
   // * dataBody                                      数据内容
   res.fillFrom(buf.readBytes(res.getPoolSize()));
   return res;
 }
예제 #27
0
  public StationFrameData(String ip, ByteBuf data) {
    this.ip = ip;
    byte labelCount = data.readByte();
    if (labelCount <= 0) {
      throw new ClientException(ErrorCode.INVALID_REQUEST, "收到的标签数量为负数:" + labelCount);
    }

    labelInfos = new LabelInfo[labelCount];
    for (int i = 0; i < labelCount; i++) {

      long labelId = data.readLong();
      byte rssi = data.readByte();
      byte power = data.readByte();
      LabelInfo labelInfo = new LabelInfo(labelId, rssi, power);
      labelInfos[i] = labelInfo;
    }

    time = System.currentTimeMillis();
  }
예제 #28
0
 public DestroyAllIdentificator(ByteBuf pBuf, int pTargetOrMeta, int pChainOrMeta) {
   this();
   // Target
   if (pBuf.isReadable(4)) {
     for (int li = pBuf.readInt(); li > 0; li--) {
       add(pBuf.readInt(), pBuf.readByte() | pTargetOrMeta);
     }
   }
   // Chain
   if (pBuf.isReadable(4)) {
     int li = pBuf.readInt();
     if (li > 0) {
       chain = new DestroyAllIdentificator();
       for (; li > 0; li--) {
         chain.add(pBuf.readInt(), pBuf.readByte() | pChainOrMeta);
       }
     }
   }
 }
예제 #29
0
  private void processHeaderState(ByteBuf in) throws Http2Exception {
    if (in.readableBytes() < FRAME_HEADER_LENGTH) {
      // Wait until the entire frame header has been read.
      return;
    }

    // Read the header and prepare the unmarshaller to read the frame.
    payloadLength = in.readUnsignedMedium();
    if (payloadLength > maxFrameSize) {
      throw connectionError(
          PROTOCOL_ERROR, "Frame length: %d exceeds maximum: %d", payloadLength, maxFrameSize);
    }
    frameType = in.readByte();
    flags = new Http2Flags(in.readUnsignedByte());
    streamId = readUnsignedInt(in);

    switch (frameType) {
      case DATA:
        verifyDataFrame();
        break;
      case HEADERS:
        verifyHeadersFrame();
        break;
      case PRIORITY:
        verifyPriorityFrame();
        break;
      case RST_STREAM:
        verifyRstStreamFrame();
        break;
      case SETTINGS:
        verifySettingsFrame();
        break;
      case PUSH_PROMISE:
        verifyPushPromiseFrame();
        break;
      case PING:
        verifyPingFrame();
        break;
      case GO_AWAY:
        verifyGoAwayFrame();
        break;
      case WINDOW_UPDATE:
        verifyWindowUpdateFrame();
        break;
      case CONTINUATION:
        verifyContinuationFrame();
        break;
      default:
        // Unknown frame type, could be an extension.
        break;
    }

    // Start reading the payload for the frame.
    state = State.FRAME_PAYLOAD;
  }
예제 #30
0
 @Override
 public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
   ByteBuf in = (ByteBuf) msg;
   try {
     while (in.isReadable()) { // (1)
       System.out.print((char) in.readByte());
       System.out.flush();
     }
   } finally {
     ReferenceCountUtil.release(msg); // (2)
   }
 }