Java Code Examples for org.apache.mina.core.buffer.IoBuffer#hasArray()

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#hasArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Packet.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Setter for data
 *
 * @param buffer
 *            Packet data
 */
public void setData(IoBuffer buffer) {
    if (noCopy) {
        log.trace("Using buffer reference");
        this.data = buffer;
    } else {
        // try the backing array first if it exists
        if (buffer.hasArray()) {
            log.trace("Buffer has backing array, making a copy");
            byte[] copy = new byte[buffer.limit()];
            buffer.mark();
            buffer.get(copy);
            buffer.reset();
            data = IoBuffer.wrap(copy);
        } else {
            log.trace("Buffer has no backing array, using ByteBuffer");
            // fallback to ByteBuffer
            data.put(buffer.buf()).flip();
        }
    }
}
 
Example 2
Source File: Packet.java    From red5-websocket with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the packet which just wraps the IoBuffer.
 * 
 * @param buffer
 * @return packet
 */
public static Packet build(IoBuffer buffer) {
    if (buffer.hasArray()) {
        return new Packet(buffer.array());
    }
    byte[] buf = new byte[buffer.remaining()];
    buffer.get(buf);
    return new Packet(buf);
}
 
Example 3
Source File: TestRc4Filter.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception
{
	if (message instanceof IoBuffer)
	{
		IoBuffer ioBuf = (IoBuffer)message;
		if (ioBuf.hasArray())
			updateInput(ioBuf.array(), ioBuf.position(), ioBuf.remaining());
		else
			updateInput(ioBuf.buf(), ioBuf.position(), ioBuf.remaining());
	}
	nextFilter.messageReceived(message);
}
 
Example 4
Source File: TestRc4Filter.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception
{
	Object message = writeRequest.writeRequestMessage();
	if (message instanceof IoBuffer)
	{
		IoBuffer ioBuf = (IoBuffer)message;
		if (ioBuf.hasArray())
			updateOutput(ioBuf.array(), ioBuf.position(), ioBuf.remaining());
		else
			updateOutput(ioBuf.buf(), ioBuf.position(), ioBuf.remaining());
	}
	nextFilter.filterWrite(writeRequest);
}
 
Example 5
Source File: FLVWriter.java    From red5-io with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean writeTag(byte dataType, IoBuffer data) throws IOException {
    if (timeOffset == 0) {
        timeOffset = (int) System.currentTimeMillis();
    }
    try {
        lock.acquire();
        /*
         * Tag header = 11 bytes |-|---|----|---| 0 = type 1-3 = data size 4-7 = timestamp 8-10 = stream id (always 0) Tag data = variable bytes Previous tag = 4 bytes (tag header size +
         * tag data size)
         */
        if (log.isTraceEnabled()) {
            log.trace("writeTag - type: {} data: {}", dataType, data);
        }
        long prevBytesWritten = bytesWritten;
        log.trace("Previous bytes written: {}", prevBytesWritten);
        // skip tags with no data
        int bodySize = data.limit();
        log.debug("Tag body size: {}", bodySize);
        // ensure that the channel is still open
        if (dataChannel != null) {
            log.debug("Current file position: {}", dataChannel.position());
            // set a var holding the entire tag size including the previous tag length
            int totalTagSize = TAG_HEADER_LENGTH + bodySize + 4;
            // create a buffer for this tag
            ByteBuffer tagBuffer = ByteBuffer.allocate(totalTagSize);
            // Data Type
            IOUtils.writeUnsignedByte(tagBuffer, dataType); //1
            // Body Size - Length of the message. Number of bytes after StreamID to end of tag 
            // (Equal to length of the tag - 11) 
            IOUtils.writeMediumInt(tagBuffer, bodySize); //3
            // Timestamp
            int timestamp = (int) (System.currentTimeMillis() - timeOffset);
            IOUtils.writeExtendedMediumInt(tagBuffer, timestamp); //4
            // Stream id
            tagBuffer.put(DEFAULT_STREAM_ID); //3
            log.trace("Tag buffer (after tag header) limit: {} remaining: {}", tagBuffer.limit(), tagBuffer.remaining());
            // get the body if we have one
            if (data.hasArray()) {
                tagBuffer.put(data.array());
                log.trace("Tag buffer (after body) limit: {} remaining: {}", tagBuffer.limit(), tagBuffer.remaining());
            }
            // store new previous tag size
            lastTagSize = TAG_HEADER_LENGTH + bodySize;
            // we add the tag size
            tagBuffer.putInt(lastTagSize);
            log.trace("Tag buffer (after prev tag size) limit: {} remaining: {}", tagBuffer.limit(), tagBuffer.remaining());
            // flip so we can process from the beginning
            tagBuffer.flip();
            if (log.isDebugEnabled()) {
                //StringBuilder sb = new StringBuilder();
                //HexDump.dumpHex(sb, tagBuffer.array());
                //log.debug("\n{}", sb);
            }
            // write the tag
            dataChannel.write(tagBuffer);
            bytesWritten = dataChannel.position();
            if (log.isTraceEnabled()) {
                log.trace("Tag written, check value: {} (should be 0)", (bytesWritten - prevBytesWritten) - totalTagSize);
            }
            tagBuffer.clear();
            // update the duration
            duration = Math.max(duration, timestamp);
            log.debug("Writer duration: {}", duration);
            // validate written amount
            if ((bytesWritten - prevBytesWritten) != totalTagSize) {
                log.debug("Not all of the bytes appear to have been written, prev-current: {}", (bytesWritten - prevBytesWritten));
            }
            return true;
        } else {
            // throw an exception and let them know the cause
            throw new IOException("FLV write channel has been closed", new ClosedChannelException());
        }
    } catch (InterruptedException e) {
        log.warn("Exception acquiring lock", e);
    } finally {
        // update the file information
        updateInfoFile();
        // release lock
        lock.release();
    }
    return false;
}
 
Example 6
Source File: OutboundHandshake.java    From red5-client with Apache License 2.0 4 votes vote down vote up
/**
 * Decodes the second server response (S2).
 * <pre>
 * S2 = Copy of C1 bytes
 * </pre>
 * @param in incoming handshake S2
 * @return true if validation passes and false otherwise
 */
public boolean decodeServerResponse2(IoBuffer in) {
    log.debug("decodeServerResponse2");
    // the handshake type byte is not included
    byte[] s2;
    if (in.hasArray()) {
        s2 = in.array();
    } else {
        s2 = new byte[Constants.HANDSHAKE_SIZE];
        in.get(s2);
    }
    //if (log.isTraceEnabled()) {
    //    log.trace("S2: {}", Hex.encodeHexString(s2));
    //}
    if (fp9Handshake) {
        if (s2[4] == 0 && s2[5] == 0 && s2[6] == 0 && s2[7] == 0) {
            log.warn("Server refused signed authentication");
        }
        // validate server response part 2, not really required for client
        byte[] signature = new byte[DIGEST_LENGTH];
        byte[] digest = new byte[DIGEST_LENGTH];
        calculateHMAC_SHA256(c1, digestPosClient, DIGEST_LENGTH, GENUINE_FMS_KEY, GENUINE_FMS_KEY.length, digest, 0);
        calculateHMAC_SHA256(s2, 0, Constants.HANDSHAKE_SIZE - DIGEST_LENGTH, digest, DIGEST_LENGTH, signature, 0);
        log.debug("Digest key: {}", Hex.encodeHexString(digest));
        // FP10 stuff
        if (handshakeType == RTMPConnection.RTMP_ENCRYPTED_XTEA) {
            log.debug("RTMPE type 8 XTEA");
            // encrypt signatureResp
            for (int i = 0; i < DIGEST_LENGTH; i += 8) {
                //encryptXtea(signature, i, digest[i] % 15);
            }
        } else if (handshakeType == RTMPConnection.RTMP_ENCRYPTED_BLOWFISH) {
            log.debug("RTMPE type 9 Blowfish");
            // encrypt signatureResp
            for (int i = 0; i < DIGEST_LENGTH; i += 8) {
                //encryptBlowfish(signature, i, digest[i] % 15);
            }
        }
        log.debug("Signature calculated: {}", Hex.encodeHexString(signature));
        log.debug("Server sent signature: {}", Hex.encodeHexString(s2));
        if (!Arrays.equals(signature, Arrays.copyOfRange(s2, (Constants.HANDSHAKE_SIZE - DIGEST_LENGTH), (Constants.HANDSHAKE_SIZE - DIGEST_LENGTH) + DIGEST_LENGTH))) {
            log.info("Server not genuine");
            return false;
        } else {
            log.debug("Compatible flash server");
        }
    } else {
        if (!Arrays.equals(s2, c1)) {
            log.info("Client signature doesn't match!");
        }
    }
    return true;
}