private static void checkHeader(ByteBuf buffer, boolean hasMask) {
   assertEquals(
       "Wrong oxm-class", OxmMatchConstants.OPENFLOW_BASIC_CLASS, buffer.readUnsignedShort());
   short fieldAndMask = buffer.readUnsignedByte();
   assertEquals("Wrong oxm-field", OxmMatchConstants.SCTP_DST, fieldAndMask >>> 1);
   assertEquals("Wrong hasMask", hasMask, (fieldAndMask & 1) != 0);
   assertEquals("Wrong length", EncodeConstants.SIZE_OF_SHORT_IN_BYTES, buffer.readUnsignedByte());
 }
  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.readUnsignedShort() & FRAME_LENGTH_MASK;
    frameType = Http2FrameType.forTypeCode(in.readUnsignedByte());
    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;
      case ALT_SVC:
        verifyAltSvcFrame();
        break;
      case BLOCKED:
        verifyBlockedFrame();
        break;
      default:
        throw protocolError("Unsupported frame type: %s", frameType);
    }

    // Start reading the payload for the frame.
    state = State.FRAME_PAYLOAD;
  }
  int decode(ByteBuf buf) {
    // ByteBuf bbuf = Unpooled.wrappedBuffer(buf);
    // ByteBuf tmpbuf = bbuf.readerIndex(pos);

    this.msgType = buf.readUnsignedInt();
    this.seqNo = buf.readUnsignedByte();
    this.msgLen = buf.readUnsignedShort();
    this.flags = buf.readUnsignedByte();

    return 0;
  }
  @Test
  public void testDummyIncomingAck() {
    ByteBuf expectResult = Unpooled.wrappedBuffer(new byte[] {(byte) 0x82, 0x00, 0x00});

    ch.writeOutbound(UsnMessageHelper.makeDummyIncomingAck());

    ByteBuf outBuff = (ByteBuf) ch.readOutbound();

    while (expectResult.isReadable()) {
      assertEquals(expectResult.readUnsignedByte(), outBuff.readUnsignedByte());
    }
  }
Example #5
0
 @Override
 public void receiveCommand(String command, Side side, Object sender, ByteBuf stream) {
   if (side.isServer()) {
     if ("setLabel".equals(command)) {
       setLabel(NetworkUtils.readUTF(stream));
     } else if ("switchButton".equals(command)) {
       switchButton(stream.readUnsignedByte(), stream.readUnsignedByte());
     } else if ("setStack".equals(command)) {
       setStack(
           stream.readUnsignedByte(), stream.readUnsignedByte(), NetworkUtils.readStack(stream));
     }
   }
 }
  @Override
  public Subobject parseSubobject(final ByteBuf buffer, final boolean loose)
      throws PCEPDeserializerException {
    Preconditions.checkArgument(
        buffer != null && buffer.isReadable(),
        "Array of bytes is mandatory. Can't be null or empty.");
    if (buffer.readableBytes() < HEADER_LENGTH) {
      throw new PCEPDeserializerException(
          "Wrong length of array of bytes. Passed: "
              + buffer.readableBytes()
              + "; Expected: >"
              + HEADER_LENGTH
              + ".");
    }
    final BitArray reserved = BitArray.valueOf(buffer, FLAGS_SIZE);
    final short cType = buffer.readUnsignedByte();

    final LabelType labelType = this.registry.parseLabel(cType, buffer.slice());
    if (labelType == null) {
      throw new PCEPDeserializerException(
          "Unknown C-TYPE for ero label subobject. Passed: " + cType);
    }
    final LabelBuilder builder = new LabelBuilder();
    builder.setUniDirectional(reserved.get(U_FLAG_OFFSET));
    builder.setLabelType(labelType);
    return new SubobjectBuilder()
        .setLoose(loose)
        .setSubobjectType(new LabelCaseBuilder().setLabel(builder.build()).build())
        .build();
  }
 public void readData(ByteBuf data) {
   id = data.readShort();
   parseData(data.readUnsignedShort(), data.readUnsignedByte());
   dX = data.readFloat();
   dY = data.readFloat();
   dZ = data.readFloat();
 }
 private static void addIcmpv6TypeValue(ByteBuf input, MatchEntryBuilder builder) {
   Icmpv6TypeCaseBuilder caseBuilder = new Icmpv6TypeCaseBuilder();
   Icmpv6TypeBuilder icmpBuilder = new Icmpv6TypeBuilder();
   icmpBuilder.setIcmpv6Type(input.readUnsignedByte());
   caseBuilder.setIcmpv6Type(icmpBuilder.build());
   builder.setMatchEntryValue(caseBuilder.build());
 }
 @Override
 public void readData(ByteBuf data) {
   super.readData(data);
   displayPower = new short[] {0, 0, 0, 0, 0, 0};
   overload = data.readBoolean();
   for (int i = 0; i < displayPower.length; i++) {
     displayPower[i] = data.readUnsignedByte();
   }
 }
 private void readAltSvcFrame(
     ChannelHandlerContext ctx, ByteBuf payload, Http2FrameObserver observer)
     throws Http2Exception {
   long maxAge = payload.readUnsignedInt();
   int port = payload.readUnsignedShort();
   payload.skipBytes(1);
   short protocolIdLength = payload.readUnsignedByte();
   ByteBuf protocolId = payload.readSlice(protocolIdLength);
   short hostLength = payload.readUnsignedByte();
   String host = payload.toString(payload.readerIndex(), hostLength, UTF_8);
   payload.skipBytes(hostLength);
   String origin = null;
   if (payload.isReadable()) {
     origin = payload.toString(UTF_8);
     payload.skipBytes(payload.readableBytes());
   }
   observer.onAltSvcRead(ctx, streamId, maxAge, port, protocolId, host, origin);
 }
 private void readPriorityFrame(
     ChannelHandlerContext ctx, ByteBuf payload, Http2FrameObserver observer)
     throws Http2Exception {
   long word1 = payload.readUnsignedInt();
   boolean exclusive = (word1 & 0x80000000L) > 0;
   int streamDependency = (int) (word1 & 0x7FFFFFFFL);
   short weight = (short) (payload.readUnsignedByte() + 1);
   observer.onPriorityRead(ctx, streamId, streamDependency, weight, exclusive);
 }
  @Override
  public void decode(ByteBuf data) {
    byteCount = data.readUnsignedByte();

    registers = new int[byteCount / 2];
    for (int i = 0; i < registers.length; i++) {
      registers[i] = data.readUnsignedShort();
    }
  }
  @Override
  protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // mark the reader index to be able to start decoding from the same position if there is not
    // enough data to finish the frame decoding
    in.markReaderIndex();

    boolean frameDecoded = false;

    try {
      if (!in.isReadable(FRAME_HEADER_LENGTH)) {
        return;
      }

      int frameVersion = in.readUnsignedByte();
      sessionHandler.versionRead(frameVersion);

      int frameType = in.readUnsignedByte();
      LOG.debug("Received a lumberjack frame of type {}", (char) frameType);

      switch (frameType) {
        case TYPE_JSON:
          frameDecoded = handleJsonFrame(in, out);
          break;
        case TYPE_DATA:
          frameDecoded = handleDataFrame(in, out);
          break;
        case TYPE_WINDOW:
          frameDecoded = handleWindowFrame(in);
          break;
        case TYPE_COMPRESS:
          frameDecoded = handleCompressedFrame(ctx, in, out);
          break;
        default:
          throw new RuntimeException("Unsupported frame type=" + frameType);
      }
    } finally {
      if (!frameDecoded) {
        LOG.debug(
            "Not enough data to decode a complete frame, retry when more data is available. Reader index was {}",
            in.readerIndex());
        in.resetReaderIndex();
      }
    }
  }
Example #14
0
  public static MetaParam<?>[] readMetadata(ByteBuf in) throws IOException {
    MetaParam<?>[] parameters = new MetaParam<?>[MetaParam.METADATA_SIZE];

    for (int data = in.readUnsignedByte(); data != 127; data = in.readUnsignedByte()) {
      int index = data & 0x1F;
      MetaParam.Type type = MetaParam.Type.fromId(data >> 5);

      switch (type) {
        case BYTE:
          parameters[index] = new MetaParam<Byte>(index, in.readByte());
          break;

        case SHORT:
          parameters[index] = new MetaParam<Short>(index, in.readShort());
          break;

        case INT:
          parameters[index] = new MetaParam<Integer>(index, in.readInt());
          break;

        case FLOAT:
          parameters[index] = new MetaParam<Float>(index, in.readFloat());
          break;

        case STRING:
          parameters[index] = new MetaParam<String>(index, readString(in));
          break;

        case ITEM:
          parameters[index] = new MetaParam<ItemStack>(index, readItemstack(in));
          break;

        case COORDINATE:
          Position pos;
          pos = new Position(in.readInt(), in.readInt(), in.readInt());

          parameters[index] = new MetaParam<Position>(index, pos);

        default:
          throw new UnsupportedOperationException("Unknown metadata ID " + type);
      }
    }
    return parameters;
  }
 /**
  * Transforms ByteBuf into correct POJO message
  *
  * @param rawMessage
  * @param version version decoded from OpenFlow protocol message
  * @return correct POJO as DataObject
  */
 public DataObject deserialize(final ByteBuf rawMessage, final short version) {
   DataObject dataObject = null;
   int type = rawMessage.readUnsignedByte();
   Class<?> clazz = messageClassMap.get(new TypeToClassKey(version, type));
   rawMessage.skipBytes(EncodeConstants.SIZE_OF_SHORT_IN_BYTES);
   OFDeserializer<DataObject> deserializer =
       registry.getDeserializer(new MessageCodeKey(version, type, clazz));
   dataObject = deserializer.deserialize(rawMessage);
   return dataObject;
 }
  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;
  }
 @Override
 public Tlv parseTlv(final ByteBuf buffer) throws BmpDeserializationException {
   if (buffer == null) {
     return null;
   }
   return new PerAfiSafiLocRibTlvBuilder()
       .setAfi(this.afiRegistry.classForFamily(buffer.readUnsignedShort()))
       .setSafi(this.safiRegistry.classForFamily(buffer.readUnsignedByte()))
       .setCount(new Gauge64(new BigInteger(ByteArray.readAllBytes(buffer))))
       .build();
 }
Example #18
0
  public static int readVarShort(ByteBuf buf) {
    int low = buf.readUnsignedShort();
    int high = 0;

    if ((low & 0x8000) != 0) {
      low = low & 0x7FFF;
      high = buf.readUnsignedByte();
    }

    return ((high & 0xFF) << 15) | low;
  }
 public static TravellingObject fromPacket(ByteBuf buf) {
   Class<? extends TravellingObject> cls = CLASS_MAP.get(new Integer(buf.readUnsignedByte()));
   if (cls != null) {
     try {
       TravellingObject o = cls.newInstance();
       o.readData(buf);
       return o;
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return null;
 }
 @Test
 public void testEncode() {
   MockRelayMessage message = new MockRelayMessage();
   message.code(Unsigned16.get(100));
   message.length(Unsigned32.get(36L));
   message.flag(new FlagData(FlagImpl.REQUEST));
   message.hopByHop(Integer64.get(1L));
   message.endToEnd(Integer64.get(2L));
   message.addAttribute(new IgnoredAttribute(new IgnoredData(new byte[] {1, 2, 3, 4})));
   ByteBuf buf = MessageFactory.getInstance().generateByteBuf(message);
   Assert.assertEquals(message.version().get().byteValue(), buf.readUnsignedByte());
   Assert.assertEquals(message.code().get().intValue(), buf.readUnsignedShort());
   assertEquals(64, buf.readUnsignedByte());
   Assert.assertEquals(message.length().get().intValue(), buf.readUnsignedInt());
   assertEquals(message.hopByHop().get().longValue(), buf.readLong());
   assertEquals(message.endToEnd().get().longValue(), buf.readLong());
   assertEquals(0, buf.readUnsignedShort());
   assertEquals(4, buf.readUnsignedInt());
   assertEquals(1, buf.readByte());
   assertEquals(2, buf.readByte());
   assertEquals(3, buf.readByte());
   assertEquals(4, buf.readByte());
 }
 private void readSettingsFrame(
     ChannelHandlerContext ctx, ByteBuf payload, Http2FrameObserver observer)
     throws Http2Exception {
   if (flags.ack()) {
     observer.onSettingsAckRead(ctx);
   } else {
     int numSettings = payloadLength / SETTING_ENTRY_LENGTH;
     Http2Settings settings = new Http2Settings();
     for (int index = 0; index < numSettings; ++index) {
       short id = payload.readUnsignedByte();
       long value = payload.readUnsignedInt();
       switch (id) {
         case SETTINGS_HEADER_TABLE_SIZE:
           if (value < 0 || value > Integer.MAX_VALUE) {
             throw protocolError("Invalid value for HEADER_TABLE_SIZE: %d", value);
           }
           settings.maxHeaderTableSize((int) value);
           break;
         case SETTINGS_COMPRESS_DATA:
           if (value != 0 && value != 1) {
             throw protocolError("Invalid value for COMPRESS_DATA: %d", value);
           }
           settings.allowCompressedData(value == 1);
           break;
         case SETTINGS_ENABLE_PUSH:
           if (value != 0 && value != 1) {
             throw protocolError("Invalid value for ENABLE_PUSH: %d", value);
           }
           settings.pushEnabled(value == 1);
           break;
         case SETTINGS_INITIAL_WINDOW_SIZE:
           if (value < 0 || value > Integer.MAX_VALUE) {
             throw protocolError("Invalid value for INITIAL_WINDOW_SIZE: %d", value);
           }
           settings.initialWindowSize((int) value);
           break;
         case SETTINGS_MAX_CONCURRENT_STREAMS:
           if (value < 0 || value > Integer.MAX_VALUE) {
             throw protocolError("Invalid value for MAX_CONCURRENT_STREAMS: %d", value);
           }
           settings.maxConcurrentStreams((int) value);
           break;
         default:
           throw protocolError("Unsupport setting: %d", id);
       }
     }
     observer.onSettingsRead(ctx, settings);
   }
 }
Example #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();
  }
Example #23
0
    @Override
    public LispMapNotify readFrom(ByteBuf byteBuf) throws LispParseError, LispReaderException {

      if (byteBuf.readerIndex() != 0) {
        return null;
      }

      // skip first three bytes as they represent type and reserved fields
      byteBuf.skipBytes(RESERVED_SKIP_LENGTH);

      // record count -> 8 bits
      byte recordCount = (byte) byteBuf.readUnsignedByte();

      // nonce -> 64 bits
      long nonce = byteBuf.readLong();

      // keyId -> 16 bits
      short keyId = byteBuf.readShort();

      // authenticationDataLength -> 16 bits
      short authLength = byteBuf.readShort();

      // authenticationData -> depends on the authenticationDataLength
      byte[] authData = new byte[authLength];
      byteBuf.readBytes(authData);

      List<LispMapRecord> mapRecords = Lists.newArrayList();
      for (int i = 0; i < recordCount; i++) {
        mapRecords.add(new DefaultLispMapRecord.MapRecordReader().readFrom(byteBuf));
      }

      return new DefaultNotifyBuilder()
          .withRecordCount(recordCount)
          .withNonce(nonce)
          .withKeyId(keyId)
          .withAuthenticationData(authData)
          .withMapRecords(mapRecords)
          .build();
    }
 @Override
 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
   int available = in.readableBytes();
   if (available == 0) {
     return;
   }
   do {
     if (packetType == -1 && available >= 1) {
       packetType = in.readByte() - cipher.nextInt() & 0xff;
       packetSize = protocol.getInboundPacketSize(packetType);
       available--;
     }
     if (packetSize == -1) {
       if (available >= 1) {
         packetSize = in.readUnsignedByte();
         available--;
       } else {
         return;
       }
     } else if (packetSize == -2) {
       if (available >= 2) {
         packetSize = in.readUnsignedShort();
         available -= 2;
       } else {
         return;
       }
     }
     if (available < packetSize) {
       return;
     }
     byte[] data = new byte[packetSize];
     in.readBytes(data);
     out.add(new GamePacket(packetType, data));
     available -= packetSize;
     packetType = -1;
   } while (available > 0);
 }
Example #25
0
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    ByteBuf in = msg.content();
    if (in.readUnsignedByte() != 0xFE || in.readUnsignedByte() != 0xFD) {
      bungee.getLogger().log(Level.WARNING, "Query - Incorrect magic!: {0}", msg.sender());
      return;
    }

    ByteBuf out = ctx.alloc().buffer();
    AddressedEnvelope response = new DatagramPacket(out, msg.sender());

    byte type = in.readByte();
    int sessionId = in.readInt();

    if (type == 0x09) {
      out.writeByte(0x09);
      out.writeInt(sessionId);

      int challengeToken = random.nextInt();
      sessions.put(challengeToken, System.currentTimeMillis());

      writeNumber(out, challengeToken);
    }

    if (type == 0x00) {
      int challengeToken = in.readInt();
      Long session = sessions.get(challengeToken);
      if (session == null || System.currentTimeMillis() - session > TimeUnit.SECONDS.toMillis(30)) {
        throw new IllegalStateException("No session!");
      }

      out.writeByte(0x00);
      out.writeInt(sessionId);

      if (in.readableBytes() == 0) {
        // Short response
        writeString(out, listener.getMotd()); // MOTD
        writeString(out, "SMP"); // Game Type
        writeString(out, "BungeeCord_Proxy"); // World Name
        writeNumber(out, bungee.getOnlineCount()); // Online Count
        writeNumber(out, listener.getMaxPlayers()); // Max Players
        writeShort(out, listener.getHost().getPort()); // Port
        writeString(out, listener.getHost().getHostString()); // IP
      } else if (in.readableBytes() == 4) {
        // Long Response
        out.writeBytes(
            new byte[] {0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, (byte) 0x80, 0x00});
        Map<String, String> data = new LinkedHashMap<>();

        data.put("hostname", listener.getMotd());
        data.put("gametype", "SMP");
        // Start Extra Info
        data.put("game_id", "MINECRAFT");
        data.put("version", bungee.getGameVersion());
        data.put("plugins", "");
        // End Extra Info
        data.put("map", "BungeeCord");
        // data.put( "numplayers", Integer.toString( bungee.getOnlineCount() ) );
        data.put("numplayers", Integer.toString(getFakePlayerNumber()));
        data.put("maxplayers", Integer.toString(listener.getMaxPlayers()));
        data.put("hostport", Integer.toString(listener.getHost().getPort()));
        data.put("hostip", listener.getHost().getHostString());

        for (Map.Entry<String, String> entry : data.entrySet()) {
          writeString(out, entry.getKey());
          writeString(out, entry.getValue());
        }
        out.writeByte(0x00); // Null

        // Padding
        writeString(out, "\01player_\00");
        // Player List
        for (ProxiedPlayer p : bungee.getPlayers()) {
          writeString(out, p.getName());
        }
        // writeString( out, "Mr_ludek" );
        // for(int x = 0; x < getFakePlayerNumber(); x++){

        // }
        writePlayers(getFakePlayerNumber(), out);

        out.writeByte(0x00); // Null
      } else {
        // Error!
        throw new IllegalStateException("Invalid data request packet");
      }
    }

    ctx.writeAndFlush(response);
  }
 @Override
 public ExtendedCommunities parseExtendedCommunity(
     final ReferenceCache refCache, final ExtendedCommunitiesBuilder comm, final ByteBuf buffer)
     throws BGPDocumentedException {
   ExtendedCommunity c = null;
   if (comm.getCommType().equals(FS_TYPE)) {
     switch (comm.getCommSubType()) {
       case TRAFFIC_RATE_SUBTYPE:
         final ShortAsNumber as = new ShortAsNumber((long) buffer.readUnsignedShort());
         final Bandwidth value = new Bandwidth(ByteArray.readBytes(buffer, TRAFFIC_RATE_SIZE));
         c =
             new TrafficRateExtendedCommunityCaseBuilder()
                 .setTrafficRateExtendedCommunity(
                     new TrafficRateExtendedCommunityBuilder()
                         .setInformativeAs(as)
                         .setLocalAdministrator(value)
                         .build())
                 .build();
         break;
       case TRAFFIC_ACTION_SUBTYPE:
         buffer.skipBytes(RESERVED);
         final BitArray flags = BitArray.valueOf(buffer, FLAGS_SIZE);
         final boolean sample = flags.get(SAMPLE_BIT);
         final boolean terminal = flags.get(TERMINAL_BIT);
         c =
             new TrafficActionExtendedCommunityCaseBuilder()
                 .setTrafficActionExtendedCommunity(
                     new TrafficActionExtendedCommunityBuilder()
                         .setSample(sample)
                         .setTerminalAction(terminal)
                         .build())
                 .build();
         break;
       case REDIRECT_SUBTYPE:
         final ShortAsNumber as1 = new ShortAsNumber((long) buffer.readUnsignedShort());
         final byte[] byteValue = ByteArray.readBytes(buffer, TRAFFIC_RATE_SIZE);
         c =
             new RedirectExtendedCommunityCaseBuilder()
                 .setRedirectExtendedCommunity(
                     new RedirectExtendedCommunityBuilder()
                         .setGlobalAdministrator(as1)
                         .setLocalAdministrator(byteValue)
                         .build())
                 .build();
         break;
       case TRAFFIC_MARKING_SUBTYPE:
         buffer.skipBytes(RESERVED);
         final Dscp dscp = new Dscp(buffer.readUnsignedByte());
         c =
             new TrafficMarkingExtendedCommunityCaseBuilder()
                 .setTrafficMarkingExtendedCommunity(
                     new TrafficMarkingExtendedCommunityBuilder()
                         .setGlobalAdministrator(dscp)
                         .build())
                 .build();
         break;
       default:
         throw new BGPDocumentedException(
             "Could not parse Flowspec Extended Community type: " + comm.getCommSubType(),
             BGPError.OPT_ATTR_ERROR);
     }
   }
   if (c == null) {
     LOG.debug("Extended community is not from Flowspec, fallback to original communities.");
     return super.parseExtendedCommunity(refCache, comm, buffer);
   }
   return comm.setExtendedCommunity(c).build();
 }
Example #27
0
  @Override
  protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {

    Object result = null;

    switch (state()) {
      case READ_MAGIC:
        magic = buf.readInt();
        if (magic == MAGIC_BYTES_AS_INT) {
          checkpoint(DecodeState.READ_VERSION);
        } else {
          throw new IllegalArgumentException(
              String.format(
                  "Expected to read magic 4 bytes: %d but received %d.", 0x5355524C, magic));
        }
      case READ_VERSION:
        version = buf.readUnsignedByte();
        checkpoint(DecodeState.READ_COMMAND);

      case READ_COMMAND:
        command = buf.readUnsignedByte();
        checkpoint(DecodeState.READ_MSGID);

      case READ_MSGID:
        id = buf.readUnsignedInt();
        checkpoint(DecodeState.READ_COMMAND_DATA);

      case READ_COMMAND_DATA:
        switch (command) {
          case 0x01:
            {
              final int longURILen = buf.readInt();
              final String longURI = buf.readBytes(longURILen).toString(CHARSET);
              result = new ShurlyShrinkMessage(version, id, URI.create(longURI));
              break;
            }
          case 0x02:
            {
              final int longURILen = buf.readInt();
              final String longURI = buf.readBytes(longURILen).toString(CHARSET);
              final int shortURILen = buf.readInt();
              final String shortURI = buf.readBytes(shortURILen).toString(CHARSET);
              result =
                  new ShurlyShrunkMessage(version, id, URI.create(longURI), URI.create(shortURI));
              break;
            }
          case 0x03:
            {
              final long errorCode = buf.readUnsignedInt();
              final int reasonLength = buf.readInt();
              final String reason = buf.readBytes(reasonLength).toString(CHARSET);
              result = new ShurlyErrorMessage(version, id, errorCode, reason);
              break;
            }
          case 0x04:
            {
              final int shortURILen = buf.readInt();
              final String shortURI = buf.readBytes(shortURILen).toString(CHARSET);
              result = new ShurlyFollowMessage(version, id, URI.create(shortURI));
              break;
            }
          default:
            throw new IllegalArgumentException("Unrecognized command: " + command);
        }
    }

    //noinspection ConstantConditions
    assert result != null;
    state(DecodeState.READ_MAGIC);
    out.add(result);
  }
Example #28
0
 @Override
 public void readData(ByteBuf data) {
   int flags = data.readUnsignedByte();
   color = flags & 15;
   isFilter = (flags & 0x20) > 0;
 }
 @Override
 public int readUnsignedByte() {
   return buffer.readUnsignedByte();
 }
 @Override
 public void channelRead(final ChannelHandlerContext ctx, final Object inputObj) throws Exception {
   try {
     final ByteBuf input = (ByteBuf) inputObj;
     if (!input.isReadable()) {
       return;
     }
     final Channel channel = ctx.channel();
     receivedData.writeBytes(input);
     ProtocolVersion handshakeversion = ProtocolVersion.NOT_SET;
     receivedData.readerIndex(0);
     int firstbyte = receivedData.readUnsignedByte();
     switch (firstbyte) {
       case 0xFE:
         { // old ping
           try {
             if (receivedData.readableBytes() == 0) { // really old protocol probably
               scheduleTask(ctx, new Ping11ResponseTask(channel), 1000, TimeUnit.MILLISECONDS);
             } else if (receivedData.readUnsignedByte() == 1) {
               if (receivedData.readableBytes() == 0) {
                 // 1.5.2 probably
                 scheduleTask(
                     ctx, new Ping152ResponseTask(this, channel), 500, TimeUnit.MILLISECONDS);
               } else if ((receivedData.readUnsignedByte() == 0xFA)
                   && "MC|PingHost"
                       .equals(
                           new String(
                               Utils.toArray(
                                   receivedData.readBytes(receivedData.readUnsignedShort() * 2)),
                               StandardCharsets.UTF_16BE))) { // 1.6.*
                 receivedData.readUnsignedShort();
                 handshakeversion = ProtocolVersion.fromId(receivedData.readUnsignedByte());
               }
             }
           } catch (IndexOutOfBoundsException ex) {
           }
           break;
         }
       case 0x02:
         { // 1.6 or 1.5.2 handshake
           try {
             handshakeversion = ProtocolVersion.fromId(receivedData.readUnsignedByte());
           } catch (IndexOutOfBoundsException ex) {
           }
           break;
         }
       default:
         { // 1.7 or 1.8 handshake
           receivedData.readerIndex(0);
           ByteBuf data = getVarIntPrefixedData(receivedData);
           if (data != null) {
             handshakeversion = readNPHandshake(data);
           }
           break;
         }
     }
     // if we detected the protocol than we save it and process data
     if (handshakeversion != ProtocolVersion.NOT_SET) {
       setProtocol(channel, receivedData, handshakeversion);
     }
   } catch (Throwable t) {
     ctx.channel().close();
   } finally {
     ReferenceCountUtil.release(inputObj);
   }
 }