示例#1
0
  protected CacheEntry(
      int _entry_type,
      CacheFileWithCache _file,
      DirectByteBuffer _buffer,
      long _offset,
      int _size) {
    entry_type = _entry_type;
    file = _file;
    buffer = _buffer;
    offset = _offset;
    size = _size;

    buffer_pos = buffer.position(DirectByteBuffer.SS_CACHE);
    buffer_limit = buffer.limit(DirectByteBuffer.SS_CACHE);

    if (size != buffer_limit - buffer_pos) {

      Debug.out(
          "CacheEntry: initial size incorrect - size ="
              + size
              + ", pos = "
              + buffer_pos
              + ", lim = "
              + buffer_limit);
    }

    dirty = true;
    last_used = SystemTime.getCurrentTime();
  }
示例#2
0
 protected String getString() {
   return ("["
       + offset
       + " - "
       + (offset + size - 1)
       + ":"
       + buffer.position(DirectByteBuffer.SS_CACHE)
       + "/"
       + buffer.limit(DirectByteBuffer.SS_CACHE)
       + "]");
 }
  @Override
  public Message deserialize(DirectByteBuffer data, byte version) throws MessageException {
    try {
      int pos = data.position(DirectByteBuffer.SS_MSG);
      byte[] raw = new byte[data.remaining(DirectByteBuffer.SS_MSG)];
      data.get(DirectByteBuffer.SS_MSG, raw);
      data.position(DirectByteBuffer.SS_MSG, pos);
      Map<?, ?> map = MessagingUtil.convertBencodedByteStreamToPayload(data, 2, getID());

      int msg_type = ((Long) map.get("msg_type")).intValue();
      int piece = ((Long) map.get("piece")).intValue();
      if (msg_type == REQUEST_MESSAGE_TYPE_ID) {
        return new UTMetadata(msg_type, piece, 0, null, (byte) 1);
      } else if (msg_type == DATA_MESSAGE_TYPE_ID) {
        int total_size = ((Long) map.get("total_size")).intValue();
        int offset = BEncoder.encode(map).length;
        byte[] metadata = new byte[raw.length - offset];
        System.arraycopy(raw, offset, metadata, 0, metadata.length);
        return new UTMetadata(msg_type, piece, total_size, metadata, (byte) 1);
      } else if (msg_type == REJECT_MESSAGE_TYPE_ID) {
        return new UTMetadata(msg_type, piece, 0, null, (byte) 1);
      }

      // what is the best way to handle this error?
      if (Logger.isEnabled()) {
        Logger.log(
            new LogEvent(LOGID, LogEvent.LT_ERROR, "METADATA (UT): No valid msg_type=" + msg_type));
      }

      return null;
    } catch (Throwable e) {
      // what is the best way to handle this error?
      if (Logger.isEnabled()) {
        Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "METADATA (UT)", e));
      }
      return null;
    }
  }
  private int postReadProcess() throws IOException {
    int prot_bytes_read = 0;
    int data_bytes_read = 0;

    if (!reading_length_mode && !destroyed) { // reading payload data mode
      // ensure-restore proper buffer limits
      payload_buffer.limit(SS, message_length);
      length_buffer.limit(SS, 4);

      int read = payload_buffer.position(SS) - pre_read_start_position;

      if (payload_buffer.position(SS) > 0) { // need to have read the message id first byte
        if (BTMessageFactory.getMessageType(payload_buffer) == Message.TYPE_DATA_PAYLOAD) {
          data_bytes_read += read;
        } else {
          prot_bytes_read += read;
        }
      }

      if (!payload_buffer.hasRemaining(SS) && !is_paused) { // full message received!
        payload_buffer.position(SS, 0);

        DirectByteBuffer ref_buff = payload_buffer;
        payload_buffer = null;

        if (reading_handshake_message) { // decode handshake
          reading_handshake_message = false;

          DirectByteBuffer handshake_data =
              DirectByteBufferPool.getBuffer(DirectByteBuffer.AL_MSG_BT_HAND, 68);
          handshake_data.putInt(SS, HANDSHAKE_FAKE_LENGTH);
          handshake_data.put(SS, ref_buff);
          handshake_data.flip(SS);

          ref_buff.returnToPool();

          try {
            Message handshake =
                MessageManager.getSingleton()
                    .createMessage(BTMessage.ID_BT_HANDSHAKE_BYTES, handshake_data, (byte) 1);
            messages_last_read.add(handshake);
          } catch (MessageException me) {
            handshake_data.returnToPool();
            throw new IOException("BT message decode failed: " + me.getMessage());
          }

          // we need to auto-pause decoding until we're told to start again externally,
          // as we don't want to accidentally read the next message on the stream if it's an
          // AZ-format handshake
          pauseDecoding();
        } else { // decode normal message
          try {
            messages_last_read.add(createMessage(ref_buff));
          } catch (Throwable e) {
            ref_buff.returnToPoolIfNotFree();

            // maintain unexpected errors as such so they get logged later

            if (e instanceof RuntimeException) {

              throw ((RuntimeException) e);
            }

            throw new IOException("BT message decode failed: " + e.getMessage());
          }
        }

        reading_length_mode = true; // see if we've already read the next message's length
        percent_complete = -1; // reset receive percentage
      } else { // only partial received so far
        percent_complete =
            (payload_buffer.position(SS) * 100) / message_length; // compute receive percentage
      }
    }

    if (reading_length_mode && !destroyed) {
      length_buffer.limit(SS, 4); // ensure proper buffer limit

      prot_bytes_read +=
          (pre_read_start_buffer == 1)
              ? length_buffer.position(SS) - pre_read_start_position
              : length_buffer.position(SS);

      if (!length_buffer.hasRemaining(SS)) { // done reading the length
        reading_length_mode = false;

        length_buffer.position(SS, 0);
        message_length = length_buffer.getInt(SS);

        length_buffer.position(SS, 0); // reset it for next length read

        if (message_length == HANDSHAKE_FAKE_LENGTH) { // handshake message
          reading_handshake_message = true;
          message_length = 64; // restore 'real' length
          payload_buffer =
              DirectByteBufferPool.getBuffer(DirectByteBuffer.AL_MSG_BT_HAND, message_length);
        } else if (message_length == 0) { // keep-alive message
          reading_length_mode = true;
          last_received_was_keepalive = true;

          try {
            Message keep_alive =
                MessageManager.getSingleton()
                    .createMessage(BTMessage.ID_BT_KEEP_ALIVE_BYTES, null, (byte) 1);
            messages_last_read.add(keep_alive);
          } catch (MessageException me) {
            throw new IOException("BT message decode failed: " + me.getMessage());
          }
        } else if (message_length < MIN_MESSAGE_LENGTH || message_length > MAX_MESSAGE_LENGTH) {
          throw new IOException(
              "Invalid message length given for BT message decode: " + message_length);
        } else { // normal message
          payload_buffer =
              DirectByteBufferPool.getBuffer(DirectByteBuffer.AL_MSG_BT_PAYLOAD, message_length);
        }
      }
    }

    protocol_bytes_last_read += prot_bytes_read;
    data_bytes_last_read += data_bytes_read;

    return prot_bytes_read + data_bytes_read;
  }
  public ByteBuffer destroy() {
    if (destroyed) {
      Debug.out("Trying to redestroy message decoder, stack trace follows: " + this);
      Debug.outStackTrace();
    }

    is_paused = true;
    destroyed = true;

    // there's a concurrency issue with the decoder whereby it can be destroyed while will being
    // messed with. Don't
    // have the energy to look into it properly atm so just try to ensure that it doesn't bork too
    // badly (parg: 29/04/2012)
    // only occasional but does have potential to generate direct buffer mem leak ;(

    int lbuff_read = 0;
    int pbuff_read = 0;
    length_buffer.limit(SS, 4);

    DirectByteBuffer plb = payload_buffer;

    if (reading_length_mode) {
      lbuff_read = length_buffer.position(SS);
    } else { // reading payload
      length_buffer.position(SS, 4);
      lbuff_read = 4;
      pbuff_read = plb == null ? 0 : plb.position(SS);
    }

    ByteBuffer unused = ByteBuffer.allocate(lbuff_read + pbuff_read); // TODO convert to direct?

    length_buffer.flip(SS);
    unused.put(length_buffer.getBuffer(SS));

    try {
      if (plb != null) {
        plb.flip(SS);
        unused.put(
            plb.getBuffer(
                SS)); // Got a buffer overflow exception here in the past - related to PEX?
      }
    } catch (RuntimeException e) {
      Debug.out("hit known threading issue");
    }

    unused.flip();

    length_buffer.returnToPool();

    if (plb != null) {
      plb.returnToPool();
      payload_buffer = null;
    }

    try {
      for (int i = 0; i < messages_last_read.size(); i++) {
        Message msg = (Message) messages_last_read.get(i);
        msg.destroy();
      }
    } catch (RuntimeException e) {
      // happens if messages modified by alt thread...
      Debug.out("hit known threading issue");
    }
    messages_last_read.clear();

    return unused;
  }
示例#6
0
 protected void resetBufferPosition() {
   buffer.position(DirectByteBuffer.SS_CACHE, buffer_pos);
 }