Exemplo n.º 1
0
void 
Mesh::vertices(BufferPtr theVertices, int theVertexSize) {
    _myNumberOfVertices = theVertices->size() / theVertexSize;
    _myVertexSize = theVertexSize;
    _myVertices = theVertices;
    theVertices->rewind();
}
Exemplo n.º 2
0
	void VolumeHeader::EncryptNew (const BufferPtr &newHeaderBuffer, const ConstBufferPtr &newSalt, const ConstBufferPtr &newHeaderKey, shared_ptr <Pkcs5Kdf> newPkcs5Kdf)
	{
		if (newHeaderBuffer.Size() != HeaderSize || newSalt.Size() != SaltSize)
			throw ParameterIncorrect (SRC_POS);

		shared_ptr <EncryptionMode> mode = EA->GetMode()->GetNew();
		shared_ptr <EncryptionAlgorithm> ea = EA->GetNew();

		if (typeid (*mode) == typeid (EncryptionModeXTS))
		{
			mode->SetKey (newHeaderKey.GetRange (EA->GetKeySize(), EA->GetKeySize()));
			ea->SetKey (newHeaderKey.GetRange (0, ea->GetKeySize()));
		}
		else
		{
			mode->SetKey (newHeaderKey.GetRange (0, mode->GetKeySize()));
			ea->SetKey (newHeaderKey.GetRange (LegacyEncryptionModeKeyAreaSize, ea->GetKeySize()));
		}

		ea->SetMode (mode);

		newHeaderBuffer.CopyFrom (newSalt);

		BufferPtr headerData = newHeaderBuffer.GetRange (EncryptedHeaderDataOffset, EncryptedHeaderDataSize);
		Serialize (headerData);
		ea->Encrypt (headerData);

		if (newPkcs5Kdf)
			Pkcs5 = newPkcs5Kdf;
	}
Exemplo n.º 3
0
void 
Mesh::textureCoords(int theLevel, BufferPtr theTextureCoords, int theTextureCoordSize) {
    _myNumberOfVertices = theTextureCoords->size() / theTextureCoordSize;
    _myTextureCoordSize[theLevel] = theTextureCoordSize;
    _myTextureCoords[theLevel] = theTextureCoords;
    theTextureCoords->rewind();
}
DLLEXPORT double buffer_clear(double handle) {
    BufferPtr buffer = handles.find<Buffer> (handle);
    if (buffer) {
        buffer->clear();
    }
    return 0;
}
DLLEXPORT double udp_send(double handle, const char *host, double port) {
    uint16_t intPort;
    try {
        intPort = numeric_cast<uint16_t> (port);
    } catch (bad_numeric_cast &e) {
        intPort = 0;
    }

    if (intPort == 0) {
        return false;
    }

    BufferPtr buffer = handles.find<Buffer> (handle);
    if(buffer) {
        if(!defaultUdpSocket) {
            defaultUdpSocket = UdpSocket::bind(0);
        }
        defaultUdpSocket->write(buffer->getData(), buffer->size());
        defaultUdpSocket->send(host, intPort);
        return true;
    }

    boost::shared_ptr<UdpSocket> sock = handles.find<UdpSocket>(handle);
    if(sock) {
        return sock->send(host, intPort);
    }
    return false;
}
Exemplo n.º 6
0
 // Read a text file as a std::string, throw error if file is binary
 inline std::string read_text(const std::string& filename, const boost::uint64_t max_size = 0)
 {
   BufferPtr bp = read_binary(filename, max_size);
   if (bp->contains_null())
     OPENVPN_THROW(file_is_binary, "file is binary: " << filename);
   return std::string((const char *)bp->c_data(), bp->size());
 }
Exemplo n.º 7
0
  // Read a file (may be text or binary).
  inline BufferPtr read_binary(const std::string& filename,
			       const boost::uint64_t max_size = 0,
			       const unsigned int buffer_flags = 0)
  {
    std::ifstream ifs(filename.c_str(), std::ios::binary);
    if (!ifs)
      OPENVPN_THROW(open_file_error, "cannot open: " << filename);

    // get length of file
    ifs.seekg (0, std::ios::end);
    const std::streamsize length = ifs.tellg();
    if (max_size && boost::uint64_t(length) > max_size)
      OPENVPN_THROW(file_too_large, "file too large [" << length << '/' << max_size << "]: " << filename);
    ifs.seekg (0, std::ios::beg);

    // allocate buffer
    BufferPtr b = new BufferAllocated(size_t(length), buffer_flags | BufferAllocated::ARRAY);

    // read data
    ifs.read((char *)b->data(), length);

    // check for errors
    if (ifs.gcount() != length)
      OPENVPN_THROW(open_file_error, "read length inconsistency: " << filename);
    if (!ifs)
      OPENVPN_THROW(open_file_error, "cannot read: " << filename);

    return b;
  }
orc::Buffer *HdfsInputStream::read(uint64_t offset, uint64_t length, orc::Buffer *buffer)
{
    if(!configured_) {
        throw std::runtime_error("Need to configure first");
    }
    if (buffer == NULL) {
        buffer = new HeapBuffer(length);
    } else if (buffer->getLength() < length) {
        delete buffer;
        buffer = new HeapBuffer(length);
    }

    //blockreader::BlockPtr block = hdfsBlockReader_.getBlock(offset, length);

    hdfsutils::HdfsBlockLocator locator;
    base::ConfigurationMap conf;
    conf["filename"] = url_;
    conf["hdfsConfigurationFile"] = hdfsConfigurationFile_;
    conf["fileStatCache"] = fileStatCache_;
    locator.configure(conf);
    BufferPtr block = locator.getBlock(offset, length);
    if(block->size() != length) {
        throw std::runtime_error("size mismatch");
    }
    // TODO get rid of this copy
    memcpy(buffer->getStart(), block->data(), block->size());
    return buffer;
}
Exemplo n.º 9
0
bool
Block::fromBuffer(const uint8_t* buffer, size_t maxSize, Block& block)
{
  const uint8_t* tempBegin = buffer;
  const uint8_t* tempEnd = buffer + maxSize;

  uint32_t type = 0;
  bool isOk = Tlv::readType(tempBegin, tempEnd, type);
  if (!isOk)
    return false;

  uint64_t length;
  isOk = Tlv::readVarNumber(tempBegin, tempEnd, length);
  if (!isOk)
    return false;

  if (length > static_cast<uint64_t>(tempEnd - tempBegin))
    {
      return false;
    }

  BufferPtr sharedBuffer = make_shared<Buffer>(buffer, tempBegin + length);
  block = Block(sharedBuffer, type,
                sharedBuffer->begin(), sharedBuffer->end(),
                sharedBuffer->begin() + (tempBegin - buffer), sharedBuffer->end());

  return true;
}
Exemplo n.º 10
0
Block 
SecTpmMemory::signInTpm(const uint8_t *data, size_t dataLength,
                const Name& keyName,
                DigestAlgorithm digestAlgorithm)
{
  if (digestAlgorithm != DIGEST_ALGORITHM_SHA256)
    return ConstBufferPtr();

  // Find the private key and sign.
  PrivateKeyStore::iterator privateKey = privateKeyStore_.find(keyName.toUri());
  if (privateKey == privateKeyStore_.end())
    throw Error(string("MemoryPrivateKeyStorage: Cannot find private key ") + keyName.toUri());
  
  uint8_t digest[SHA256_DIGEST_LENGTH];
  SHA256_CTX sha256;
  SHA256_Init(&sha256);
  SHA256_Update(&sha256, data, dataLength);
  SHA256_Final(digest, &sha256);

  BufferPtr signatureBuffer = ptr_lib::make_shared<Buffer>();
  signatureBuffer->resize(RSA_size(privateKey->second->getPrivateKey()));
  
  unsigned int signatureBitsLength;  
  if (!RSA_sign(NID_sha256, digest, sizeof(digest),
                signatureBuffer->buf(),
                &signatureBitsLength,
                privateKey->second->getPrivateKey()))
    {
      throw Error("Error in RSA_sign");
    }

  return Block(Tlv::SignatureValue, signatureBuffer);
}
Exemplo n.º 11
0
void TcpConnection::RealSend(const BufferPtr& buffer)
{
    send_buf_.push_back(buffer);

    socket_.Send(std::bind(&TcpConnection::OnWrite, shared_from_this(),
        std::placeholders::_1, std::placeholders::_2), &(*buffer->begin()), buffer->size());
}
Exemplo n.º 12
0
std::tuple<bool, Block>
Block::fromBuffer(const uint8_t* buffer, size_t maxSize)
{
  const uint8_t* tempBegin = buffer;
  const uint8_t* tempEnd = buffer + maxSize;

  uint32_t type = 0;
  bool isOk = tlv::readType(tempBegin, tempEnd, type);
  if (!isOk)
    return std::make_tuple(false, Block());

  uint64_t length;
  isOk = tlv::readVarNumber(tempBegin, tempEnd, length);
  if (!isOk)
    return std::make_tuple(false, Block());

  if (length > static_cast<uint64_t>(tempEnd - tempBegin))
    return std::make_tuple(false, Block());

  BufferPtr sharedBuffer = make_shared<Buffer>(buffer, tempBegin + length);
  return std::make_tuple(true,
         Block(sharedBuffer, type,
               sharedBuffer->begin(), sharedBuffer->end(),
               sharedBuffer->begin() + (tempBegin - buffer), sharedBuffer->end()));
}
DLLEXPORT double buffer_size(double handle) {
    BufferPtr buffer = handles.find<Buffer> (handle);
    if (buffer) {
        return buffer->size();
    } else {
        return 0;
    }
}
Exemplo n.º 14
0
	void MeshSubsetGL3::initializeIndexArray(BufferPtr indexBuffer, IndexFormat::Enum indexFormat) {
		assert(this);

		BufferPtr buffer = std::move(indexBuffer);

		this->indexBuffer.reset(static_cast<BufferGL3*>(buffer.release()));
		this->indexFormat = indexFormat;
	}
Exemplo n.º 15
0
BufferPtr
serializeMsg(const Msg& msg)
{
  int size = msg.ByteSize();
  BufferPtr bytes = std::make_shared<Buffer>(size);
  msg.SerializeToArray(bytes->buf(), size);
  return bytes;
}
Exemplo n.º 16
0
	void VolumeHeader::SerializeEntry (const T &entry, const BufferPtr &header, size_t &offset) const
	{
		offset += sizeof (T);

		if (offset > header.Size())
			throw ParameterIncorrect (SRC_POS);

		*reinterpret_cast<T *> (header.Get() + offset - sizeof (T)) = Endian::Big (entry);
	}
Exemplo n.º 17
0
ObjectDataICommand ObjectDataOCommand::_getCommand( LocalNodePtr node )
{
    lunchbox::Bufferb& outBuffer = getBuffer();
    uint8_t* bytes = outBuffer.getData();
    reinterpret_cast< uint64_t* >( bytes )[ 0 ] = outBuffer.getSize();

    BufferPtr inBuffer = node->allocBuffer( outBuffer.getSize( ));
    inBuffer->swap( outBuffer );
    return ObjectDataICommand( node, node, inBuffer, false );
}
Exemplo n.º 18
0
ConstBufferPtr
Digest<Hash>::computeDigest(const uint8_t* buffer, size_t size)
{
  Hash hash;
  BufferPtr result = make_shared<Buffer>(hash.DigestSize());
  hash.Update(buffer, size);
  hash.Final(result->get());

  return result;
}
Exemplo n.º 19
0
uint64 File::ReadAt (const BufferPtr &buffer, uint64 position) const
{
    if_debug (ValidateState());

#ifdef TC_TRACE_FILE_OPERATIONS
    TraceFileOperation (FileHandle, Path, false, buffer.Size(), position);
#endif
    ssize_t bytesRead = pread (FileHandle, buffer, buffer.Size(), position);
    throw_sys_sub_if (bytesRead == -1, wstring (Path));

    return bytesRead;
}
Exemplo n.º 20
0
	void Socket::IOControl(DWORD dwIoControlCode, const BufferPtr &inBuffer, const BufferPtr &outBuffer)
	{
		DWORD bytesReturned;

		if (0 != WSAIoctl(hSocket, dwIoControlCode, inBuffer->Pointer(), inBuffer->Size(),
			outBuffer->Pointer(), outBuffer->Size(), &bytesReturned, 0, 0))
		{
			throw Win32Exception("WSAIoCtl");
		}

		outBuffer->Resize(bytesReturned);
	}
Exemplo n.º 21
0
size_t Stream::write(BufferPtr buffer)
{
	if(!buffer)
	{
#ifdef AEON_USE_AEON_CONSOLE_LIBRARY
		Console::error("Stream: Tried writing an empty buffer to a stream.");
#endif

		return 0;
	}

	return write(buffer->get(), buffer->size());
}
Exemplo n.º 22
0
BufferPtr BufferCache::alloc( const uint64_t size )
{
    LB_TS_SCOPED( _thread );
    LBASSERTINFO( size >= COMMAND_ALLOCSIZE, size );
    LBASSERTINFO( size < LB_BIT48,
                  "Out-of-sync network stream: buffer size " << size << "?" );

    BufferPtr buffer = _impl->newBuffer();
    LBASSERT( buffer->getRefCount() == 1 );

    buffer->reserve( size );
    buffer->resize( 0 );
    return buffer;
}
Exemplo n.º 23
0
//----------------------------------------------------------------------
// read
//----------------------------------------------------------------------
void Connection::recvNB( BufferPtr buffer, const uint64_t bytes )
{
    LBASSERT( !_impl->buffer );
    LBASSERT( _impl->bytes == 0 );
    LBASSERT( buffer );
    LBASSERT( bytes > 0 );
    LBASSERTINFO( bytes < LB_BIT48,
                  "Out-of-sync network stream: read size " << bytes << "?" );

    _impl->buffer = buffer;
    _impl->bytes = bytes;
    buffer->reserve( buffer->getSize() + bytes );
    readNB( buffer->getData() + buffer->getSize(), bytes );
}
Exemplo n.º 24
0
OCommand::~OCommand()
{
    if( _impl->isLocked )
    {
        LBASSERT( _impl->size > 0 );
        const uint64_t size = _impl->size + getBuffer().getSize();
        const size_t minSize = Buffer::getMinSize();
        const Connections& connections = getConnections();
        if( size < minSize ) // Fill send to minimal size
        {
            const size_t delta = minSize - size;
            void* padding = alloca( delta );
            for( ConnectionsCIter i = connections.begin();
                 i != connections.end(); ++i )
            {
                ConnectionPtr connection = *i;
                connection->send( padding, delta, true );
            }
        }
        for( ConnectionsCIter i = connections.begin();
             i != connections.end(); ++i )
        {
            ConnectionPtr connection = *i;
            connection->unlockSend();
        }
        _impl->isLocked = false;
        _impl->size = 0;
        reset();
    }
    else
        disable();

    if( _impl->dispatcher )
    {
        LBASSERT( _impl->localNode );

        // #145 proper local command dispatch?
        LBASSERT( _impl->size == 0 );
        const uint64_t size = getBuffer().getSize();
        BufferPtr buffer = _impl->localNode->allocBuffer( size );
        buffer->swap( getBuffer( ));
        reinterpret_cast< uint64_t* >( buffer->getData( ))[ 0 ] = size;

        ICommand cmd( _impl->localNode, _impl->localNode, buffer, false );
        _impl->dispatcher->dispatchCommand( cmd );
    }

    delete _impl;
}
Exemplo n.º 25
0
bool Player::PreBuffer(){
    // But not if buffer is full
    if(this->totalBufferSize>this->maxBufferSize){
        return false;
    }else{
        BufferPtr newBuffer = this->stream->NextBuffer();
        if(newBuffer){
            boost::mutex::scoped_lock lock(this->mutex);
            this->bufferQueue.push_back(newBuffer);
            this->totalBufferSize += newBuffer->Bytes();
            this->waitCondition.notify_all();
        }
        return true;
    }
}
Exemplo n.º 26
0
void encoderCallback(void *enc, uint8_t *buf, int32_t bufSize, uint16_t frameType)
{
	QEncoder *encoder = (QEncoder*)enc;

	/* Store data in the output buffer. */
	BufferPtr output = encoder->pool.getBuffer(bufSize+1);
	unsigned char* outputPtr = output->getPointer();
	outputPtr[0] = (frameType == 1 ? 1 : 0);
	memcpy(outputPtr + 1, buf, bufSize);
	
	/* Put the data on the output queue. */
	encoder->queue.add(output);

	interpreterProxy->signalSemaphoreWithIndex(encoder->semaIndex);
}
Exemplo n.º 27
0
	void File::ReadCompleteBuffer (const BufferPtr &buffer) const
	{
		size_t dataLeft = buffer.Size();
		size_t offset = 0;

		while (dataLeft > 0)
		{
			size_t dataRead = static_cast <size_t> (Read (buffer.GetRange (offset, dataLeft)));
			if (dataRead == 0)
				throw InsufficientData (SRC_POS);

			dataLeft -= dataRead;
			offset += dataRead;
		}
	}
Exemplo n.º 28
0
	Error operator()(CommandBufferImpl* cmd)
	{
		TextureImpl& tex = m_tex.get();
		BufferImpl& buff = m_buff.get();

		// Bind
		GLuint copyFbo = cmd->getManager().getImplementation().
			getRenderingThread().getCopyFbo();
		glBindFramebuffer(GL_FRAMEBUFFER, copyFbo);

		// Attach texture
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
			tex.getTarget(), tex.getGlName(), 0);

		// Set draw buffers
		GLuint drawBuff = GL_COLOR_ATTACHMENT0;
		glDrawBuffers(1, &drawBuff);

		// Bind buffer
		ANKI_ASSERT(m_buff.getTarget() == GL_PIXEL_PACK_BUFFER);
		buff.bind();

		// Read pixels
		GLuint format = GL_NONE, type = GL_NONE;
		if(tex.getInternalFormat() == GL_RG32UI)
		{
			format = GL_RG_INTEGER;
			type = GL_UNSIGNED_INT;
		}
		else if(tex.getInternalFormat() == GL_RG32F)
		{
			format = GL_RG;
			type = GL_FLOAT;
		}
		else
		{
			ANKI_ASSERT(0 && "Not implemented");
		}

		glReadPixels(0, 0, tex.getWidth(), tex.getHeight(),
			format, type, nullptr);

		// End
		buff.unbind();
		glBindFramebuffer(GL_FRAMEBUFFER, 0);

		return ErrorCode::NONE;
	}
Exemplo n.º 29
0
	void VolumeHeader::Create (const BufferPtr &headerBuffer, VolumeHeaderCreationOptions &options)
	{
		if (options.DataKey.Size() != options.EA->GetKeySize() * 2 || options.Salt.Size() != GetSaltSize())
			throw ParameterIncorrect (SRC_POS);

		headerBuffer.Zero();

		HeaderVersion = CurrentHeaderVersion;
		RequiredMinProgramVersion = CurrentRequiredMinProgramVersion;

		DataAreaKey.Zero();
		DataAreaKey.CopyFrom (options.DataKey);

		VolumeCreationTime = 0;
		HiddenVolumeDataSize = (options.Type == VolumeType::Hidden ? options.VolumeDataSize : 0);
		VolumeDataSize = options.VolumeDataSize;

		EncryptedAreaStart = options.VolumeDataStart;
		EncryptedAreaLength = options.VolumeDataSize;

		SectorSize = options.SectorSize;

		if (SectorSize < TC_MIN_VOLUME_SECTOR_SIZE
			|| SectorSize > TC_MAX_VOLUME_SECTOR_SIZE
			|| SectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0)
		{
			throw ParameterIncorrect (SRC_POS);
		}

		EA = options.EA;
		shared_ptr <EncryptionMode> mode (new EncryptionModeXTS ());
		EA->SetMode (mode);

		EncryptNew (headerBuffer, options.Salt, options.HeaderKey, options.Kdf);
	}
Exemplo n.º 30
0
void OnReceive(const AsyncResultPtr &asyncResult)
{
	try {
		SocketPtr acceptSocket = asyncResult->asyncState;
		BufferPtr buffer = asyncResult->buffer;
		size_t size = acceptSocket->EndReceive(asyncResult);
		if (size != 0) {
			buffer->Resize(size);
			acceptSocket->BeginSend(buffer);
			acceptSocket->BeginReceive(BufferPtr(8192, NoRebindTag()), &OnReceive, acceptSocket);
		} else {
			acceptSocket->BeginDisconnect();
		}
	} catch (const std::exception &) {
	}
}