/**
     * Decodes the client connection preface string from the input buffer.
     *
     * @return {@code true} if processing of the client preface string is complete. Since client
     *     preface strings can only be received by servers, returns true immediately for client
     *     endpoints.
     */
    private boolean readClientPrefaceString(ByteBuf in) throws Http2Exception {
      if (clientPrefaceString == null) {
        return true;
      }

      int prefaceRemaining = clientPrefaceString.readableBytes();
      int bytesRead = min(in.readableBytes(), prefaceRemaining);

      // If the input so far doesn't match the preface, break the connection.
      if (bytesRead == 0
          || !ByteBufUtil.equals(
              in,
              in.readerIndex(),
              clientPrefaceString,
              clientPrefaceString.readerIndex(),
              bytesRead)) {
        String receivedBytes =
            hexDump(
                in, in.readerIndex(), min(in.readableBytes(), clientPrefaceString.readableBytes()));
        throw connectionError(
            PROTOCOL_ERROR,
            "HTTP/2 client preface string missing or corrupt. " + "Hex dump for received bytes: %s",
            receivedBytes);
      }
      in.skipBytes(bytesRead);
      clientPrefaceString.skipBytes(bytesRead);

      if (!clientPrefaceString.isReadable()) {
        // Entire preface has been read.
        clientPrefaceString.release();
        clientPrefaceString = null;
        return true;
      }
      return false;
    }
  @Override
  protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    long frameLength = decodeLength(in, 0);
    if (frameLength > maxFrameLength) {
      long discard = frameLength - in.readableBytes();
      tooLongFrameLength = frameLength;

      if (discard < 0) {
        // buffer contains more bytes then the frameLength so we can discard all now
        in.skipBytes((int) frameLength);
      } else {
        // Enter the discard mode and discard everything received so far.
        discardingTooLongFrame = true;
        bytesToDiscard = discard;
        in.skipBytes(in.readableBytes());
      }
      failIfNecessary(true);
    } else {
      int readerIndex = in.readerIndex();
      int actualFrameLength = (int) frameLength;
      ByteBuf buffer = extractFrame(ctx, in, readerIndex, actualFrameLength);
      in.readerIndex(readerIndex + actualFrameLength);
      out.add(buffer);
    }
  }
    @Override
    public OFPortDesc readFrom(ByteBuf bb) throws OFParseError {
      OFPort portNo = OFPort.read4Bytes(bb);
      // pad: 4 bytes
      bb.skipBytes(4);
      MacAddress hwAddr = MacAddress.read6Bytes(bb);
      // pad: 2 bytes
      bb.skipBytes(2);
      String name = ChannelUtils.readFixedLengthString(bb, 16);
      Set<OFPortConfig> config = OFPortConfigSerializerVer12.readFrom(bb);
      Set<OFPortState> state = OFPortStateSerializerVer12.readFrom(bb);
      Set<OFPortFeatures> curr = OFPortFeaturesSerializerVer12.readFrom(bb);
      Set<OFPortFeatures> advertised = OFPortFeaturesSerializerVer12.readFrom(bb);
      Set<OFPortFeatures> supported = OFPortFeaturesSerializerVer12.readFrom(bb);
      Set<OFPortFeatures> peer = OFPortFeaturesSerializerVer12.readFrom(bb);
      long currSpeed = U32.f(bb.readInt());
      long maxSpeed = U32.f(bb.readInt());

      OFPortDescVer12 portDescVer12 =
          new OFPortDescVer12(
              portNo,
              hwAddr,
              name,
              config,
              state,
              curr,
              advertised,
              supported,
              peer,
              currSpeed,
              maxSpeed);
      if (logger.isTraceEnabled()) logger.trace("readFrom - read={}", portDescVer12);
      return portDescVer12;
    }
  private SpdyHeadersFrame readHeaderBlockFrame(ByteBuf buffer) {
    int streamId;
    switch (type) {
      case SPDY_SYN_STREAM_FRAME:
        if (buffer.readableBytes() < 10) {
          return null;
        }

        int offset = buffer.readerIndex();
        streamId = getUnsignedInt(buffer, offset);
        int associatedToStreamId = getUnsignedInt(buffer, offset + 4);
        byte priority = (byte) (buffer.getByte(offset + 8) >> 5 & 0x07);
        buffer.skipBytes(10);
        length -= 10;

        SpdySynStreamFrame spdySynStreamFrame =
            new DefaultSpdySynStreamFrame(streamId, associatedToStreamId, priority);
        spdySynStreamFrame.setLast((flags & SPDY_FLAG_FIN) != 0);
        spdySynStreamFrame.setUnidirectional((flags & SPDY_FLAG_UNIDIRECTIONAL) != 0);

        return spdySynStreamFrame;

      case SPDY_SYN_REPLY_FRAME:
        if (buffer.readableBytes() < 4) {
          return null;
        }

        streamId = getUnsignedInt(buffer, buffer.readerIndex());
        buffer.skipBytes(4);
        length -= 4;

        SpdySynReplyFrame spdySynReplyFrame = new DefaultSpdySynReplyFrame(streamId);
        spdySynReplyFrame.setLast((flags & SPDY_FLAG_FIN) != 0);

        return spdySynReplyFrame;

      case SPDY_HEADERS_FRAME:
        if (buffer.readableBytes() < 4) {
          return null;
        }

        streamId = getUnsignedInt(buffer, buffer.readerIndex());
        buffer.skipBytes(4);
        length -= 4;

        SpdyHeadersFrame spdyHeadersFrame = new DefaultSpdyHeadersFrame(streamId);
        spdyHeadersFrame.setLast((flags & SPDY_FLAG_FIN) != 0);

        return spdyHeadersFrame;

      default:
        throw new Error("Shouldn't reach here.");
    }
  }
  private Object readControlFrame(ByteBuf buffer) {
    int streamId;
    int statusCode;
    switch (type) {
      case SPDY_RST_STREAM_FRAME:
        if (buffer.readableBytes() < 8) {
          return null;
        }

        streamId = getUnsignedInt(buffer, buffer.readerIndex());
        statusCode = getSignedInt(buffer, buffer.readerIndex() + 4);
        buffer.skipBytes(8);

        return new DefaultSpdyRstStreamFrame(streamId, statusCode);

      case SPDY_PING_FRAME:
        if (buffer.readableBytes() < 4) {
          return null;
        }

        int ID = getSignedInt(buffer, buffer.readerIndex());
        buffer.skipBytes(4);

        return new DefaultSpdyPingFrame(ID);

      case SPDY_GOAWAY_FRAME:
        if (buffer.readableBytes() < 8) {
          return null;
        }

        int lastGoodStreamId = getUnsignedInt(buffer, buffer.readerIndex());
        statusCode = getSignedInt(buffer, buffer.readerIndex() + 4);
        buffer.skipBytes(8);

        return new DefaultSpdyGoAwayFrame(lastGoodStreamId, statusCode);

      case SPDY_WINDOW_UPDATE_FRAME:
        if (buffer.readableBytes() < 8) {
          return null;
        }

        streamId = getUnsignedInt(buffer, buffer.readerIndex());
        int deltaWindowSize = getUnsignedInt(buffer, buffer.readerIndex() + 4);
        buffer.skipBytes(8);

        return new DefaultSpdyWindowUpdateFrame(streamId, deltaWindowSize);

      default:
        throw new Error("Shouldn't reach here.");
    }
  }
    @Override
    public OFFlowStatsEntry readFrom(ByteBuf bb) throws OFParseError {
      int start = bb.readerIndex();
      int length = U16.f(bb.readShort());
      if (length < MINIMUM_LENGTH)
        throw new OFParseError(
            "Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + 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);
      TableId tableId = TableId.readByte(bb);
      // pad: 1 bytes
      bb.skipBytes(1);
      long durationSec = U32.f(bb.readInt());
      long durationNsec = U32.f(bb.readInt());
      int priority = U16.f(bb.readShort());
      int idleTimeout = U16.f(bb.readShort());
      int hardTimeout = U16.f(bb.readShort());
      Set<OFFlowModFlags> flags = OFFlowModFlagsSerializerVer14.readFrom(bb);
      int importance = U16.f(bb.readShort());
      // pad: 2 bytes
      bb.skipBytes(2);
      U64 cookie = U64.ofRaw(bb.readLong());
      U64 packetCount = U64.ofRaw(bb.readLong());
      U64 byteCount = U64.ofRaw(bb.readLong());
      Match match = ChannelUtilsVer14.readOFMatch(bb);
      List<OFInstruction> instructions =
          ChannelUtils.readList(bb, length - (bb.readerIndex() - start), OFInstructionVer14.READER);

      OFFlowStatsEntryVer14 flowStatsEntryVer14 =
          new OFFlowStatsEntryVer14(
              tableId,
              durationSec,
              durationNsec,
              priority,
              idleTimeout,
              hardTimeout,
              flags,
              importance,
              cookie,
              packetCount,
              byteCount,
              match,
              instructions);
      if (logger.isTraceEnabled()) logger.trace("readFrom - read={}", flowStatsEntryVer14);
      return flowStatsEntryVer14;
    }
 @Override
 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
   Protocol.DirectionData prot = this.server ? this.protocol.TO_SERVER : this.protocol.TO_CLIENT;
   ByteBuf copy = in.copy();
   try {
     int packetId = DefinedPacket.readVarInt(in);
     DefinedPacket packet = null;
     if (prot.hasPacket(packetId)) {
       packet = prot.createPacket(packetId);
       packet.read(in, prot.getDirection(), this.protocolVersion);
       if (in.readableBytes() != 0) {
         throw new BadPacketException(
             "Did not read all bytes from packet "
                 + packet.getClass()
                 + " "
                 + packetId
                 + " Protocol "
                 + this.protocol
                 + " Direction "
                 + prot);
       }
     } else {
       in.skipBytes(in.readableBytes());
     }
     out.add(new PacketWrapper(packet, copy));
     copy = null;
   } finally {
     if (copy != null) {
       copy.release();
     }
   }
 }
  @Override
  protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    if (discardingTooLongFrame) {
      buffer.skipBytes(actualReadableBytes());
      checkpoint();
      return null;
    }

    Unmarshaller unmarshaller = provider.getUnmarshaller(ctx);
    ByteInput input = new ChannelBufferByteInput(buffer);
    if (maxObjectSize != Integer.MAX_VALUE) {
      input = new LimitingByteInput(input, maxObjectSize);
    }
    try {
      unmarshaller.start(input);
      Object obj = unmarshaller.readObject();
      unmarshaller.finish();
      return obj;
    } catch (LimitingByteInput.TooBigObjectException e) {
      discardingTooLongFrame = true;
      throw new TooLongFrameException();
    } finally {
      // Call close in a finally block as the ReplayingDecoder will throw an Error if not enough
      // bytes are
      // readable. This helps to be sure that we do not leak resource
      unmarshaller.close();
    }
  }
  private boolean handleCompressedFrame(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
      throws Exception {
    if (!in.isReadable(FRAME_COMPRESS_HEADER_LENGTH)) {
      return false;
    }

    int compressedPayloadLength = in.readInt();
    if (!in.isReadable(compressedPayloadLength)) {
      return false;
    }

    // decompress payload
    Inflater inflater = new Inflater();
    if (in.hasArray()) {
      inflater.setInput(in.array(), in.arrayOffset() + in.readerIndex(), compressedPayloadLength);
      in.skipBytes(compressedPayloadLength);
    } else {
      byte[] array = new byte[compressedPayloadLength];
      in.readBytes(array);
      inflater.setInput(array);
    }

    while (!inflater.finished()) {
      ByteBuf decompressed = ctx.alloc().heapBuffer(1024, 1024);
      byte[] outArray = decompressed.array();
      int count =
          inflater.inflate(outArray, decompressed.arrayOffset(), decompressed.writableBytes());
      decompressed.writerIndex(count);
      // put data in the pipeline
      out.add(decompressed);
    }

    return true;
  }
    @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;
    }
Example #11
0
 @Override
 protected void handleData(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) {
   byte[] data = new byte[byteBuf.readableBytes() - 5];
   byteBuf.skipBytes(5);
   byteBuf.readBytes(data);
   String content = new String(data);
   System.out.println(name + " get content: " + content);
 }
Example #12
0
 @Override
 protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
   // 跳过4个字节
   msg = msg.skipBytes(4);
   // 剔除最后一个字符串 03
   msg = msg.copy(0, msg.readableBytes() - 1);
   // 加进集合中
   out.add(msg.toString(charset));
 }
 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);
 }
Example #14
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;
 }
 private static List<QueueProperty> createPropertiesList(ByteBuf input, int length) {
   int propertiesLength = length;
   List<QueueProperty> propertiesList = new ArrayList<>();
   while (propertiesLength > 0) {
     QueuePropertyBuilder propertiesBuilder = new QueuePropertyBuilder();
     QueueProperties property = QueueProperties.forValue(input.readUnsignedShort());
     propertiesBuilder.setProperty(property);
     propertiesLength -= input.readUnsignedShort();
     input.skipBytes(PADDING_IN_QUEUE_PROPERTY_HEADER);
     if (property.equals(QueueProperties.OFPQTMINRATE)) {
       RateQueuePropertyBuilder rateBuilder = new RateQueuePropertyBuilder();
       rateBuilder.setRate(input.readUnsignedShort());
       propertiesBuilder.addAugmentation(RateQueueProperty.class, rateBuilder.build());
       input.skipBytes(PADDING_IN_RATE_QUEUE_PROPERTY);
     }
     propertiesList.add(propertiesBuilder.build());
   }
   return propertiesList;
 }
 @Override
 public GetQueueConfigOutput deserialize(ByteBuf rawMessage) {
   GetQueueConfigOutputBuilder builder = new GetQueueConfigOutputBuilder();
   builder.setVersion((short) EncodeConstants.OF10_VERSION_ID);
   builder.setXid((rawMessage.readUnsignedInt()));
   builder.setPort(new PortNumber((long) rawMessage.readUnsignedShort()));
   rawMessage.skipBytes(PADDING_IN_QUEUE_GET_CONFIG_REPLY_HEADER);
   builder.setQueues(createQueuesList(rawMessage));
   return builder.build();
 }
 /**
  * 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;
 }
 @Override
 public Action deserialize(ByteBuf message) {
   ActionBuilder actionBuilder = deserializeHeader(message);
   ActionSetNshc1Builder builder = new ActionSetNshc1Builder();
   NxActionSetNshc1Builder nxActionSetNspBuilder = new NxActionSetNshc1Builder();
   message.skipBytes(padding);
   nxActionSetNspBuilder.setNshc(message.readUnsignedInt());
   builder.setNxActionSetNshc1(nxActionSetNspBuilder.build());
   actionBuilder.setActionChoice(builder.build());
   return actionBuilder.build();
 }
Example #19
0
    /**
     * Transfers data from the original message to the channel, encrypting it in the process.
     *
     * <p>This method also breaks down the original message into smaller chunks when needed. This is
     * done to keep memory usage under control. This avoids having to copy the whole message data
     * into memory at once, and can avoid ballooning memory usage when transferring large messages
     * such as shuffle blocks.
     *
     * <p>The {@link #transfered()} counter also behaves a little funny, in that it won't go forward
     * until a whole chunk has been written. This is done because the code can't use the actual
     * number of bytes written to the channel as the transferred count (see {@link #count()}).
     * Instead, once an encrypted chunk is written to the output (including its header), the size of
     * the original block will be added to the {@link #transfered()} amount.
     */
    @Override
    public long transferTo(final WritableByteChannel target, final long position)
        throws IOException {

      Preconditions.checkArgument(position == transfered(), "Invalid position.");

      long reportedWritten = 0L;
      long actuallyWritten = 0L;
      do {
        if (currentChunk == null) {
          nextChunk();
        }

        if (currentHeader.readableBytes() > 0) {
          int bytesWritten = target.write(currentHeader.nioBuffer());
          currentHeader.skipBytes(bytesWritten);
          actuallyWritten += bytesWritten;
          if (currentHeader.readableBytes() > 0) {
            // Break out of loop if there are still header bytes left to write.
            break;
          }
        }

        actuallyWritten += target.write(currentChunk);
        if (!currentChunk.hasRemaining()) {
          // Only update the count of written bytes once a full chunk has been written.
          // See method javadoc.
          long chunkBytesRemaining = unencryptedChunkSize - currentReportedBytes;
          reportedWritten += chunkBytesRemaining;
          transferred += chunkBytesRemaining;
          currentHeader.release();
          currentHeader = null;
          currentChunk = null;
          currentChunkSize = 0;
          currentReportedBytes = 0;
        }
      } while (currentChunk == null && transfered() + reportedWritten < count());

      // Returning 0 triggers a backoff mechanism in netty which may harm performance. Instead,
      // we return 1 until we can (i.e. until the reported count would actually match the size
      // of the current chunk), at which point we resort to returning 0 so that the counts still
      // match, at the cost of some performance. That situation should be rare, though.
      if (reportedWritten != 0L) {
        return reportedWritten;
      }

      if (actuallyWritten > 0 && currentReportedBytes < currentChunkSize - 1) {
        transferred += 1L;
        currentReportedBytes += 1L;
        return 1L;
      }

      return 0L;
    }
 protected void decode(ChannelHandlerContext context, ByteBuf buffer) throws Exception {
   ChannelPipeline pipeline = context.pipeline();
   if (detectSsl && SslHandler.isEncrypted(buffer)) {
     SSLEngine engine = SSL_SERVER_CONTEXT.getValue().createSSLEngine();
     engine.setUseClientMode(false);
     pipeline.addLast(
         new SslHandler(engine),
         new ChunkedWriteHandler(),
         new PortUnificationServerHandler(delegatingHttpRequestHandler, false, detectGzip));
   } else {
     int magic1 = buffer.getUnsignedByte(buffer.readerIndex());
     int magic2 = buffer.getUnsignedByte(buffer.readerIndex() + 1);
     if (detectGzip && magic1 == 31 && magic2 == 139) {
       pipeline.addLast(
           new JZlibEncoder(ZlibWrapper.GZIP),
           new JdkZlibDecoder(ZlibWrapper.GZIP),
           new PortUnificationServerHandler(delegatingHttpRequestHandler, detectSsl, false));
     } else if (isHttp(magic1, magic2)) {
       NettyUtil.initHttpHandlers(pipeline);
       pipeline.addLast(delegatingHttpRequestHandler);
       if (BuiltInServer.LOG.isDebugEnabled()) {
         pipeline.addLast(
             new ChannelOutboundHandlerAdapter() {
               @Override
               public void write(
                   ChannelHandlerContext context, Object message, ChannelPromise promise)
                   throws Exception {
                 if (message instanceof HttpResponse) {
                   //                BuiltInServer.LOG.debug("OUT HTTP:\n" + message);
                   HttpResponse response = (HttpResponse) message;
                   BuiltInServer.LOG.debug(
                       "OUT HTTP: "
                           + response.getStatus().code()
                           + " "
                           + response.headers().get("Content-type"));
                 }
                 super.write(context, message, promise);
               }
             });
       }
     } else if (magic1 == 'C' && magic2 == 'H') {
       buffer.skipBytes(2);
       pipeline.addLast(new CustomHandlerDelegator());
     } else {
       BuiltInServer.LOG.warn("unknown request, first two bytes " + magic1 + " " + magic2);
       context.close();
     }
   }
   // must be after new channels handlers addition (netty bug?)
   ensureThatExceptionHandlerIsLast(pipeline);
   pipeline.remove(this);
   context.fireChannelRead(buffer);
 }
  /**
   * Read a string that is prefixed by its length encoded by a 4 bytes integer.
   *
   * @param in the buffer to consume
   * @return the read string or {@code null} if not enough data available to read the whole string
   */
  private String readLengthPrefixedString(ByteBuf in) {
    if (!in.isReadable(INT_LENGTH)) {
      return null;
    }
    int length = in.readInt();
    if (!in.isReadable(length)) {
      return null;
    }

    String str = in.toString(in.readerIndex(), length, StandardCharsets.UTF_8);
    in.skipBytes(length);
    return str;
  }
 private static List<Queues> createQueuesList(ByteBuf input) {
   List<Queues> queuesList = new ArrayList<>();
   while (input.readableBytes() > 0) {
     QueuesBuilder queueBuilder = new QueuesBuilder();
     queueBuilder.setQueueId(new QueueId(input.readUnsignedInt()));
     int length = input.readUnsignedShort();
     input.skipBytes(PADDING_IN_PACKET_QUEUE_HEADER);
     queueBuilder.setQueueProperty(
         createPropertiesList(input, length - PACKET_QUEUE_HEADER_LENGTH));
     queuesList.add(queueBuilder.build());
   }
   return queuesList;
 }
Example #23
0
    private void nextChunk() throws IOException {
      byteChannel.reset();
      if (isByteBuf) {
        int copied = byteChannel.write(buf.nioBuffer());
        buf.skipBytes(copied);
      } else {
        region.transferTo(byteChannel, region.transfered());
      }

      byte[] encrypted = backend.wrap(byteChannel.getData(), 0, byteChannel.length());
      this.currentChunk = ByteBuffer.wrap(encrypted);
      this.currentChunkSize = encrypted.length;
      this.currentHeader = Unpooled.copyLong(8 + currentChunkSize);
      this.unencryptedChunkSize = byteChannel.length();
    }
    @Override
    public OFPortStatsRequest readFrom(ByteBuf bb) throws OFParseError {
      int start = bb.readerIndex();
      // fixed value property version == 4
      byte version = bb.readByte();
      if (version != (byte) 0x4)
        throw new OFParseError("Wrong version: Expected=OFVersion.OF_13(4), got=" + version);
      // fixed value property type == 18
      byte type = bb.readByte();
      if (type != (byte) 0x12)
        throw new OFParseError("Wrong type: Expected=OFType.STATS_REQUEST(18), got=" + type);
      int length = U16.f(bb.readShort());
      if (length != 24) throw new OFParseError("Wrong length: Expected=24(24), 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 == 4
      short statsType = bb.readShort();
      if (statsType != (short) 0x4)
        throw new OFParseError("Wrong statsType: Expected=OFStatsType.PORT(4), got=" + statsType);
      Set<OFStatsRequestFlags> flags = OFStatsRequestFlagsSerializerVer13.readFrom(bb);
      // pad: 4 bytes
      bb.skipBytes(4);
      OFPort portNo = OFPort.read4Bytes(bb);
      // pad: 4 bytes
      bb.skipBytes(4);

      OFPortStatsRequestVer13 portStatsRequestVer13 =
          new OFPortStatsRequestVer13(xid, flags, portNo);
      if (logger.isTraceEnabled()) logger.trace("readFrom - read={}", portStatsRequestVer13);
      return portStatsRequestVer13;
    }
  @Override
  protected Object decodeLast(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    switch (buffer.readableBytes()) {
      case 0:
        return null;
      case 1:
        // Ignore the last TC_RESET
        if (buffer.getByte(buffer.readerIndex()) == ObjectStreamConstants.TC_RESET) {
          buffer.skipBytes(1);
          return null;
        }
    }

    return decode(ctx, buffer);
  }
Example #26
0
 private static SSLEngineResult wrap(SSLEngine engine, ByteBuf in, ByteBuf out)
     throws SSLException {
   ByteBuffer in0 = in.nioBuffer();
   for (; ; ) {
     ByteBuffer out0 = out.nioBuffer(out.writerIndex(), out.writableBytes());
     SSLEngineResult result = engine.wrap(in0, out0);
     in.skipBytes(result.bytesConsumed());
     out.writerIndex(out.writerIndex() + result.bytesProduced());
     if (result.getStatus() == Status.BUFFER_OVERFLOW) {
       out.ensureWritableBytes(engine.getSession().getPacketBufferSize());
     } else {
       return result;
     }
   }
 }
  private void readDataFrame(
      ChannelHandlerContext ctx, ByteBuf payload, Http2FrameListener listener)
      throws Http2Exception {
    short padding = readPadding(payload);

    // Determine how much data there is to read by removing the trailing
    // padding.
    int dataLength = payload.readableBytes() - padding;
    if (dataLength < 0) {
      throw streamError(streamId, FRAME_SIZE_ERROR, "Frame payload too small for padding.");
    }

    ByteBuf data = payload.readSlice(dataLength);
    listener.onDataRead(ctx, streamId, data, padding, flags.endOfStream());
    payload.skipBytes(payload.readableBytes());
  }
Example #28
0
 private static SSLEngineResult unwrap(SSLEngine engine, ByteBuf in, ByteBuf out)
     throws SSLException {
   ByteBuffer in0 = in.nioBuffer();
   for (; ; ) {
     ByteBuffer out0 = out.nioBuffer(out.writerIndex(), out.writableBytes());
     SSLEngineResult result = engine.unwrap(in0, out0);
     in.skipBytes(result.bytesConsumed());
     out.writerIndex(out.writerIndex() + result.bytesProduced());
     switch (result.getStatus()) {
       case BUFFER_OVERFLOW:
         out.ensureWritableBytes(engine.getSession().getApplicationBufferSize());
         break;
       default:
         return result;
     }
   }
 }
    @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;
    }
Example #30
0
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
        throws Exception {

      byte[] data;
      int offset;
      int length = msg.readableBytes();
      if (msg.hasArray()) {
        data = msg.array();
        offset = msg.arrayOffset();
        msg.skipBytes(length);
      } else {
        data = new byte[length];
        msg.readBytes(data);
        offset = 0;
      }

      out.add(Unpooled.wrappedBuffer(backend.unwrap(data, offset, length)));
    }