public static AnnounceRequest parse(byte[] byteArray) {
    ByteBuffer bufferReceive = ByteBuffer.wrap(byteArray);
    AnnounceRequest request = new AnnounceRequest();

    request.setConnectionId(bufferReceive.getLong(0));
    request.setAction(Action.valueOf(bufferReceive.getInt(8)));
    request.setTransactionId(bufferReceive.getInt(12));

    byte[] infoHash = new byte[20];
    bufferReceive.position(16);
    bufferReceive.get(infoHash);
    request.setInfoHash(Utilities.toHexString(infoHash));

    byte[] peerId = new byte[20];
    bufferReceive.position(36);
    bufferReceive.get(peerId);
    request.setPeerId(new String(peerId));
    request.setDownloaded(bufferReceive.getLong(56));
    request.setLeft(bufferReceive.getLong(64));
    request.setUploaded(bufferReceive.getLong(72));
    request.setEvent(Event.valueOf(bufferReceive.getInt(80)));
    PeerInfo peerInfo = new PeerInfo();
    peerInfo.setIpAddress(bufferReceive.getInt(84));
    peerInfo.setPort(bufferReceive.getChar(96));
    request.setPeerInfo(peerInfo);

    request.setKey(bufferReceive.getInt(88));
    request.setNumWant(bufferReceive.getInt(92));

    return request;
  }
Ejemplo n.º 2
0
 public static long hash64A(final ByteBuffer buf, final int seed) {
   final ByteOrder byteOrder = buf.order();
   buf.order(ByteOrder.LITTLE_ENDIAN);
   final long m = -4132994306676758123L;
   final int r = 47;
   long h = seed ^ buf.remaining() * m;
   while (buf.remaining() >= 8) {
     long k = buf.getLong();
     k *= m;
     k ^= k >>> r;
     k *= m;
     h ^= k;
     h *= m;
   }
   if (buf.remaining() > 0) {
     final ByteBuffer finish = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
     finish.put(buf).rewind();
     h ^= finish.getLong();
     h *= m;
   }
   h ^= h >>> r;
   h *= m;
   h ^= h >>> r;
   buf.order(byteOrder);
   return h;
 }
Ejemplo n.º 3
0
  private static void parseTCPMsg(byte[] msg) throws UnknownHostException {
    switch (msg[0]) {
      case 0x00:
        if (msg[1] == 0x01) System.out.println("Server: OPEN");
        else System.out.println("Server: CLOSED");
        break;
      case 0x01:
        if (msg[1] == 0x00)
          System.out.printf("[ERR]: %s", new String(Arrays.copyOfRange(msg, 2, msg.length)));
        else {
          ByteBuffer buffer = ByteBuffer.wrap(Arrays.copyOfRange(msg, 1, msg.length));
          userId = new UUID(buffer.getLong(), buffer.getLong());
          groupIp =
              InetAddress.getByAddress(ByteBuffer.allocate(4).putInt(buffer.getInt()).array());

          // connect to the group and start receiving
          udpSocket.connect(groupIp.getHostAddress());
          udpSocket.startReceive(new UDPHandler());

          System.out.printf(
              "User ID: %s\nGroup IP: %s\nPort: %d\n",
              userId.toString(), groupIp.getHostAddress(), buffer.getInt());
        }
        break;
      case 0x02:
        if (msg[1] == 0x00)
          System.out.printf("[ERR]: %s", new String(Arrays.copyOfRange(msg, 2, msg.length)));
        else System.out.println("Successfully deregestered");
      default:
        System.out.println("[ERR] Inavlid msg");
    }
  }
  public DataFileAccessorImpl(final File file) throws Exception {
    this.fileInfo = file;
    this.file = new RandomAccessFile(file, "rw");

    try {
      this.channel = this.file.getChannel();

      final ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE);

      while (buffer.hasRemaining()) {
        final int rc = this.channel.read(buffer);
        logger.debug("Read {} bytes", rc);
      }

      buffer.flip();

      final int magic = buffer.getInt();
      final int version = buffer.getInt();
      this.start = new Date(buffer.getLong());
      this.end = new Date(buffer.getLong());

      logger.debug(
          "Header - magic: {}, version: {}, start: {}, end: {}",
          new Object[] {magic, version, this.start, this.end});

      if (logger.isDebugEnabled()) {
        logger.debug("File position after header: {}", this.channel.position());
      }
      // position is at end of file
    } catch (final Exception e) {
      logger.warn("Failed to open file", e);
      this.file.close();
      throw e;
    }
  }
Ejemplo n.º 5
0
 private Object getSingleValue(ByteBuffer buffer) {
   Object v;
   if (type.equals("float")) {
     v = buffer.getFloat();
   } else if (type.equals("double")) {
     v = buffer.getDouble();
   } else if (type.equals("int8_t") || type.equals("bool")) {
     v = (int) buffer.get();
   } else if (type.equals("uint8_t")) {
     v = buffer.get() & 0xFF;
   } else if (type.equals("int16_t")) {
     v = (int) buffer.getShort();
   } else if (type.equals("uint16_t")) {
     v = buffer.getShort() & 0xFFFF;
   } else if (type.equals("int32_t")) {
     v = buffer.getInt();
   } else if (type.equals("uint32_t")) {
     v = buffer.getInt() & 0xFFFFFFFFl;
   } else if (type.equals("int64_t")) {
     v = buffer.getLong();
   } else if (type.equals("uint64_t")) {
     v = buffer.getLong();
   } else if (type.equals("char")) {
     v = buffer.get();
   } else {
     throw new RuntimeException("Unsupported type: " + type);
   }
   return v;
 }
Ejemplo n.º 6
0
    public Object objectFromBuffer(byte[] buffer, int offset, int length) throws Exception {
      ByteBuffer buf = ByteBuffer.wrap(buffer, offset, length);

      byte type = buf.get();
      switch (type) {
        case START:
        case GET_CONFIG:
          return new MethodCall(type);
        case SET_OOB:
        case SET_SYNC:
          return new MethodCall(type, buf.get() == 1);
        case SET_NUM_MSGS:
        case SET_NUM_THREADS:
        case SET_MSG_SIZE:
        case SET_ANYCAST_COUNT:
          return new MethodCall(type, buf.getInt());
        case GET:
          return new MethodCall(type, buf.getLong());
        case PUT:
          Long longarg = buf.getLong();
          int len = buf.getInt();
          byte[] arg2 = new byte[len];
          buf.get(arg2, 0, arg2.length);
          return new MethodCall(type, longarg, arg2);
        case SET_READ_PERCENTAGE:
          return new MethodCall(type, buf.getDouble());
        default:
          throw new IllegalStateException("type " + type + " not known");
      }
    }
Ejemplo n.º 7
0
  public ChmItsfHeader(ByteBuffer bb) {
    byte[] sbuf = new byte[4];
    bb.get(sbuf);
    signature = new String(sbuf);

    version = bb.getInt();
    header_len = bb.getInt();
    unknown_000c = bb.getInt();
    last_modified = ByteBufferHelper.parseBigEndianInt(bb);
    Calendar c = Calendar.getInstance();
    c.set(1970, Calendar.JANUARY, 1);
    c.add(Calendar.SECOND, 0x3DB0C239);
    timestamp = c.getTime();
    // DateFormat f = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    // System.out.println("Last modified: " + f.format(timestamp));

    lang_id = bb.getInt();
    bb.get(new byte[32]);
    unknown_len = bb.getLong();
    unknown_offset = bb.getLong();
    dir_offset = bb.getLong();
    dir_len = bb.getLong();
    data_offset = 0; // TODO:
    if (version >= 3) {
      data_offset = bb.getLong();
    }
  }
Ejemplo n.º 8
0
 private Object getValue(MAVLinkDataType type, int offset) {
   switch (type) {
     case CHAR:
       return payloadBB.get(offset);
     case UINT8:
       return payloadBB.get(offset) & 0xFF;
     case INT8:
       return (int) payloadBB.get(offset);
     case UINT16:
       return payloadBB.getShort(offset) & 0xFFFF;
     case INT16:
       return (int) payloadBB.getShort(offset);
     case UINT32:
       return payloadBB.getInt(offset) & 0xFFFFFFFFl;
     case INT32:
       return payloadBB.getInt(offset);
     case UINT64:
       return payloadBB.getLong(offset);
     case INT64:
       return payloadBB.getLong(offset);
     case FLOAT:
       return payloadBB.getFloat(offset);
     case DOUBLE:
       return payloadBB.getDouble(offset);
     default:
       throw new RuntimeException("Unknown type: " + type);
   }
 }
Ejemplo n.º 9
0
 DigitalGoodsPurchase(ByteBuffer buffer, byte transactionVersion) {
   super(buffer, transactionVersion);
   this.goodsId = buffer.getLong();
   this.quantity = buffer.getInt();
   this.priceNQT = buffer.getLong();
   this.deliveryDeadlineTimestamp = buffer.getInt();
 }
Ejemplo n.º 10
0
 @Override
 public Object fetch(long r, Charset encoding) {
   ByteBuffer bb = pickByteBuffer();
   long len =
       ngx_http_clojure_mem_get_request_body(r, bb.array(), BYTE_ARRAY_OFFSET, bb.capacity());
   if (len == 0) {
     return null;
   } else if (len < 0) {
     len = -len;
     bb.limit((int) len);
     String tmpfile = decode(bb, DEFAULT_ENCODING, pickCharBuffer());
     try {
       if (log.isDebugEnabled()) {
         log.debug("#%d:get tmp file :%s", r, tmpfile);
       }
       return new FileInputStream(tmpfile);
     } catch (FileNotFoundException e) {
       throw new RuntimeException("can not find tmp file", e);
     }
   } else {
     long li = bb.order(ByteOrder.nativeOrder()).getLong();
     if (li == len) {
       return new NativeInputStream(bb.getLong(), len);
     } else {
       InputStream rt = new NativeInputStream(bb.getLong(), li);
       li = bb.getLong();
       while (li > 0) {
         rt = new SequenceInputStream(rt, new NativeInputStream(bb.getLong(), li));
         li = bb.getLong();
       }
       return rt;
     }
   }
 }
Ejemplo n.º 11
0
  /**
   * @param b
   * @return
   */
  public static UUID fromByte(byte[] b) {
    final ByteBuffer bb = ByteBuffer.wrap(b);
    long firstLong = bb.getLong();
    long secondLong = bb.getLong();

    return new UUID(firstLong, secondLong);
  }
Ejemplo n.º 12
0
 public Data09(DatagramPacket p, Player player, long serverID) {
   ByteBuffer b = ByteBuffer.wrap(p.getData());
   b.get();
   b.getLong();
   unknown1 = b.getLong();
   this.player = player;
   this.serverID = serverID;
 }
Ejemplo n.º 13
0
  public UUID compose(ByteBuffer bytes) {

    bytes = bytes.slice();
    if (bytes.remaining() < 16) {
      return new UUID(0, 0);
    }
    return new UUID(bytes.getLong(), bytes.getLong());
  }
Ejemplo n.º 14
0
  /**
   * Reader factory method. Build a Node object (of the right type) by reading a block in the file.
   *
   * @param config Configuration of the History Tree
   * @param fc FileChannel to the history file, ALREADY SEEKED at the start of the node.
   * @return The node object
   * @throws IOException If there was an error reading from the file channel
   */
  public static final HTNode readNode(HTConfig config, FileChannel fc) throws IOException {
    HTNode newNode = null;
    int res, i;

    ByteBuffer buffer = ByteBuffer.allocate(config.getBlockSize());
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.clear();
    res = fc.read(buffer);
    assert (res == config.getBlockSize());
    buffer.flip();

    /* Read the common header part */
    byte typeByte = buffer.get();
    NodeType type = NodeType.fromByte(typeByte);
    long start = buffer.getLong();
    long end = buffer.getLong();
    int seqNb = buffer.getInt();
    int parentSeqNb = buffer.getInt();
    int intervalCount = buffer.getInt();
    int stringSectionOffset = buffer.getInt();
    buffer.get(); // TODO Used to be "isDone", to be removed from the header

    /* Now the rest of the header depends on the node type */
    switch (type) {
      case CORE:
        /* Core nodes */
        newNode = new CoreNode(config, seqNb, parentSeqNb, start);
        newNode.readSpecificHeader(buffer);
        break;

      case LEAF:
        /* Leaf nodes */
        newNode = new LeafNode(config, seqNb, parentSeqNb, start);
        newNode.readSpecificHeader(buffer);
        break;

      default:
        /* Unrecognized node type */
        throw new IOException();
    }

    /*
     * At this point, we should be done reading the header and 'buffer'
     * should only have the intervals left
     */
    for (i = 0; i < intervalCount; i++) {
      HTInterval interval = HTInterval.readFrom(buffer);
      newNode.fIntervals.add(interval);
      newNode.fSizeOfIntervalSection += interval.getIntervalSize();
    }

    /* Assign the node's other information we have read previously */
    newNode.fNodeEnd = end;
    newNode.fStringSectionOffset = stringSectionOffset;
    newNode.fIsOnDisk = true;

    return newNode;
  }
Ejemplo n.º 15
0
 public static Authorization fromToken(SecretKeySpec key, String token)
     throws AuthenticationException {
   if (token == null) {
     throw new IllegalArgumentException("Token required");
   }
   try {
     int hashSizeBytes = 16;
     Cipher decodingCipher = Cipher.getInstance("AES");
     decodingCipher.init(Cipher.DECRYPT_MODE, key);
     ByteBuffer buffer =
         ByteBuffer.wrap(decodingCipher.doFinal(Hex.decodeHex(token.toCharArray())));
     MessageDigest messageDigest = MessageDigest.getInstance("MD5");
     byte[] foundHash = new byte[hashSizeBytes];
     buffer.get(foundHash, 0, hashSizeBytes);
     byte[] hashInput = new byte[buffer.capacity() - hashSizeBytes];
     buffer.get(hashInput);
     buffer.position(hashSizeBytes);
     byte[] calculatedHash = messageDigest.digest(hashInput);
     if (Arrays.equals(foundHash, calculatedHash)) {
       byte type = buffer.get();
       Authorization authorization = null;
       long expires = buffer.getLong();
       long uoid = buffer.getLong();
       switch (type) {
         case ExplicitRightsAuthorization.ID:
           authorization = ExplicitRightsAuthorization.fromBuffer(buffer);
           break;
         case UserAuthorization.ID:
           authorization = UserAuthorization.fromBuffer(buffer);
           break;
         case SystemAuthorization.ID:
           authorization = SystemAuthorization.fromBuffer(buffer);
           break;
         case AnonymousAuthorization.ID:
           authorization = AnonymousAuthorization.fromBuffer(buffer);
           break;
         case AdminAuthorization.ID:
           authorization = AdminAuthorization.fromBuffer(buffer);
           break;
         default:
           throw new AuthenticationException("Unknown authorization type: " + type);
       }
       authorization.setUoid(uoid);
       authorization.setExpires(expires);
       if (authorization.getExpires().getTimeInMillis()
           < new GregorianCalendar().getTimeInMillis()) {
         throw new AuthenticationException("This token has expired");
       }
       return authorization;
     } else {
       throw new AuthenticationException("Given token is corrupt");
     }
   } catch (GeneralSecurityException e) {
     throw new AuthenticationException("Invalid token", e);
   } catch (DecoderException e) {
     throw new AuthenticationException(e);
   }
 }
Ejemplo n.º 16
0
 public static UUID fromBytes(byte[] array) {
   if (array.length != 16) {
     throw new IllegalArgumentException("Illegal byte array length: " + array.length);
   }
   ByteBuffer byteBuffer = ByteBuffer.wrap(array);
   long mostSignificant = byteBuffer.getLong();
   long leastSignificant = byteBuffer.getLong();
   return new UUID(mostSignificant, leastSignificant);
 }
Ejemplo n.º 17
0
  /**
   * Returns the clock and the count associated with the given counter id, or (0, 0) if no such
   * shard is present.
   */
  @VisibleForTesting
  public ClockAndCount getClockAndCountOf(ByteBuffer context, CounterId id) {
    int position = findPositionOf(context, id);
    if (position == -1) return ClockAndCount.BLANK;

    long clock = context.getLong(position + CounterId.LENGTH);
    long count = context.getLong(position + CounterId.LENGTH + CLOCK_LENGTH);
    return ClockAndCount.create(clock, count);
  }
Ejemplo n.º 18
0
 @Override
 // TODO replace on tweeter Snowflake
 public String getId() {
   if (null == this.uuid) {
     final ByteBuffer bb = ByteBuffer.wrap(this.id);
     final UUID u = new UUID(bb.getLong(), bb.getLong());
     this.uuid = u.toString();
   }
   return this.uuid;
 }
Ejemplo n.º 19
0
  public ExtendedBpb(ByteBuffer bb) {
    super(bb);

    totalSectors = bb.getLong(TOTAL_SECTORS_OFFSET);
    mftLogicalCluster = bb.getLong(MFT_LOGICAL_CLUSTER_OFFSET);
    mftMirrorLogicalCluster = bb.getLong(MFT_MIRROR_LOGICAL_CLUSTER_OFFSET);
    clustersPerMftRecord = bb.get(CLUSTERS_PER_MFT_RECORD);
    clustersPerIndexBuffer = bb.get(CLUSTERS_PER_INDEX_BUFFER_OFFSET);
    volumeSerialNumber = bb.getLong(VOLUME_SERIAL_NUMBER_OFFSET);
  }
Ejemplo n.º 20
0
 /**
  * This comparator WILL compare between xsd:decimal and the extending types
  *
  * @see org.mulgara.store.stringpool.SPComparator#compare(ByteBuffer, int, ByteBuffer, int)
  */
 public int compare(ByteBuffer d1, int subtypeId1, ByteBuffer d2, int subtypeId2) {
   int c;
   if (isLong(d1) && isLong(d2)) {
     c = SPDecimalExtImpl.compare(d1.getLong(), d2.getLong());
   } else {
     c = decode(d1).compareTo(decode(d2));
   }
   if (c == 0) c = AbstractSPObject.compare(subtypeId1, subtypeId2);
   return c;
 }
Ejemplo n.º 21
0
  public static ZipFile.EocdRecord parseZip64EocdRecord(
      RandomAccessFile raf, long eocdRecordOffset, int commentLength) throws IOException {
    raf.seek(eocdRecordOffset);
    final int signature = Integer.reverseBytes(raf.readInt());
    if (signature != ZIP64_EOCD_RECORD_SIGNATURE) {
      throw new ZipException(
          "Invalid zip64 eocd record offset, sig="
              + Integer.toHexString(signature)
              + " offset="
              + eocdRecordOffset);
    }

    // The zip64 eocd record specifies its own size as an 8 byte integral type. It is variable
    // length because of the "zip64 extensible data sector" but that field is reserved for
    // pkware's proprietary use. We therefore disregard it altogether and treat the end of
    // central directory structure as fixed length.
    //
    // We also skip "version made by" (2 bytes) and "version needed to extract" (2 bytes)
    // fields. We perform additional validation at the ZipEntry level, where applicable.
    //
    // That's a total of 12 bytes to skip
    raf.skipBytes(12);

    byte[] zip64Eocd = new byte[ZIP64_EOCD_RECORD_EFFECTIVE_SIZE];
    raf.readFully(zip64Eocd);

    ByteBuffer buf = ByteBuffer.wrap(zip64Eocd).order(ByteOrder.LITTLE_ENDIAN);
    try {
      int diskNumber = buf.getInt();
      int diskWithCentralDirStart = buf.getInt();
      long numEntries = buf.getLong();
      long totalNumEntries = buf.getLong();
      buf.getLong(); // Ignore the size of the central directory
      long centralDirOffset = buf.getLong();

      if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDirStart != 0) {
        throw new ZipException(
            "Spanned archives not supported :"
                + " numEntries="
                + numEntries
                + ", totalNumEntries="
                + totalNumEntries
                + ", diskNumber="
                + diskNumber
                + ", diskWithCentralDirStart="
                + diskWithCentralDirStart);
      }

      return new ZipFile.EocdRecord(numEntries, centralDirOffset, commentLength);
    } catch (BufferUnderflowException bue) {
      ZipException zipException = new ZipException("Error parsing zip64 eocd record.");
      zipException.initCause(bue);
      throw zipException;
    }
  }
Ejemplo n.º 22
0
 ColoredCoinsAssetTransfer(ByteBuffer buffer, byte transactionVersion)
     throws RiseException.NotValidException {
   super(buffer, transactionVersion);
   this.assetId = buffer.getLong();
   this.quantityQNT = buffer.getLong();
   this.comment =
       getVersion() == 0
           ? Convert.readString(
               buffer, buffer.getShort(), Constants.MAX_ASSET_TRANSFER_COMMENT_LENGTH)
           : null;
 }
 @Override
 public boolean decode(final byte[] rawDatas) {
   final ByteBuffer bb = ByteBuffer.wrap(rawDatas);
   this.m_eventId = bb.getLong();
   this.m_invitedId = bb.getLong();
   final byte[] tInvitedName = new byte[bb.get()];
   bb.get(tInvitedName);
   this.m_invitedName = StringUtils.fromUTF8(tInvitedName);
   this.m_result = bb.get();
   return true;
 }
Ejemplo n.º 24
0
  public void onReceive(ByteBuffer b) {
    if (b.remaining() == 4) {
      Common.logError("invalid packet:");
      byte[] data = new byte[b.remaining()];
      b.get(data);
      Common.print_dump(data);
      //	retry( TLMessage.keyAt(  TLMessage.size() - 1) );
      return;
    }

    try {
      if (b.getLong() == 0) { // auth_key_id
        b.getLong(); // message_id
        b.getInt(); // message length
        process(TL.deserialize(b));
      } else {
        byte[] msg_key = new byte[16];
        b.get(msg_key);
        byte[] data = new byte[b.remaining()];
        b.get(data);

        synchronized (aes) {
          aes.prepare(false, msg_key, auth_key);
          data = aes.IGE(data, false);
        }

        ByteBuffer btmp = ByteBuffer.wrap(data);
        btmp.order(ByteOrder.LITTLE_ENDIAN);
        server_salt = btmp.getLong();
        btmp.getLong(); // session_id
        cur_message_id = btmp.getLong(); // message_id
        cur_msg_seq = btmp.getInt(); // seq_no
        // if (cur_msg_seq > seqno)
        //	seqno = cur_msg_seq + cur_msg_seq % 2;
        int bsize = btmp.getInt();
        if (bsize < 0 || bsize > 1024 * 1024) {
          Common.print_dump(btmp.array());
          Common.logError(new String(btmp.array()));
          Common.logError("FFFUUUUUUUUUUU!!!");
        }

        b = BufferAlloc(bsize);
        btmp.get(b.array());
        b.getInt();
        ack_message(cur_msg_seq, cur_message_id);
        b.position(0);

        process(TL.deserialize(b));
        send_accept();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 25
0
 public void decode(ByteBuffer buf) {
   type = Type.values()[buf.getInt()];
   keySize = buf.getInt();
   valueSize = buf.getInt();
   keyCount = buf.getLong();
   order = Order.values()[buf.getInt()];
   distribution = Distribution.values()[buf.getInt()];
   start = buf.getLong();
   end = buf.getLong();
   scanBufferSize = buf.getInt();
 }
Ejemplo n.º 26
0
 DigitalGoodsDelivery(ByteBuffer buffer, byte transactionVersion)
     throws RiseException.NotValidException {
   super(buffer, transactionVersion);
   this.purchaseId = buffer.getLong();
   int length = buffer.getInt();
   goodsIsText = length < 0;
   if (length < 0) {
     length &= Integer.MAX_VALUE;
   }
   this.goods = EncryptedData.readEncryptedData(buffer, length, Constants.MAX_DGS_GOODS_LENGTH);
   this.discountNQT = buffer.getLong();
 }
Ejemplo n.º 27
0
 public boolean next() throws IOException {
   for (; ; ) {
     if (buf == null || !buf.hasRemaining()) {
       if (input == null) {
         return false;
       }
       buf = input.readNext();
       limit = buf == null ? 0 : buf.limit();
       if (limit <= 0) {
         close();
         return false;
       }
     }
     modificationTime = buf.getLong();
     filesize = buf.getLong();
     replication = buf.getInt();
     final int nameLen = buf.getInt();
     isDirectory = buf.get() != 0;
     numStripes = buf.getInt();
     numRecoveryStripes = buf.getInt();
     striperType = buf.getInt();
     stripeSize = buf.getInt();
     owner = buf.getInt();
     group = buf.getInt();
     mode = buf.getShort();
     fileId = buf.getLong();
     fileCount = isDirectory ? buf.getLong() : 0;
     dirCount = isDirectory ? buf.getLong() : 0;
     final int onameLen = buf.getInt();
     final int gnameLen = buf.getInt();
     owner &= 0xFFFFFFFFL;
     group &= 0xFFFFFFFFL;
     mode &= 0xFFFF;
     filename = readString(nameLen);
     if (owner == prevOwner && ownerName != null) {
       skip(onameLen);
     } else {
       prevOwner = owner;
       ownerName = readString(onameLen);
     }
     if (group == prevGroup && groupName != null) {
       skip(gnameLen);
     } else {
       prevGroup = group;
       groupName = readString(gnameLen);
     }
     if (nameLen > 0) {
       break;
     }
   }
   return true;
 }
Ejemplo n.º 28
0
  /**
   * Factory method for Request and Response. It expects the bytes to be correctly formed so it's
   * possible that it throws underflow exceptions but you shouldn't be concerned about that since
   * that all bytes sent in should already be formatted correctly.
   *
   * @param bytes bytes to be converted.
   * @return Request or Response depending on the data.
   * @throws ClassNotFoundException if the Command or Answer can not be formed.
   * @throws
   */
  public static Request parse(final byte[] bytes)
      throws ClassNotFoundException, UnsupportedVersionException {
    ByteBuffer buff = ByteBuffer.wrap(bytes);
    final byte ver = buff.get();
    final Version version = Version.get(ver);
    if (version.ordinal() != Version.v1.ordinal() && version.ordinal() != Version.v3.ordinal()) {
      throw new UnsupportedVersionException(
          "This version is no longer supported: " + version.toString(),
          UnsupportedVersionException.IncompatibleVersion);
    }
    final byte reserved = buff.get(); // tossed away for now.
    final short flags = buff.getShort();
    final boolean isRequest = (flags & FLAG_REQUEST) > 0;

    final long seq = buff.getLong();
    // The size here is uncompressed size, if the data is compressed.
    final int size = buff.getInt();
    final long mgmtId = buff.getLong();
    final long agentId = buff.getLong();

    long via;
    if (version.ordinal() == Version.v1.ordinal()) {
      via = buff.getLong();
    } else {
      via = agentId;
    }

    if ((flags & FLAG_COMPRESSED) != 0) {
      buff = doDecompress(buff, size);
    }

    byte[] command = null;
    int offset = 0;
    if (buff.hasArray()) {
      command = buff.array();
      offset = buff.arrayOffset() + buff.position();
    } else {
      command = new byte[buff.remaining()];
      buff.get(command);
      offset = 0;
    }

    final String content = new String(command, offset, command.length - offset);

    if (isRequest) {
      return new Request(version, seq, agentId, mgmtId, via, flags, content);
    } else {
      return new Response(Version.get(ver), seq, agentId, mgmtId, via, flags, content);
    }
  }
Ejemplo n.º 29
0
  public static void main(final String[] args) throws IOException {
    final FileChannel receiveFileChannel = Common.createTmpFileChannel();
    final ByteBuffer receiveByteBuffer =
        receiveFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, MTU_LENGTH_DEFAULT);
    final DatagramChannel receiveDatagramChannel = DatagramChannel.open();
    init(receiveDatagramChannel);
    receiveDatagramChannel.bind(new InetSocketAddress("localhost", 40124));
    receiveDatagramChannel.connect(new InetSocketAddress("localhost", 40123));

    final FileChannel sendFileChannel = Common.createTmpFileChannel();
    final ByteBuffer sendByteBuffer =
        sendFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, MTU_LENGTH_DEFAULT);
    final DatagramChannel sendDatagramChannel = DatagramChannel.open();
    init(sendDatagramChannel);
    sendDatagramChannel.bind(new InetSocketAddress("localhost", 40125));
    sendDatagramChannel.connect(new InetSocketAddress("localhost", 40126));

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    final int packetSize = SIZE_OF_LONG * 2;

    while (true) {
      boolean available = false;
      while (!available) {
        if (!running.get()) {
          return;
        }

        final long bytesReceived =
            receiveFileChannel.transferFrom(receiveDatagramChannel, 0, packetSize);
        if (packetSize == bytesReceived) {
          available = true;
        }
      }

      final long receivedSequenceNumber = receiveByteBuffer.getLong(0);
      final long receivedTimestamp = receiveByteBuffer.getLong(SIZE_OF_LONG);

      sendByteBuffer.putLong(0, receivedSequenceNumber);
      sendByteBuffer.putLong(SIZE_OF_LONG, receivedTimestamp);

      final long bytesSent = sendFileChannel.transferTo(0, packetSize, sendDatagramChannel);
      if (packetSize != bytesSent) {
        throw new IllegalStateException("Invalid bytes sent " + bytesSent);
      }
    }
  }
Ejemplo n.º 30
0
  /**
   * Parses the zip64 end of central directory record locator. The locator must be placed
   * immediately before the end of central directory (eocd) record starting at {@code eocdOffset}.
   *
   * <p>The position of the file cursor for {@code raf} after a call to this method is undefined an
   * callers must reposition it after each call to this method.
   */
  public static long parseZip64EocdRecordLocator(RandomAccessFile raf, long eocdOffset)
      throws IOException {
    // The spec stays curiously silent about whether a zip file with an EOCD record,
    // a zip64 locator and a zip64 eocd record is considered "empty". In our implementation,
    // we parse all records and read the counts from them instead of drawing any size or
    // layout based information.
    if (eocdOffset > ZIP64_LOCATOR_SIZE) {
      raf.seek(eocdOffset - ZIP64_LOCATOR_SIZE);
      if (Integer.reverseBytes(raf.readInt()) == ZIP64_LOCATOR_SIGNATURE) {
        byte[] zip64EocdLocator = new byte[ZIP64_LOCATOR_SIZE - 4];
        raf.readFully(zip64EocdLocator);
        ByteBuffer buf = ByteBuffer.wrap(zip64EocdLocator).order(ByteOrder.LITTLE_ENDIAN);

        final int diskWithCentralDir = buf.getInt();
        final long zip64EocdRecordOffset = buf.getLong();
        final int numDisks = buf.getInt();

        if (numDisks != 1 || diskWithCentralDir != 0) {
          throw new ZipException("Spanned archives not supported");
        }

        return zip64EocdRecordOffset;
      }
    }

    return -1;
  }