@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;
    }
  @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);
    }
  }
    /**
     * 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;
    }
  protected void checkCloseFrameBody(ChannelHandlerContext ctx, ByteBuf buffer) {
    if (buffer == null || buffer.capacity() == 0) {
      return;
    }
    if (buffer.capacity() == 1) {
      protocolViolation(ctx, "Invalid close frame body");
    }

    // Save reader index
    int idx = buffer.readerIndex();
    buffer.readerIndex(0);

    // Must have 2 byte integer within the valid range
    int statusCode = buffer.readShort();
    if (statusCode >= 0 && statusCode <= 999
        || statusCode >= 1004 && statusCode <= 1006
        || statusCode >= 1012 && statusCode <= 2999) {
      protocolViolation(ctx, "Invalid close frame getStatus code: " + statusCode);
    }

    // May have UTF-8 message
    if (buffer.isReadable()) {

      try {
        new UTF8Output(buffer);
      } catch (UTF8Exception ex) {
        protocolViolation(ctx, "Invalid close frame reason text. Invalid UTF-8 bytes");
      }
    }

    // Restore reader index
    buffer.readerIndex(idx);
  }
    @Override
    public OFInstructionIdBsnAutoNegotiation readFrom(ByteBuf bb) throws OFParseError {
      int start = bb.readerIndex();
      // fixed value property type == 65535
      short type = bb.readShort();
      if (type != (short) 0xffff)
        throw new OFParseError(
            "Wrong type: Expected=OFInstructionType.EXPERIMENTER(65535), got=" + type);
      int length = U16.f(bb.readShort());
      if (length != 12) throw new OFParseError("Wrong length: Expected=12(12), 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);
      // 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);

      if (logger.isTraceEnabled())
        logger.trace("readFrom - returning shared instance={}", INSTANCE);
      return INSTANCE;
    }
 public static int find(ByteBuf buffer, ByteBuf searchValue) {
   for (int i = buffer.readerIndex(); i < buffer.readerIndex() + buffer.readableBytes(); i++) {
     if (isValueFound(buffer, i, searchValue)) {
       return i;
     }
   }
   return -1;
 }
  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.");
    }
  }
Example #8
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;
 }
    @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;
    }
    /**
     * Peeks at that the next frame in the buffer and verifies that it is a {@code SETTINGS} frame.
     *
     * @param in the inbound buffer.
     * @return {@code} true if the next frame is a {@code SETTINGS} frame, {@code false} if more
     *     data is required before we can determine the next frame type.
     * @throws Http2Exception thrown if the next frame is NOT a {@code SETTINGS} frame.
     */
    private boolean verifyFirstFrameIsSettings(ByteBuf in) throws Http2Exception {
      if (in.readableBytes() < 4) {
        // Need more data before we can see the frame type for the first frame.
        return false;
      }

      byte frameType = in.getByte(in.readerIndex() + 3);
      if (frameType != SETTINGS) {
        throw connectionError(
            PROTOCOL_ERROR,
            "First received frame was not SETTINGS. " + "Hex dump for first 4 bytes: %s",
            hexDump(in, in.readerIndex(), 4));
      }
      return true;
    }
Example #11
0
  @Override
  protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception {
    final SocketAddress remoteAddress;
    final ByteBuf data;
    if (msg instanceof AddressedEnvelope) {
      @SuppressWarnings("unchecked")
      AddressedEnvelope<ByteBuf, SocketAddress> envelope =
          (AddressedEnvelope<ByteBuf, SocketAddress>) msg;
      remoteAddress = envelope.recipient();
      data = envelope.content();
    } else {
      data = (ByteBuf) msg;
      remoteAddress = null;
    }

    final int dataLen = data.readableBytes();
    if (dataLen == 0) {
      return true;
    }

    final ByteBuffer nioData = data.internalNioBuffer(data.readerIndex(), dataLen);
    final int writtenBytes;
    if (remoteAddress != null) {
      writtenBytes = javaChannel().send(nioData, remoteAddress);
    } else {
      writtenBytes = javaChannel().write(nioData);
    }
    return writtenBytes > 0;
  }
  @Override
  public int onDataRead(
      ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream)
      throws Http2Exception {
    FullHttpMessage msg = messageMap.get(streamId);
    if (msg == null) {
      throw connectionError(
          PROTOCOL_ERROR, "Data Frame received for unknown stream id %d", streamId);
    }

    ByteBuf content = msg.content();
    final int dataReadableBytes = data.readableBytes();
    if (content.readableBytes() > maxContentLength - dataReadableBytes) {
      throw connectionError(
          INTERNAL_ERROR,
          "Content length exceeded max of %d for stream id %d",
          maxContentLength,
          streamId);
    }

    content.writeBytes(data, data.readerIndex(), dataReadableBytes);

    if (endOfStream) {
      fireChannelRead(ctx, msg, streamId);
    }

    // All bytes have been processed.
    return dataReadableBytes + padding;
  }
  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;
  }
Example #14
0
 /**
  * Appends the specified {@code Buffer} to the end of this Buffer. The buffer will expand as
  * necessary to accommodate any bytes written.
  *
  * <p>Returns a reference to {@code this} so multiple operations can be appended together.
  */
 public Buffer appendBuffer(Buffer buff) {
   ByteBuf cb = buff.getByteBuf();
   buffer.writeBytes(buff.getByteBuf());
   cb.readerIndex(
       0); // Need to reset readerindex since Netty write modifies readerIndex of source!
   return this;
 }
Example #15
0
  private boolean add(ByteBuf var1) {
    if (this.count == Native.IOV_MAX) {
      return false;
    } else {
      int var2 = var1.readableBytes();
      if (var2 == 0) {
        return true;
      } else {
        long var3 = var1.memoryAddress();
        int var5 = var1.readerIndex();
        long var6 = this.memoryAddress(this.count++);
        long var8 = var6 + (long) ADDRESS_SIZE;
        if (ADDRESS_SIZE == 8) {
          PlatformDependent.putLong(var6, var3 + (long) var5);
          PlatformDependent.putLong(var8, (long) var2);
        } else {
          assert ADDRESS_SIZE == 4;

          PlatformDependent.putInt(var6, (int) var3 + var5);
          PlatformDependent.putInt(var8, var2);
        }

        this.size += (long) var2;
        return true;
      }
    }
  }
Example #16
0
 public void decodeSignature(final ByteBuf buf, final int readerBefore, final boolean donePayload)
     throws InvalidKeyException, SignatureException {
   final int readerAfter = buf.readerIndex();
   final int len = readerAfter - readerBefore;
   if (len > 0) {
     verifySignature(buf, readerBefore, len, donePayload);
   }
 }
Example #17
0
 /**
  * converts a bytebuf to byte array.
  *
  * @param buf
  * @param isReadDestroy if true then the reader index of the bytebuf will be modified.
  * @return
  */
 public static byte[] toByteArray(ByteBuf buf, boolean isReadDestroy) {
   byte[] arr = new byte[buf.readableBytes()];
   if (isReadDestroy) {
     buf.readBytes(arr);
   } else {
     buf.getBytes(buf.readerIndex(), arr);
   }
   return arr;
 }
  private void validate(final ByteBuf buffer) {
    final int rIdx = buffer.readerIndex();
    final int rLen = buffer.readableBytes();

    final int rLenC = rLen >= 2 ? rLen - 2 : 0;

    checkMessage(buffer.slice());
    checkPrintableAscii(buffer.slice(rIdx, rLenC));
  }
 @Override
 public OFBsnVport readFrom(ByteBuf bb) throws OFParseError {
   if (bb.readableBytes() < MINIMUM_LENGTH) return null;
   int start = bb.readerIndex();
   short type = bb.readShort();
   bb.readerIndex(start);
   switch (type) {
     case (short) 0x1:
       // discriminator value 0x1=0x1 for class OFBsnVportL2GreVer10
       return OFBsnVportL2GreVer10.READER.readFrom(bb);
     case (short) 0x0:
       // discriminator value 0x0=0x0 for class OFBsnVportQInQVer10
       return OFBsnVportQInQVer10.READER.readFrom(bb);
     default:
       throw new OFParseError(
           "Unknown value for discriminator type of class OFBsnVportVer10: " + type);
   }
 }
  private void checkPrintableAscii(final ByteBuf buffer) {
    final ByteBuf tmpBuffer = buffer.slice();
    final int lowerBound = tmpBuffer.readerIndex();
    final int upperBound = tmpBuffer.writerIndex();

    for (int idx = lowerBound; idx < upperBound; ++idx) {
      checkPrintableAscii(tmpBuffer.getByte(idx));
    }
  }
Example #21
0
 @Override
 public byte[] get() {
   if (byteBuf == null) {
     return EMPTY_BUFFER.array();
   }
   byte[] array = new byte[byteBuf.readableBytes()];
   byteBuf.getBytes(byteBuf.readerIndex(), array);
   return array;
 }
    @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 #23
0
  @Override
  protected void doWriteMessages(MessageBuf<Object> buf) throws Exception {
    DatagramPacket p = (DatagramPacket) buf.poll();
    ByteBuf data = p.data();
    int length = data.readableBytes();
    InetSocketAddress remote = p.remoteAddress();
    if (remote != null) {
      tmpPacket.setSocketAddress(remote);
    }
    if (data.hasArray()) {
      tmpPacket.setData(data.array(), data.arrayOffset() + data.readerIndex(), length);
    } else {
      byte[] tmp = new byte[length];
      data.getBytes(data.readerIndex(), tmp);
      tmpPacket.setData(tmp);
    }

    socket.send(tmpPacket);
  }
 @Override
 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
   // TODO Auto-generated method stub
   final byte[] array;
   final int length = in.readableBytes();
   array = new byte[length];
   in.getBytes(in.readerIndex(), array, 0, length);
   MessagePack messagePack = new MessagePack();
   out.add(messagePack.read(array));
 }
    @Override
    public OFBsnTlvMissPackets readFrom(ByteBuf bb) throws OFParseError {
      int start = bb.readerIndex();
      // fixed value property type == 0xd
      short type = bb.readShort();
      if (type != (short) 0xd) throw new OFParseError("Wrong type: Expected=0xd(0xd), got=" + type);
      int length = U16.f(bb.readShort());
      if (length != 12) throw new OFParseError("Wrong length: Expected=12(12), 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);
      U64 value = U64.ofRaw(bb.readLong());

      OFBsnTlvMissPacketsVer13 bsnTlvMissPacketsVer13 = new OFBsnTlvMissPacketsVer13(value);
      if (logger.isTraceEnabled()) logger.trace("readFrom - read={}", bsnTlvMissPacketsVer13);
      return bsnTlvMissPacketsVer13;
    }
Example #26
0
 @Override
 public void onMessage(NClient conn, Object message) {
   if (message instanceof TextWebSocketFrame) {
     TextWebSocketFrame f = (TextWebSocketFrame) message;
     System.out.println(f);
     System.out.println(f.text());
   } else {
     ByteBuf bb = (ByteBuf) message;
     bb.readerIndex(conn.getProtocol().headerLen());
     byte[] c = new byte[bb.readShort()];
     bb.readBytes(c);
     System.out.println(new String(c));
     bb.readerIndex(0);
     conn.sendFrame(bb);
   }
   try {
     Thread.sleep(500);
   } catch (Exception e) {
   }
 }
  @Override
  public boolean applyProtocol(ByteBuf buffer, ChannelPipeline pipeline) {
    boolean isThisProtocol = false;
    int size = buffer.readableBytes();
    byte[] newb = new byte[size];
    buffer.copy().readBytes(newb);
    LOGGER.trace("{}", newb);

    final int opcode = buffer.getUnsignedByte(buffer.readerIndex() + 2);
    final int protocolVersion = buffer.getUnsignedByte(buffer.readerIndex() + 3);
    if (isNadProtocol(opcode, protocolVersion)) {
      pipeline.addLast("framer", createLengthBasedFrameDecoder());
      pipeline.addLast("eventDecoder", eventDecoder);
      pipeline.addLast(LOGIN_HANDLER_NAME, loginHandler);
      pipeline.addLast("lengthFieldPrepender", lengthFieldPrepender);
      pipeline.addLast("eventEncoder", eventEncoder);
      isThisProtocol = true;
    }
    return isThisProtocol;
  }
 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);
 }
Example #29
0
 /**
  * Returns a decoded TXT (text) resource record, stored as an {@link java.util.ArrayList} of
  * {@code String}s.
  *
  * @param response the DNS response that contains the resource record being decoded
  * @param resource the resource record being decoded
  */
 @Override
 public List<String> decode(DnsResponse response, DnsResource resource) {
   List<String> list = new ArrayList<String>();
   ByteBuf data = resource.content().readerIndex(response.originalIndex());
   int index = data.readerIndex();
   while (index < data.writerIndex()) {
     int len = data.getUnsignedByte(index++);
     list.add(data.toString(index, len, CharsetUtil.UTF_8));
     index += len;
   }
   return list;
 }
 /**
  * Write bytes form the given {@link ByteBuf} to the underlying {@link java.nio.channels.Channel}.
  *
  * @param buf the {@link ByteBuf} from which the bytes should be written
  * @return amount the amount of written bytes
  */
 private int doWriteBytes(ByteBuf buf, int readable) throws Exception {
   int readerIndex = buf.readerIndex();
   int localFlushedAmount;
   if (buf.nioBufferCount() == 1) {
     if (buf.hasMemoryAddress()) {
       localFlushedAmount =
           Native.writeAddress(fd, buf.memoryAddress(), readerIndex, buf.writerIndex());
     } else {
       ByteBuffer nioBuf = buf.internalNioBuffer(readerIndex, readable);
       localFlushedAmount = Native.write(fd, nioBuf, nioBuf.position(), nioBuf.limit());
     }
   } else {
     // backed by more then one buffer, do a gathering write...
     ByteBuffer[] nioBufs = buf.nioBuffers();
     localFlushedAmount = (int) Native.writev(fd, nioBufs, 0, nioBufs.length);
   }
   if (localFlushedAmount > 0) {
     buf.readerIndex(readerIndex + localFlushedAmount);
   }
   return localFlushedAmount;
 }