Пример #1
0
 void clear()
 {
     mInByteBuffer = ByteBuffer();
     mOutByteBuffer = ByteBuffer();
     mInByteBufferPos = 0;
     mBytesTransferred = 0;
 }
Пример #2
0
TEST(ByteBufferTests, LittleEndianSets) {
    ByteBuffer buf(10);
    EXPECT_EQ(buf.size(), 10);

    buf.set_le16(4, 0x1234);
    EXPECT_EQ(buf[4], 0x34);
    EXPECT_EQ(buf[5], 0x12);

    buf = ByteBuffer(10);
    buf.set_le32(3, 0x12345678);
    EXPECT_EQ(buf[3], 0x78);
    EXPECT_EQ(buf[4], 0x56);
    EXPECT_EQ(buf[5], 0x34);
    EXPECT_EQ(buf[6], 0x12);

    buf = ByteBuffer(10);
    buf.set_le48(2, 0x123456789ABC);
    EXPECT_EQ(buf[2], 0xBC);
    EXPECT_EQ(buf[3], 0x9A);
    EXPECT_EQ(buf[4], 0x78);
    EXPECT_EQ(buf[5], 0x56);
    EXPECT_EQ(buf[6], 0x34);
    EXPECT_EQ(buf[7], 0x12);

    buf = ByteBuffer(10);
    buf.set_le64(2, 0x0123456789ABCDEF);
    EXPECT_EQ(buf[2], 0xEF);
    EXPECT_EQ(buf[3], 0xCD);
    EXPECT_EQ(buf[4], 0xAB);
    EXPECT_EQ(buf[5], 0x89);
    EXPECT_EQ(buf[6], 0x67);
    EXPECT_EQ(buf[7], 0x45);
    EXPECT_EQ(buf[8], 0x23);
    EXPECT_EQ(buf[9], 0x01);
}
ByteBuffer AsioSessionState::getReadByteBuffer()
{
    if (!mAppReadBufferPtr)
    {
        return ByteBuffer();
    }
    return ByteBuffer(mAppReadBufferPtr);
}
ByteBuffer ChannelsBufferClass::getValueAsByteArray(unsigned short id){
	//If CFG file was loaded
	if (channelsConfig.isValid()){
		//Search the channel
		int index = channelsConfig.getChannelIndex(id);
		//Return a copy 
		if (index != -1){
			ByteBuffer& b = buffer[index];
			return ByteBuffer(b.data(), b.getSize());
		}
	}
	return ByteBuffer();
}
Пример #5
0
    void createNonReadOnlyByteBuffers(
        std::vector<ByteBuffer> &nonReadOnlyByteBuffers,
        const std::vector<ByteBuffer> &byteBuffers)
    {
        nonReadOnlyByteBuffers.resize(0);
        for (std::size_t i=0; i<byteBuffers.size(); ++i)
        {
            if (byteBuffers[i].getLength()  > 0)
            {
                if (byteBuffers[i].getReadOnly())
                {
                    boost::shared_ptr< std::vector<char> > spvc(
                        new std::vector<char>( byteBuffers[i].getLength()));

                    memcpy(
                        &(*spvc)[0],
                        byteBuffers[i].getPtr(),
                        byteBuffers[i].getLength() );

                    nonReadOnlyByteBuffers.push_back(
                        ByteBuffer(&(*spvc)[0], spvc->size(), spvc));
                }
                else
                {
                    nonReadOnlyByteBuffers.push_back(byteBuffers[i]);
                }
            }
        }
    }
Пример #6
0
ByteBuffer ByteBufferUtils::makeBuffer(uint8_t d0,
                                       uint8_t d1,
                                       uint8_t d2)
{
    uint8_t bytes[] = { d0, d1, d2 };
    return ByteBuffer(bytes, 3);
}
Пример #7
0
    bool unfilterData(
        const ByteBuffer &filteredByteBuffer,
        ByteBuffer &unfilteredByteBuffer,
        std::size_t unfilteredDataLen,
        const std::vector<FilterPtr> &filters)
    {
        ThreadLocalCached< std::vector<ByteBuffer> > tlcUnfilteredByteBuffers;
        std::vector<ByteBuffer> &unfilteredByteBuffers = tlcUnfilteredByteBuffers.get();

        bool ret = unfilterData(
            filteredByteBuffer,
            unfilteredByteBuffers,
            unfilteredDataLen,
            filters);

        if (unfilteredByteBuffers.empty())
        {
            unfilteredByteBuffer = ByteBuffer();
        }
        else if (unfilteredByteBuffers.size() == 1)
        {
            unfilteredByteBuffer = unfilteredByteBuffers[0];
        }
        else
        {
            // TODO: maybe check for adjacent buffers, in which case one should not need to make a copy
            copyByteBuffers(unfilteredByteBuffers, unfilteredByteBuffer);
        }
        return ret;
    }
Пример #8
0
HashResult BCryptHashImpl::Calculate(Aws::IStream& stream)
{
    if(!IsValid())
    {
        return HashResult();
    }

    std::lock_guard<std::mutex> locker(m_algorithmMutex);

    auto startingPos = stream.tellg();

    bool success = HashStream(stream);
    if(success)
    {
        stream.clear();
    }

    stream.seekg(startingPos, stream.beg);

    if(!success)
    {
        return HashResult();
    }

    return HashResult(ByteBuffer(m_hashBuffer, m_hashBufferLength));
}
Пример #9
0
    void ClientStub::flushBatch(unsigned int timeoutMs)
    {
        CurrentClientStubSentry sentry(*this);

        if (timeoutMs == 0)
        {
            timeoutMs = getRemoteCallTimeoutMs();
        }

        try
        {
            std::vector<ByteBuffer> buffers;
            buffers.push_back( ByteBuffer(mBatchBufferPtr) );
            int err = getTransport().send(*this, buffers, timeoutMs);
            RCF_UNUSED_VARIABLE(err);

            mBatchBufferPtr->resize(0);

            ++mBatchCount;
            mBatchMessageCount = 0;
        }
        catch(const RemoteException & e)
        {
            RCF_UNUSED_VARIABLE(e);
            mEncodedByteBuffers.resize(0);
            throw;
        }
        catch(...)
        {
            mEncodedByteBuffers.resize(0);
            disconnect();
            throw;
        }
    }
    void AsioSessionState::read(
        const ByteBuffer &byteBuffer,
        std::size_t bytesRequested)
    {

        RCF2_TRACE("")(this);

        if (byteBuffer.getLength() == 0)
        {
            std::vector<char> &vec = getUniqueReadBufferSecondary();
            vec.resize(bytesRequested);
            mTempByteBuffer = getReadByteBufferSecondary();
        }
        else
        {
            mTempByteBuffer = ByteBuffer(byteBuffer, 0, bytesRequested);
        }

        RCF_ASSERT(
            bytesRequested <= mTempByteBuffer.getLength())
            (bytesRequested)(mTempByteBuffer.getLength());

        char *buffer = mTempByteBuffer.getPtr();
        std::size_t bufferLen = mTempByteBuffer.getLength();

        Lock lock(mMutex);
        if (!mHasBeenClosed)
        {
            implRead(buffer, bufferLen);
        }
    }
 ByteBuffer AsioSessionState::getReadByteBuffer()
 {
     return ByteBuffer(
         &(*mReadBufferPtr)[0],
         (*mReadBufferPtr).size(),
         mReadBufferPtr);
 }
Пример #12
0
    void HttpSessionFilter::write(const std::vector<ByteBuffer> &byteBuffers)
    {
        // If we write the response directly to network here, we ar at risk of a race
        // condition as the next request may be read in on another connection, before
        // the write completion on this connection has executed.

        // So instead we make a copy of the write buffers, and send a write completion
        // back up. The subsequent read operation will unhook the HTTP session and then 
        // write the response to the network.

        if ( mNetworkSession.mCloseAfterWrite )
        {
            // Special case, if this is the last message being written before the connection closes.
            mpPostFilter->write(byteBuffers);
        }
        else
        {
            std::size_t len = lengthByteBuffers(byteBuffers);
            ReallocBufferPtr bufferPtr = getObjectPool().getReallocBufferPtr();
            bufferPtr->resize(len);
            copyByteBuffers(byteBuffers, bufferPtr->getPtr());
            mWriteBuffers.resize(0);
            mWriteBuffers.push_back(ByteBuffer(bufferPtr));

            mpPreFilter->onWriteCompleted(len);
        }
    }
Пример #13
0
    bool unfilterData(
        const ByteBuffer &filteredByteBuffer,
        std::vector<ByteBuffer> &unfilteredByteBuffers,
        std::size_t unfilteredDataLen,
        const std::vector<FilterPtr> &filters)
    {
        int error                           = 0;
        std::size_t bytesTransferred        = 0;
        std::size_t bytesTransferredTotal   = 0;

        ByteBuffer byteBuffer;
        unfilteredByteBuffers.resize(0);

        ReadProxy readProxy;
        readProxy.setInByteBuffer(filteredByteBuffer);
        readProxy.setPreFilter(*filters.back());
        filters.back()->setPostFilter(readProxy);
        filters.front()->setPreFilter(readProxy);

        while (!error && bytesTransferredTotal < unfilteredDataLen)
        {
            filters.front()->read(ByteBuffer(), unfilteredDataLen - bytesTransferredTotal);
            bytesTransferred = readProxy.getOutBytesTransferred();
            byteBuffer = readProxy.getOutByteBuffer();
            // TODO: error handling
            bytesTransferredTotal += (error) ? 0 : bytesTransferred;
            unfilteredByteBuffers.push_back(byteBuffer);
        }
        return bytesTransferredTotal == unfilteredDataLen;
    }
void AsioSessionState::beginRead()
{
    RCF_ASSERT(
        mReadBufferRemaining == 0
        ||  (mAppReadBufferPtr && mAppReadBufferPtr->size() >= mReadBufferRemaining));

    mAppReadByteBuffer = ByteBuffer();
    if (mAppReadBufferPtr)
    {
        char * pch = & (*mAppReadBufferPtr)[mAppReadBufferPtr->size() - mReadBufferRemaining];
        mAppReadByteBuffer = ByteBuffer(pch, mReadBufferRemaining, mAppReadBufferPtr);
    }

    mTransportFilters.empty() ?
    read(mAppReadByteBuffer, mReadBufferRemaining) :
    mTransportFilters.front()->read(mAppReadByteBuffer, mReadBufferRemaining);
}
Пример #15
0
std::size_t URIEncoding::decode(const ByteBuffer& buffer,
                                ByteBuffer& decodedBuffer)
{
    std::string decoded;
    Poco::URI::decode(buffer.toString(), decoded);
    decodedBuffer = ByteBuffer(decoded);
    return decodedBuffer.size();
}
Пример #16
0
ByteBuffer ByteBufferUtils::makeBuffer(uint8_t d0,
                                       uint8_t d1,
                                       uint8_t d2,
                                       uint8_t d3)
{
    uint8_t bytes[] = { d0, d1, d2, d3 };
    return ByteBuffer(bytes, 4);
}
 ByteBuffer UdpSessionState::getReadByteBuffer()
 {
     return ByteBuffer(
         &(*mReadVecPtr)[0] + 4,
         mReadVecPtr->size() - 4,
         4,
         mReadVecPtr);
 }
 ByteBuffer 
     AsioSessionState::getReadByteBufferSecondary() const
 {
     return ByteBuffer(
         &(*mReadBufferSecondaryPtr)[0],
         (*mReadBufferSecondaryPtr).size(),
         mReadBufferSecondaryPtr);
 }
 ByteBuffer UdpSessionState::getReadByteBuffer()
 {
     return ByteBuffer(
         &mReadVecPtr->front() + 4,
         mReadVecPtr->size() - 4,
         4,
         mReadVecPtr);
 }
Пример #20
0
 void operator()(const CohesivePacket& packet)
 {
     m_duplicate.reset(new ChunkPacket());
     for (auto layer : osi_layers) {
         const auto range = packet[layer];
         m_duplicate->layer(layer) = ByteBuffer(range.begin(), range.end());
     }
 }
Пример #21
0
std::size_t URIEncoding::encode(const ByteBuffer& buffer,
                                ByteBuffer& encodedBuffer)
{
    std::string encoded;
    Poco::URI::encode(buffer.toString(), "", encoded);
    encodedBuffer = ByteBuffer(encoded);
    return encodedBuffer.size();
}
Пример #22
0
 void operator()(const CohesivePacket& packet)
 {
     m_duplicate.reset(new ChunkPacket());
     for (auto layer : osi_layers) {
         const auto source = packet[layer];
         auto& dest = m_duplicate->layer(layer);
         dest = ByteBuffer(source.begin(), source.end());
     }
 }
Пример #23
0
ByteBuffer ByteBufferUtils::makeBuffer(uint8_t d0,
                                       uint8_t d1,
                                       uint8_t d2,
                                       uint8_t d3,
                                       uint8_t d4)
{
    uint8_t bytes[] = { d0, d1, d2, d3, d4 };
    return ByteBuffer(bytes, 5);
}
void AsioSessionState::onNetworkReadCompleted(
    AsioErrorCode error, size_t bytesTransferred)
{
    RCF_LOG_4()(this)(bytesTransferred) << "AsioSessionState - read from socket completed.";

    ThreadTouchGuard threadTouchGuard;

    mLastError = error;

    mBytesReceivedCounter += bytesTransferred;

#ifdef BOOST_WINDOWS

    if (error.value() == ERROR_OPERATION_ABORTED)
    {
        error = AsioErrorCode();
    }

#endif

    if (!error && !mTransport.mStopFlag)
    {
        if (bytesTransferred == 0 && mIssueZeroByteRead)
        {
            // TCP framing.
            if (!mAppReadBufferPtr || !mAppReadBufferPtr.unique())
            {
                mAppReadBufferPtr = getObjectPool().getReallocBufferPtr();
            }
            mAppReadBufferPtr->resize(4);

            mReadBufferRemaining = 4;
            mIssueZeroByteRead = false;
            beginRead();
        }
        else if (mReflecting)
        {
            AsioErrorCode ec;
            onReflectedReadWriteCompleted(ec, bytesTransferred);
        }
        else
        {
            CurrentRcfSessionSentry guard(*mSessionPtr);

            mNetworkReadByteBuffer = ByteBuffer(
                                         mNetworkReadByteBuffer,
                                         0,
                                         bytesTransferred);

            mTransportFilters.empty() ?
            onAppReadWriteCompleted(bytesTransferred) :
            mTransportFilters.back()->onReadCompleted(mNetworkReadByteBuffer);
        }
    }
}
Пример #25
0
    void onRtfCompleted(
        RCF::Future<Void>                           fv, 
        RcfClientPtr                                rtfClientPtr,
        ClientStub &                                clientStubOrig,
        boost::shared_ptr<std::vector<FilterPtr> >  filters, 
        boost::function0<void>                      onCompletion)
    {
        ClientStubPtr rtfStubPtr = rtfClientPtr->getClientStubPtr();
        clientStubOrig.setTransport( rtfStubPtr->releaseTransport() );
        clientStubOrig.setSubRcfClientPtr( RcfClientPtr() );

        std::auto_ptr<Exception> ePtr = fv.getAsyncException();
        if ( ePtr.get() )
        {
            clientStubOrig.setAsyncException(ePtr);
        }
        else
        {
            // Get OOB response.
            OobRequestTransportFilters msg(clientStubOrig.getRuntimeVersion());
            ByteBuffer controlResponse = rtfStubPtr->getOutOfBandResponse();
            rtfStubPtr->setOutofBandRequest(ByteBuffer());
            rtfStubPtr->setOutofBandResponse(ByteBuffer());
            msg.decodeResponse(controlResponse);

            int ret = msg.mResponseError; 
            if (ret != RcfError_Ok)
            {
                ePtr.reset( new RemoteException(Error(ret)) );
                clientStubOrig.setAsyncException(ePtr);
            }
            else
            {
                for (std::size_t i=0; i<filters->size(); ++i)
                {
                    (*filters)[i]->resetState();
                }
                clientStubOrig.getTransport().setTransportFilters(*filters);
            }
        }
        onCompletion();
    }
Пример #26
0
void NetInterface::sendPunchPackets(NetConnection *conn)
{
   ConnectionParameters &theParams = conn->getConnectionParameters();
   PacketStream out;
   out.write(U8(Punch));

   if(theParams.mIsInitiator)
      theParams.mNonce.write(&out);
   else
      theParams.mServerNonce.write(&out);

   U32 encryptPos = out.getBytePosition();
   out.setBytePosition(encryptPos);

   if(theParams.mIsInitiator)
      theParams.mServerNonce.write(&out);
   else
   {
      theParams.mNonce.write(&out);
      if(out.writeFlag(mRequiresKeyExchange || (theParams.mRequestKeyExchange && !mPrivateKey.isNull())))
      {
         if(out.writeFlag(theParams.mRequestCertificate && !mCertificate.isNull()))
            out.write(mCertificate);
         else
            out.write(mPrivateKey->getPublicKey());
      }
   }
   SymmetricCipher theCipher(theParams.mArrangedSecret);
   out.hashAndEncrypt(NetConnection::MessageSignatureBytes, encryptPos, &theCipher);

   for(S32 i = 0; i < theParams.mPossibleAddresses.size(); i++)
   {
      out.sendto(mSocket, theParams.mPossibleAddresses[i]);

      TNLLogMessageV(LogNetInterface, ("Sending punch packet (%s, %s) to %s",
         ByteBuffer(theParams.mNonce.data, Nonce::NonceSize).encodeBase64()->getBuffer(),
         ByteBuffer(theParams.mServerNonce.data, Nonce::NonceSize).encodeBase64()->getBuffer(),
         theParams.mPossibleAddresses[i].toString()));
   }
   conn->mConnectSendCount++;
   conn->mConnectLastSendTime = getCurrentTime();
}
    void AsioSessionState::invokeAsyncRead()
    {
        RCF2_TRACE("")(this);

        mReadByteBuffer = ByteBuffer(
            getReadByteBuffer(),
            getReadByteBuffer().getLength()-mReadBufferRemaining);

        mTransportFilters.empty() ?
            read(mReadByteBuffer, mReadBufferRemaining) :
            mTransportFilters.front()->read(mReadByteBuffer, mReadBufferRemaining);
    }
Пример #28
0
    void copyByteBuffers(
        const std::vector<ByteBuffer> &byteBuffers,
        ByteBuffer &byteBuffer)
    {
        boost::shared_ptr<std::vector<char> > vecPtr(
            new std::vector<char>(lengthByteBuffers(byteBuffers)));

        copyByteBuffers(byteBuffers, &(*vecPtr)[0]);
        byteBuffer = ByteBuffer(
            &(*vecPtr)[0],
            (*vecPtr).size(),
            vecPtr);
    }
Пример #29
0
    void SubscriptionService::doRequestSubscriptionAsync_Complete(
        Future<Void>                    fv,
        RcfClientPtr                    requestClientPtr,
        const std::string &             publisherName,
        RcfClientPtr                    rcfClientPtr,
        OnSubscriptionDisconnect        onDisconnect,
        OnAsyncSubscribeCompleted       onCompletion)
    {
        bool pingsEnabled = true;

        boost::uint32_t ret = 0;
        boost::uint32_t pubToSubPingIntervalMs = 0;

        ExceptionPtr ePtr( fv.getAsyncException().release() );
        if (!ePtr)
        {
            // Get OOB response.
            ClientStub & stub = requestClientPtr->getClientStub();
            OobRequestSubscription msg(stub.getRuntimeVersion());
            ByteBuffer controlResponse = stub.getOutOfBandResponse();
            stub.setOutofBandRequest(ByteBuffer());
            stub.setOutofBandResponse(ByteBuffer());
            msg.decodeResponse(controlResponse);

            ret = msg.mResponseError; 
            pubToSubPingIntervalMs = msg.mPubToSubPingIntervalMs;
        }

        createSubscriptionImplEnd(
            ePtr, 
            requestClientPtr->getClientStubPtr(), 
            ret, 
            publisherName, 
            rcfClientPtr, 
            onDisconnect, 
            onCompletion, 
            pubToSubPingIntervalMs, 
            pingsEnabled);
    }
Пример #30
0
    void ClientStub::requestTransportFilters(const std::vector<FilterPtr> &filters)
    {
        if (getRuntimeVersion() <= 11)
        {
            requestTransportFilters_Legacy(filters);
            return;
        }

        ClientStub stub(*this);
        stub.setTransport( releaseTransport());
        stub.setTargetToken( Token());

        RestoreClientTransportGuard guard(*this, stub);

        // Set OOB request.
        OobRequestTransportFilters msg(getRuntimeVersion(), filters);
        ByteBuffer controlRequest;
        msg.encodeRequest(controlRequest);
        stub.setOutofBandRequest(controlRequest);

        stub.ping(RCF::Twoway);

        // Get OOB response.
        ByteBuffer controlResponse = stub.getOutOfBandResponse();
        stub.setOutofBandRequest(ByteBuffer());
        stub.setOutofBandResponse(ByteBuffer());
        msg.decodeResponse(controlResponse);

        int ret = msg.mResponseError; 
        RCF_VERIFY(ret == RcfError_Ok, RemoteException( Error(ret) ));

        for (std::size_t i=0; i<filters.size(); ++i)
        {
            filters[i]->resetState();
        }

        stub.getTransport().setTransportFilters(filters);
    }