public void validateForNativeProtocol(ByteBuffer bytes, ProtocolVersion version) { try { ByteBuffer input = bytes.duplicate(); int n = readCollectionSize(input, version); for (int i = 0; i < n; i++) elements.validate(readValue(input, version)); if (input.hasRemaining()) throw new MarshalException("Unexpected extraneous bytes after list value"); } catch (BufferUnderflowException e) { throw new MarshalException("Not enough bytes to read a list"); } }
/** * Given a serialized map, gets the value associated with a given key. * @param serializedMap a serialized map * @param serializedKey a serialized key * @param keyType the key type for the map * @return the value associated with the key if one exists, null otherwise */ public ByteBuffer getSerializedValue(ByteBuffer serializedMap, ByteBuffer serializedKey, AbstractType keyType) { try { ByteBuffer input = serializedMap.duplicate(); int n = readCollectionSize(input, ProtocolVersion.V3); for (int i = 0; i < n; i++) { ByteBuffer kbb = readValue(input, ProtocolVersion.V3); ByteBuffer vbb = readValue(input, ProtocolVersion.V3); int comparison = keyType.compare(kbb, serializedKey); if (comparison == 0) return vbb; else if (comparison > 0) // since the map is in sorted order, we know we've gone too far and the element doesn't exist return null; } return null; } catch (BufferUnderflowException e) { throw new MarshalException("Not enough bytes to read a map"); } }
public void validateForNativeProtocol(ByteBuffer bytes, ProtocolVersion version) { try { ByteBuffer input = bytes.duplicate(); int n = readCollectionSize(input, version); for (int i = 0; i < n; i++) elements.validate(readValue(input, version)); if (input.hasRemaining()) throw new MarshalException("Unexpected extraneous bytes after set value"); } catch (BufferUnderflowException e) { throw new MarshalException("Not enough bytes to read a set"); } }
@Override C decodeInternal(ByteBuffer input) { if (input == null || input.remaining() == 0) return newInstance(0); try { ByteBuffer i = input.duplicate(); int size = readSize(i); C coll = newInstance(size); for (int pos = 0; pos < size; pos++) { ByteBuffer databb = readValue(i); coll.add(elementCodec.decode(databb)); } return coll; } catch (BufferUnderflowException e) { throw new InvalidTypeException("Not enough bytes to deserialize collection", e); } }
@Override Tuple decodeInternal(ByteBuffer input) { if (input == null) { return null; } ByteBuffer bytes = input.duplicate(); int numberOfValues = tupleType.fieldTypes.size(); List<Object> values = new ArrayList<>(tupleType.fieldTypes.size()); try { for (int i = 0; bytes.hasRemaining() && i < numberOfValues; i++) { int n = bytes.getInt(); ByteBuffer element = n < 0 ? null : readBytes(bytes, n); values.add(elementCodecs.get(i).decode(element)); } } catch (BufferUnderflowException | IllegalArgumentException e) { throw new InvalidTypeException("Not enough bytes top deserialize a tuple", e); } return new Tuple(tupleType, values); }
@Override Map<K, V> decodeInternal(ByteBuffer input) { if (input == null || input.remaining() == 0) { return new LinkedHashMap<>(); } try { ByteBuffer bytes = input.duplicate(); int n = readSize(bytes); Map<K, V> m = new LinkedHashMap<>(n); for (int i = 0; i < n; i++) { ByteBuffer kbb = readValue(bytes); ByteBuffer vbb = readValue(bytes); m.put(keyCodec.decode(kbb), valueCodec.decode(vbb)); } return m; } catch (BufferUnderflowException | IllegalArgumentException e) { throw new InvalidTypeException("Not enough bytes to deserialize a map", e); } }
@Override protected void readImpl() { _targetX = readD(); _targetY = readD(); _targetZ = readD(); _originX = readD(); _originY = readD(); _originZ = readD(); try { _moveMovement = readD(); // is 0 if cursor keys are used 1 if mouse is used } catch (BufferUnderflowException e) { // ignore for now if(Config.L2WALKER_PROTECTION) { L2PcInstance activeChar = getClient().getActiveChar(); activeChar.sendPacket(SystemMessageId.HACKING_TOOL); Util.handleIllegalPlayerAction(activeChar, "Player " + activeChar.getName() + " Tried to Use L2Walker And Got Kicked", IllegalPlayerAction.PUNISH_KICK); } } }
private void verifyPFB(ByteBuffer bb) throws FontFormatException { int pos = 0; while (true) { try { int segType = bb.getShort(pos) & 0xffff; if (segType == 0x8001 || segType == 0x8002) { bb.order(ByteOrder.LITTLE_ENDIAN); int segLen = bb.getInt(pos+2); bb.order(ByteOrder.BIG_ENDIAN); if (segLen <= 0) { throw new FontFormatException("bad segment length"); } pos += segLen+6; } else if (segType == 0x8003) { return; } else { throw new FontFormatException("bad pfb file"); } } catch (BufferUnderflowException bue) { throw new FontFormatException(bue.toString()); } catch (Exception e) { throw new FontFormatException(e.toString()); } } }
synchronized void send(ByteBuffer b) throws IOException { byte[] msgBytes = new byte[b.capacity()]; try { /** * position:相当于一个游标(cursor),记录我们从哪里开始写数据,从哪里开始读数据。 位置:下一个要被读或写的元素的索引,每次读写缓冲区数据时都会改变该值,为下次读写作准备 */ b.position(0); b.get(msgBytes); } catch (BufferUnderflowException be) { LOG.error("BufferUnderflowException ", be); return; } dout.writeInt(b.capacity()); dout.write(b.array()); dout.flush(); }
@Override public Handshakedata translateHandshake( ByteBuffer buf ) throws InvalidHandshakeException { HandshakeBuilder bui = translateHandshakeHttp( buf, role ); // the first drafts are lacking a protocol number which makes them difficult to distinguish. Sec-WebSocket-Key1 is typical for draft76 if( ( bui.hasFieldValue( "Sec-WebSocket-Key1" ) || role == Role.CLIENT ) && !bui.hasFieldValue( "Sec-WebSocket-Version" ) ) { byte[] key3 = new byte[ role == Role.SERVER ? 8 : 16 ]; try { buf.get( key3 ); } catch ( BufferUnderflowException e ) { throw new IncompleteHandshakeException( buf.capacity() + 16 ); } bui.setContent( key3 ); } return bui; }
private void putData(ByteBuffer input, ByteBuffer output) { int id = input.getInt(); int size = input.getInt(); byte[] entity = new byte[size]; try { input.get(entity); } catch (BufferUnderflowException bue) { } publish(id, entity); System.out.println("Bytes sent into the data server: "); /*ByteBuffer buf = ByteBuffer.wrap(entity); while (true) { try { System.out.println("" + buf.get() + " " + buf.get() + " " + buf.get() + " " + buf.get()); } catch (BufferUnderflowException bue) { break; } }*/ }
@Test public void byteArrayReadByteTest() throws IOException { // Mix positives and negatives to test sign preservation in readByte() byte[] bytes = new byte[] {-128, -127, -126, -1, 0, 1, 125, 126, 127}; try (RandomAccessObject obj = new RandomAccessObject.RandomAccessByteArrayObject(bytes)) { for (int x = 0; x < bytes.length; x++) { Assert.assertEquals(bytes[x], obj.readByte()); } try { obj.readByte(); Assert.fail("Should've thrown an IOException"); } catch (BufferUnderflowException expected) { } } }
@Test public void byteArrayReadUnsignedByteTest() throws IOException { // Test values above 127 to test unsigned-ness of readUnsignedByte() int[] ints = new int[] {255, 254, 253}; byte[] bytes = new byte[] {(byte) 0xff, (byte) 0xfe, (byte) 0xfd}; try (RandomAccessObject obj = new RandomAccessObject.RandomAccessByteArrayObject(bytes)) { for (int x = 0; x < bytes.length; x++) { Assert.assertEquals(ints[x], obj.readUnsignedByte()); } try { obj.readUnsignedByte(); Assert.fail("Should've thrown an IOException"); } catch (BufferUnderflowException expected) { } } }
@Test public void mmapReadIntTest() throws IOException { File tmpFile = storeInTempFile(new ByteArrayInputStream(BLOB)); try { RandomAccessObject obj = new RandomAccessObject.RandomAccessMmapObject(new RandomAccessFile(tmpFile, "r"), "r"); readIntTest(obj); try { obj.readInt(); Assert.fail("Should've thrown an BufferUnderflowException"); } catch (BufferUnderflowException expected) { } } finally { tmpFile.delete(); } }
public BitcoinPacketHeader(ByteBuffer in) throws ProtocolException, BufferUnderflowException { header = new byte[HEADER_LENGTH]; in.get(header, 0, header.length); int cursor = 0; // The command is a NULL terminated string, unless the command fills all twelve bytes // in which case the termination is implicit. for (; header[cursor] != 0 && cursor < COMMAND_LEN; cursor++) ; byte[] commandBytes = new byte[cursor]; System.arraycopy(header, 0, commandBytes, 0, cursor); command = Utils.toString(commandBytes, "US-ASCII"); cursor = COMMAND_LEN; size = (int) readUint32(header, cursor); cursor += 4; if (size > Message.MAX_SIZE || size < 0) throw new ProtocolException("Message size too large: " + size); // Old clients don't send the checksum. checksum = new byte[4]; // Note that the size read above includes the checksum bytes. System.arraycopy(header, cursor, checksum, 0, 4); cursor += 4; }
public static int a(ByteBuffer byteBuffer, h hVar) { try { return byteBuffer.getInt(); } catch (BufferUnderflowException e) { a(e.fillInStackTrace(), hVar, byteBuffer); if (hVar != null) { hVar.g = 10000; } return -1; } catch (BufferOverflowException e2) { a(e2.fillInStackTrace(), hVar, byteBuffer); if (hVar != null) { hVar.g = 10000; } return -1; } catch (Exception e3) { a(e3.fillInStackTrace(), hVar, byteBuffer); if (hVar != null) { hVar.g = 10000; } return -1; } }
public static ByteBuffer a(ByteBuffer byteBuffer, byte[] bArr, h hVar) { try { return byteBuffer.get(bArr); } catch (BufferUnderflowException e) { a(e.fillInStackTrace(), hVar, byteBuffer); if (hVar != null) { hVar.g = 10000; } return null; } catch (BufferOverflowException e2) { a(e2.fillInStackTrace(), hVar, byteBuffer); if (hVar != null) { hVar.g = 10000; } return null; } catch (Exception e3) { a(e3.fillInStackTrace(), hVar, byteBuffer); if (hVar != null) { hVar.g = 10000; } return null; } }
private static void expunge(Path p, KerberosTime currTime) throws IOException { Path p2 = Files.createTempFile(p.getParent(), "rcache", null); try (SeekableByteChannel oldChan = Files.newByteChannel(p); SeekableByteChannel newChan = createNoClose(p2)) { long timeLimit = currTime.getSeconds() - readHeader(oldChan); while (true) { try { AuthTime at = AuthTime.readFrom(oldChan); if (at.ctime > timeLimit) { ByteBuffer bb = ByteBuffer.wrap(at.encode(true)); newChan.write(bb); } } catch (BufferUnderflowException e) { break; } } } makeMine(p2); Files.move(p2, p, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); }
@Override public final byte readByte() throws IOException { try { return curBuf.get(); } catch (BufferUnderflowException e) { do { curBufIndex++; if (curBufIndex >= buffers.length) { throw new EOFException("read past EOF: " + this); } curBuf = buffers[curBufIndex]; curBuf.position(0); } while (!curBuf.hasRemaining()); return curBuf.get(); } catch (NullPointerException npe) { throw new AlreadyClosedException("Already closed: " + this); } }
@Override public final void readBytes(byte[] b, int offset, int len) throws IOException { try { curBuf.get(b, offset, len); } catch (BufferUnderflowException e) { int curAvail = curBuf.remaining(); while (len > curAvail) { curBuf.get(b, offset, curAvail); len -= curAvail; offset += curAvail; curBufIndex++; if (curBufIndex >= buffers.length) { throw new EOFException("read past EOF: " + this); } curBuf = buffers[curBufIndex]; curBuf.position(0); curAvail = curBuf.remaining(); } curBuf.get(b, offset, len); } catch (NullPointerException npe) { throw new AlreadyClosedException("Already closed: " + this); } }
/** * Returns the required number of bytes in the {@code source} * {@link ByteBuffer} necessary to explore SSL/TLS connection. * <P> * This method tries to parse as few bytes as possible from * {@code source} byte buffer to get the length of an * SSL/TLS record. * <P> * This method accesses the {@code source} parameter in read-only * mode, and does not update the buffer's properties such as capacity, * limit, position, and mark values. * * @param source * a {@link ByteBuffer} containing * inbound or outbound network data for an SSL/TLS connection. * @throws BufferUnderflowException if less than {@code RECORD_HEADER_SIZE} * bytes remaining in {@code source} * @return the required size in byte to explore an SSL/TLS connection */ public final static int getRequiredSize(ByteBuffer source) { ByteBuffer input = source.duplicate(); // Do we have a complete header? if (input.remaining() < RECORD_HEADER_SIZE) { throw new BufferUnderflowException(); } // Is it a handshake message? byte firstByte = input.get(); byte secondByte = input.get(); byte thirdByte = input.get(); if ((firstByte & 0x80) != 0 && thirdByte == 0x01) { // looks like a V2ClientHello // return (((firstByte & 0x7F) << 8) | (secondByte & 0xFF)) + 2; return RECORD_HEADER_SIZE; // Only need the header fields } else { return (((input.get() & 0xFF) << 8) | (input.get() & 0xFF)) + 5; } }
@OnMessage public void message(Session session, ByteBuffer buffer) throws IOException { int slot; try { slot = Byte.toUnsignedInt(buffer.get()); } catch(BufferUnderflowException bue) { session.close(new CloseReason(CloseReason.CloseCodes.PROTOCOL_ERROR, "Not enough data")); return; } removeViewer(); if(slot > 255 || (game = Game.getGame(slot)) == null) { session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, "Invalid slot ID")); return; } game.getDisplayHandler().addViewer(viewer); }
/** * parse a compressed DWORD (a variant length integer) */ public static long parseCWord(ByteBuffer bb) throws IOException { try { long accumulator = 0; byte temp = bb.get(); while (temp < 0) { // if the most significant bit is 1 accumulator <<= 7; accumulator += temp & 0x7f; temp = bb.get(); } return (accumulator << 7) + temp; } catch (BufferUnderflowException e) { throw new IOException(e); } }
@Override public void seekPastMagicBytes(ByteBuffer in) throws BufferUnderflowException { int magicCursor = 3; // Which byte of the magic we're looking for currently. while (true) { byte b = in.get(); // We're looking for a run of bytes that is the same as the packet magic but we want to ignore partial // magics that aren't complete. So we keep track of where we're up to with magicCursor. byte expectedByte = (byte)(0xFF & params.getPacketMagic() >>> (magicCursor * 8)); if (b == expectedByte) { magicCursor--; if (magicCursor < 0) { // We found the magic sequence. return; } else { // We still have further to go to find the next message. } } else { magicCursor = 3; } } }
private int nextTokenType(ByteBuffer bb) { try { byte b = skip(bb); while (true) { if (b == (byte)'/') { // PS defined name follows. return PSNAMETOKEN; } else if (b == (byte)'(') { // PS string follows return PSSTRINGTOKEN; } else if ((b == (byte)'\r') || (b == (byte)'\n')) { b = skip(bb); } else { b = bb.get(); } } } catch (BufferUnderflowException e) { return PSEOFTOKEN; } }
/** Parse the constant pool of the class * calling a method visit* each time a constant pool entry is parsed. * * The order of the calls to visit* is not guaranteed to be the same * than the order of the constant pool entry in the bytecode array. * * @param visitor * @throws InvalidConstantPoolFormatException */ public void parse(ConstantPoolVisitor visitor) throws InvalidConstantPoolFormatException { ByteBuffer buffer = ByteBuffer.wrap(classFile); buffer.position(getStartOffset()); //skip header Object[] values = new Object[getLength()]; try { parseConstantPool(buffer, values, visitor); } catch(BufferUnderflowException e) { throw new InvalidConstantPoolFormatException(e); } if (endOffset == 0) { endOffset = buffer.position(); secondHeader = new char[4]; for (int i = 0; i < secondHeader.length; i++) { secondHeader[i] = (char) getUnsignedShort(buffer); } } resolveConstantPool(values, visitor); }
private static TypeAnnotation parseTypeAnnotation(ByteBuffer buf, ConstantPool cp, AnnotatedElement baseDecl, Class<?> container) { try { TypeAnnotationTargetInfo ti = parseTargetInfo(buf); LocationInfo locationInfo = LocationInfo.parseLocationInfo(buf); Annotation a = AnnotationParser.parseAnnotation(buf, cp, container, false); if (ti == null) // Inside a method for example return null; return new TypeAnnotation(ti, locationInfo, a, baseDecl); } catch (IllegalArgumentException | // Bad type in const pool at specified index BufferUnderflowException e) { throw new AnnotationFormatError(e); } }
@Override public Handshakedata translateHandshake(ByteBuffer buf) throws InvalidHandshakeException { HandshakeBuilder bui = translateHandshakeHttp(buf, role); // the first drafts are lacking a protocol number which makes them difficult to distinguish. Sec-WebSocket-Key1 is typical for draft76 if ((bui.hasFieldValue("Sec-WebSocket-Key1") || role == Role.CLIENT) && !bui.hasFieldValue("Sec-WebSocket-Version")) { byte[] key3 = new byte[role == Role.SERVER ? 8 : 16]; try { buf.get(key3); } catch (BufferUnderflowException e) { throw new IncompleteHandshakeException(buf.capacity() + 16); } bui.setContent(key3); } return bui; }
private void authenticateMultiuser(PoolImpl pool, Connection conn, UserAttributes ua) { try { Long userId = (Long) AuthenticateUserOp.executeOn(conn.getServer(), pool, ua.getCredentials()); if (userId != null) { ua.setServerToId(conn.getServer(), userId); if (logger.isDebugEnabled()) { logger.debug("OpExecutorImpl.execute() - multiuser mode - authenticated this user on {}", conn); } } } catch (ServerConnectivityException sce) { Throwable cause = sce.getCause(); if (cause instanceof SocketException || cause instanceof EOFException || cause instanceof IOException || cause instanceof BufferUnderflowException || cause instanceof CancelException || (sce.getMessage() != null && (sce.getMessage().indexOf("Could not create a new connection to server") != -1 || sce.getMessage().indexOf("socket timed out on client") != -1 || sce.getMessage().indexOf("connection was asynchronously destroyed") != -1))) { throw new ServerConnectivityException("Connection error while authenticating user"); } else { throw sce; } } }
private static int csize(int p) throws Exception { try (SeekableByteChannel chan = Files.newByteChannel( Paths.get(dfl(p)), StandardOpenOption.READ)) { chan.position(6); int cc = 0; while (true) { try { if (AuthTime.readFrom(chan) != null) cc++; } catch (BufferUnderflowException e) { break; } } return cc; } catch (IOException ioe) { return 0; } }
public PauseConnectionFrame(final byte[] frame) throws IncorrectFrameException { final BinaryReader reader = new BinaryReader(frame); try { final byte remoteVersion = reader.getSignedByte(); final byte remoteType = reader.getSignedByte(); if (remoteVersion != VERSION) { throw new IncorrectFrameException("Incorrect version (" + remoteVersion + ", should be " + VERSION + ")"); } if (remoteType != TYPE.getValue()) { throw new IncorrectFrameException("Incorrect type (" + remoteType + ", should be " + TYPE + ")"); } connectionID = reader.getSignedShort(); } catch (final BufferUnderflowException e) { throw new IncorrectFrameException("Incorrect frame length"); } }
/** * Try to transfer date from InAppBB to ChannelLineBuffers.inputBuffer * If inputBuffer don't have enough free space inAppBB will have * *Return bytes cleared. * * @return */ private int clearInAppBB() { inAppBB.flip(); //ready for output int tmpSize =0; if (inAppBB.hasRemaining()){ ByteBuffer inputBuffer = lineBuffers.getInputBuffer(); //inAppBB.remaining() - 0 to limit for output, //inputBuffer.remaining() - post to limit(capasity) for input tmpSize = inAppBB.remaining() < inputBuffer.remaining() ? inAppBB.remaining() : inputBuffer.remaining(); //the lesser of two byte[] tmp = new byte[tmpSize]; try{ inAppBB.get(tmp);//may left something inputBuffer.put(tmp); }catch(BufferOverflowException|BufferUnderflowException ex){ Log.get().log(Level.SEVERE, ex.getLocalizedMessage(), ex); conn.close(); } inAppBB.compact(); //ready for in again }else inAppBB.clear(); return tmpSize; }
@Override public int getEncodedData(byte[] packetBuffer) throws BufferUnderflowException { if (!isReady()) { throw new BufferUnderflowException(); } int size = mEncodedLength; if (mTerminated) size |= 1 << 13; // Copy encoded data System.arraycopy(mBuffer, 0, packetBuffer, 0, mEncodedLength); mBufferedFrames = 0; mEncodedLength = 0; mTerminated = false; return size; }
private CloseableIterator<Record> uncompressedIterator() { final ByteBuffer buffer = this.buffer.duplicate(); buffer.position(RECORDS_OFFSET); return new RecordIterator() { @Override protected Record readNext(long baseOffset, long baseTimestamp, int baseSequence, Long logAppendTime) { try { return DefaultRecord.readFrom(buffer, baseOffset, baseTimestamp, baseSequence, logAppendTime); } catch (BufferUnderflowException e) { throw new InvalidRecordException("Incorrect declared batch size, premature EOF reached"); } } @Override protected boolean ensureNoneRemaining() { return !buffer.hasRemaining(); } @Override public void close() {} }; }