Example #1
0
bool Router::Send( char *data, BitSize_t bitLength, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddressList *recipients )
{
	RakAssert(data);
	RakAssert(bitLength);
	if (recipients->GetList()->Size()==0)
		return false;
	if (bitLength==0)
		return false;
	DataStructures::Tree<ConnectionGraph::SystemAddressAndGroupId> tree;
	SystemAddress root;
	root = rakPeerInterface->GetExternalID(rakPeerInterface->GetSystemAddressFromIndex(0));
	if (root==UNASSIGNED_SYSTEM_ADDRESS)
		return false;
	DataStructures::List<ConnectionGraph::SystemAddressAndGroupId> recipientList;
	unsigned i;
	for (i=0; i < recipients->Size(); i++)
		recipientList.Insert(ConnectionGraph::SystemAddressAndGroupId(recipients->GetList()->operator [](i),0, UNASSIGNED_RAKNET_GUID), __FILE__, __LINE__);
	if (graph->GetSpanningTree(tree, &recipientList, ConnectionGraph::SystemAddressAndGroupId(root,0,UNASSIGNED_RAKNET_GUID), 65535)==false)
		return false;

	RakNet::BitStream out;

	// Write timestamp first, if the user had a timestamp
	if (data[0]==ID_TIMESTAMP && bitLength >= BYTES_TO_BITS(sizeof(MessageID)+sizeof(RakNetTime)))
	{
		out.Write(data, sizeof(MessageID)+sizeof(RakNetTime));
		data+=sizeof(MessageID)+sizeof(RakNetTime);
		bitLength-=BYTES_TO_BITS(sizeof(MessageID)+sizeof(RakNetTime));
	}

	SendTree(priority, reliability, orderingChannel, &tree, data, bitLength, &out, recipients);
	return true;
}
Example #2
0
// Keeps a record of the last 20 calls, to give a faster response to traffic change
void LogStats(){
	const int numStats = 20;
	static myStat data[numStats];

	for(int i=0; i<=numStats-2; i++){
		data[i] = data[i+1];
	}

	RakNet::RakNetStatistics *rss=rakPeer->GetStatistics(rakPeer->GetSystemAddressFromIndex(0));
	unsigned int currTime = RakNet::GetTimeMS();

	data[numStats-1].time = currTime;
	data[numStats-1].bitsSent = BYTES_TO_BITS(rss->runningTotal[RakNet::USER_MESSAGE_BYTES_SENT]);
	data[numStats-1].bitsRec = BYTES_TO_BITS(rss->runningTotal[RakNet::USER_MESSAGE_BYTES_RECEIVED_PROCESSED]);

	float totalTime = (data[numStats-1].time - data[0].time) / 1000.f ;
	unsigned int totalBitsSent = data[numStats-1].bitsSent - data[0].bitsSent;
	unsigned int totalBitsRec = data[numStats-1].bitsRec - data[0].bitsRec;
	float bpsSent = totalBitsSent/totalTime;
	float bpsRec = totalBitsRec/totalTime;
	float avgBpsSent = rss->valueOverLastSecond[RakNet::USER_MESSAGE_BYTES_SENT];
	float avgBpsRec = rss->valueOverLastSecond[RakNet::USER_MESSAGE_BYTES_RECEIVED_PROCESSED];

	printf("avgKbpsSent=%02.1f avgKbpsRec=%02.1f kbpsSent=%02.1f kbpsRec=%02.1f    \r", avgBpsSent/1000, avgBpsRec/1000, bpsSent/1000 , bpsRec/1000, rakVoice.GetBufferedBytesToReturn(RakNet::UNASSIGNED_RAKNET_GUID));
	//printf("MsgBuf=%6i SndBuf=%10i RcvBuf=%10i    \r", rakVoice.GetRakPeerInterface()->GetStatistics(RakNet::UNASSIGNED_SYSTEM_ADDRESS)->messageSendBuffer[HIGH_PRIORITY], rakVoice.GetBufferedBytesToSend(RakNet::UNASSIGNED_SYSTEM_ADDRESS), rakVoice.GetBufferedBytesToReturn(RakNet::UNASSIGNED_SYSTEM_ADDRESS));
}
Example #3
0
/**
 * @brief allocate space for a pbs_bitmap (and possibly the bitmap itself)
 * @param pbm - bitmap to allocate space for.  NULL to allocate a new bitmap
 * @param num_bits - number of bits to allocate
 * @return pbs_bitmap *
 * @retval bitmap which was allocated
 * @retval NULL on error
 */
pbs_bitmap *
pbs_bitmap_alloc(pbs_bitmap *pbm, long num_bits)
{
	pbs_bitmap *bm;
	unsigned long *tmp_bits;
	long prev_longs;
	
	if(num_bits <= 0)
		return NULL;
	
	if(pbm == NULL) {
		bm = calloc(1, sizeof(pbs_bitmap));
		if(bm == NULL)
			return NULL;
	}
	else 
		bm = pbm;
	
	/* shrinking bitmap, clear previously used bits */
	if (num_bits < bm->num_bits) {
		int i;
		i = num_bits / BYTES_TO_BITS(sizeof(unsigned long)) + 1;
		for ( ; i < bm->num_longs; i++)
			bm->bits[i] = 0;
		for (i = pbs_bitmap_next_on_bit(bm, num_bits); i != -1; i = pbs_bitmap_next_on_bit(bm, i))
			pbs_bitmap_bit_off(bm, i);
	}

	/* If we have enough unused bits available, we don't need to allocate */
	if (bm->num_longs * BYTES_TO_BITS(sizeof(unsigned long)) >= num_bits) {
		bm->num_bits = num_bits;
		return bm;
	}
		
		
	prev_longs = bm->num_longs;
	
	bm->num_bits = num_bits;
	bm->num_longs = num_bits / BYTES_TO_BITS(sizeof(unsigned long));
	if (num_bits % BYTES_TO_BITS(sizeof(unsigned long)) > 0)
		bm->num_longs++;
	tmp_bits = calloc(bm->num_longs, sizeof(unsigned long));
	if (tmp_bits == NULL) {
		if(pbm == NULL) /* we allocated the memory */
			pbs_bitmap_free(bm);
		return NULL;
	}
	
	if(bm->bits != NULL) {
		int i;
		for(i = 0; i < prev_longs; i++)
			tmp_bits[i] = bm->bits[i];
		
		free(bm->bits);
	}
	bm->bits = tmp_bits;
		
	return bm;
}
Example #4
0
void BitStream::Write( BitStream *bitStream, BitSize_t numberOfBits )
{
	AddBitsAndReallocate( numberOfBits );
	BitSize_t numberOfBitsMod8;

	if ((bitStream->GetReadOffset()&7)==0 && (numberOfBitsUsed&7)==0)
	{
		int readOffsetBytes=bitStream->GetReadOffset()/8;
		int numBytes=numberOfBits/8;
		memcpy(data + (numberOfBitsUsed >> 3), bitStream->GetData()+readOffsetBytes, numBytes);
		numberOfBits-=BYTES_TO_BITS(numBytes);
		bitStream->SetReadOffset(BYTES_TO_BITS(numBytes+readOffsetBytes));
		numberOfBitsUsed+=BYTES_TO_BITS(numBytes);
	}
Example #5
0
/**
 * @brief pbs_bitmap version of L = R
 * @param L - bitmap lvalue
 * @param R - bitmap rvalue
 * @return int
 * @retval 1 success
 * @retval 0 failure
 */
int
pbs_bitmap_assign(pbs_bitmap *L, pbs_bitmap *R)
{
	int i;
	
	if (L == NULL || R == NULL)
		return 0;
	
	/* In the case where R is longer than L, we need to allocate more space for L
	 * Instead of using R->num_bits, we call pbs_bitmap_alloc() with the 
	 * full number of bits required for its num_longs.  This is because it
	 * is possible that R has more space allocated to it than required for its num_bits.
	 * This happens if it had a previous call to pbs_bitmap_equals() with a shorter bitmap.
	 */
	if (R->num_longs > L->num_longs)
		if(pbs_bitmap_alloc(L, BYTES_TO_BITS(R->num_longs * sizeof(unsigned long))) == NULL)
			return 0;
	
	for (i = 0; i < R->num_longs; i++)
		L->bits[i] = R->bits[i];
	if (R->num_longs < L->num_longs)
		for(; i < L->num_longs; i++)
			L->bits[i] = 0;
	
	L->num_bits = R->num_bits;
	return 1;
}
Example #6
0
size_t bt_btr_continue(struct bt_btr *btr,
	const uint8_t *buf, size_t sz,
	enum bt_btr_status *status)
{
	assert(btr);
	assert(buf);
	assert(sz > 0);
	btr->buf.addr = buf;
	btr->buf.offset = 0;
	btr->buf.at = 0;
	btr->buf.buf_sz = sz;
	btr->buf.sz = BYTES_TO_BITS(sz);
	*status = BT_BTR_STATUS_OK;

	BT_LOGV("Continuing decoding: btr-addr=%p, buf-addr=%p, buf-size=%zu",
		btr, buf, sz);

	/* Continue running the machine */
	BT_LOGV_STR("Running the state machine.");

	while (true) {
		*status = handle_state(btr);
		if (*status != BT_BTR_STATUS_OK ||
				btr->state == BTR_STATE_DONE) {
			break;
		}
	}

	/* Update packet offset for next time */
	update_packet_offset(btr);
	return btr->buf.at;
}
Example #7
0
/**
 * @brief get the value of a bit
 * @param pbm - the bitmap
 * @param bit - which bit to get the value of
 * @return int
 * @retval 1 if the bit is on
 * @retval 0 if the bit is off
 */
int
pbs_bitmap_get_bit(pbs_bitmap *pbm, unsigned long bit)
{
	long long_ind;
	unsigned long b;
	
	if (pbm == NULL)
		return 0;
	
	if (bit >= pbm->num_bits)
		return 0;
	
	long_ind = bit / BYTES_TO_BITS(sizeof(unsigned long));
	b = 1UL << (bit % BYTES_TO_BITS(sizeof(unsigned long)));
	
	return (pbm->bits[long_ind] & b) ? 1 : 0;
}
Example #8
0
// Write an array or casted stream
void BitStream::Write( const char* inputByteArray, const unsigned int numberOfBytes )
{
	if (numberOfBytes==0)
		return;

	// Optimization:
	if ((numberOfBitsUsed & 7) == 0)
	{
		AddBitsAndReallocate( BYTES_TO_BITS(numberOfBytes) );
		memcpy(data+BITS_TO_BYTES(numberOfBitsUsed), inputByteArray, (size_t) numberOfBytes);
		numberOfBitsUsed+=BYTES_TO_BITS(numberOfBytes);
	}
	else
	{
		WriteBits( ( unsigned char* ) inputByteArray, numberOfBytes * 8, true );
	}

}
Example #9
0
/**
 * @brief turn a bit off for a bitmap
 * @param pbm - the bitmap
 * @param bit - the bit to turn off
 * @return nothing
 */
int
pbs_bitmap_bit_off(pbs_bitmap *pbm, long bit)
{
	long long_ind;
	unsigned long b;
	
	if (pbm == NULL)
		return 0;
	
	if (bit >= pbm->num_bits) {
		if(pbs_bitmap_alloc(pbm, bit + 1) == NULL)
			return 0;
	}
	
	long_ind = bit / BYTES_TO_BITS(sizeof(unsigned long));
	b = 1UL << (bit % BYTES_TO_BITS(sizeof(unsigned long)));
	
	pbm->bits[long_ind] &= ~b;
	return 1;
}
Example #10
0
Packet* TCPInterface::AllocatePacket(unsigned dataSize)
{
    Packet*p = RakNet::OP_NEW<Packet>(__FILE__,__LINE__);
    p->data=(unsigned char*) rakMalloc_Ex(dataSize,__FILE__,__LINE__);
    p->length=dataSize;
    p->bitSize=BYTES_TO_BITS(dataSize);
    p->deleteData=false;
    p->guid=UNASSIGNED_RAKNET_GUID;
    p->systemAddress=UNASSIGNED_SYSTEM_ADDRESS;
    p->systemAddress.systemIndex=(SystemIndex)-1;
    return p;
}
bool TableSerializer::DeserializeCell(RakNet::BitStream *in, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType)
{
	bool isEmpty;
	double value;
	void *ptr;
	char tempString[65535];
	cell->Clear();

	if (in->Read(isEmpty)==false)
		return false;
	if (isEmpty==false)
	{
		if (columnType==DataStructures::Table::NUMERIC)
		{
			if (in->Read(value)==false)
				return false;
			cell->Set(value);
		}
		else if (columnType==DataStructures::Table::STRING)
		{
			if (stringCompressor->DecodeString(tempString, 65535, in)==false)
				return false;
			cell->Set(tempString);
		}
		else if (columnType==DataStructures::Table::POINTER)
		{
			if (in->Read(ptr)==false)
				return false;
			cell->SetPtr(ptr);
		}
		else
		{
			unsigned binaryLength;
			// Binary
			RakAssert(columnType==DataStructures::Table::BINARY);
			if (in->Read(binaryLength)==false || binaryLength > 10000000)
				return false; // Sanity check to max binary cell of 10 megabytes
			in->AlignReadToByteBoundary();
			if (BITS_TO_BYTES(in->GetNumberOfUnreadBits())<(BitSize_t)binaryLength)
				return false;
			cell->Set((char*) in->GetData()+BITS_TO_BYTES(in->GetReadOffset()), (int) binaryLength);
			in->IgnoreBits(BYTES_TO_BITS((int) binaryLength));
		}
	}
	return true;
}
Example #12
0
/**
 * @brief starting at a bit, get the next on bit
 * @param pbm - the bitmap
 * @param start_bit - which bit to start from
 * @return int
 * @retval number of next on bit
 * @retval -1 if there isn't a next on bit
 */
int
pbs_bitmap_next_on_bit(pbs_bitmap *pbm, long start_bit)
{
	long long_ind;
	long bit;
	int i;
	
	if (pbm == NULL)
		return -1;
	
	if (start_bit >= pbm->num_bits)
		return -1;
	
	long_ind = start_bit / BYTES_TO_BITS(sizeof(unsigned long));
	bit = start_bit % BYTES_TO_BITS(sizeof(unsigned long));

	/* special case - look at first long that contains start_bit */
	if (pbm->bits[long_ind] != 0) {
		for (i = bit + 1; i < BYTES_TO_BITS(sizeof(unsigned long)); i++) {
			if (pbm->bits[long_ind] & (1UL << i)) {
				return (long_ind * BYTES_TO_BITS(sizeof(unsigned long)) + i);
			}
		}

		/* didn't find an on bit after start_bit_index in the long that contained start_bit */
		if (long_ind < pbm->num_longs) {
			long_ind++;
		}
	}

	for( ; long_ind < pbm->num_longs && pbm->bits[long_ind] == 0; long_ind++)
		;

	if (long_ind == pbm->num_longs)
		return -1;

	for (i = 0 ; i < BYTES_TO_BITS(sizeof(unsigned long)) ; i++) {
		if (pbm->bits[long_ind] & (1UL << i)) {
			return (long_ind * BYTES_TO_BITS(sizeof(unsigned long)) + i);
		}
	}

	return -1;
}
bool FileListTransfer::DecodeFile(Packet *packet, bool fullFile)
{
	FileListTransferCBInterface::OnFileStruct onFileStruct;
	RakNet::BitStream inBitStream(packet->data, packet->length, false);
	inBitStream.IgnoreBits(8);

	unsigned int partCount=0;
	unsigned int partTotal=0;
	unsigned int partLength=0;
	onFileStruct.fileData=0;
	if (fullFile==false)
	{
		// Disable endian swapping on reading this, as it's generated locally in ReliabilityLayer.cpp
		inBitStream.ReadBits( (unsigned char* ) &partCount, BYTES_TO_BITS(sizeof(partCount)), true );
		inBitStream.ReadBits( (unsigned char* ) &partTotal, BYTES_TO_BITS(sizeof(partTotal)), true );
		inBitStream.ReadBits( (unsigned char* ) &partLength, BYTES_TO_BITS(sizeof(partLength)), true );
		inBitStream.IgnoreBits(8);
		// The header is appended to every chunk, which we continue to read after this statement block
	}
	inBitStream.Read(onFileStruct.context);
	inBitStream.Read(onFileStruct.setID);
	FileListReceiver *fileListReceiver;
	if (fileListReceivers.Has(onFileStruct.setID)==false)
	{
		return false;
	}
	fileListReceiver=fileListReceivers.Get(onFileStruct.setID);
	if (fileListReceiver->allowedSender!=packet->systemAddress)
	{
#ifdef _DEBUG
		RakAssert(0);
#endif
		return false;
	}

#ifdef _DEBUG
	RakAssert(fileListReceiver->gotSetHeader==true);
#endif

	if (stringCompressor->DecodeString(onFileStruct.fileName, 512, &inBitStream)==false)
	{
#ifdef _DEBUG
		RakAssert(0);
#endif
		return false;
	}

	inBitStream.ReadCompressed(onFileStruct.fileIndex);
	inBitStream.ReadCompressed(onFileStruct.finalDataLength);

	// Read header uncompressed so the data is byte aligned, for speed
	onFileStruct.compressedTransmissionLength=(unsigned int) onFileStruct.finalDataLength;

	if (fullFile)
	{
		// Support SendLists
		inBitStream.AlignReadToByteBoundary();

		onFileStruct.fileData = (char*) rakMalloc_Ex( (size_t) onFileStruct.finalDataLength, __FILE__, __LINE__ );

		inBitStream.Read((char*)onFileStruct.fileData, onFileStruct.finalDataLength);
	}
	

	onFileStruct.setCount=fileListReceiver->setCount;
	onFileStruct.setTotalCompressedTransmissionLength=fileListReceiver->setTotalCompressedTransmissionLength;
	onFileStruct.setTotalFinalLength=fileListReceiver->setTotalFinalLength;

	// User callback for this file.
	if (fullFile)
	{
		if (fileListReceiver->downloadHandler->OnFile(&onFileStruct))
			rakFree_Ex(onFileStruct.fileData, __FILE__, __LINE__ );

		fileListReceiver->filesReceived++;

		// If this set is done, free the memory for it.
		if ((int) fileListReceiver->setCount==fileListReceiver->filesReceived)
		{
			if (fileListReceiver->downloadHandler->OnDownloadComplete()==false)
			{
				fileListReceiver->downloadHandler->OnDereference();
				if (fileListReceiver->deleteDownloadHandler)
					RakNet::OP_DELETE(fileListReceiver->downloadHandler, __FILE__, __LINE__);
				fileListReceivers.Delete(onFileStruct.setID);
				RakNet::OP_DELETE(fileListReceiver, __FILE__, __LINE__);
			}
		}

	}
	else
	{
		inBitStream.AlignReadToByteBoundary();

		bool usedAlloca=false;
		char *firstDataChunk;
		unsigned int unreadBits = inBitStream.GetNumberOfUnreadBits();
		unsigned int unreadBytes = BITS_TO_BYTES(unreadBits);
		if (unreadBytes>0)
		{
#if !defined(_XBOX) && !defined(_X360)
			if (unreadBits < MAX_ALLOCA_STACK_ALLOCATION)
			{
				firstDataChunk = ( char* ) alloca( unreadBytes );
				usedAlloca=true;
			}
			else
#endif
				firstDataChunk = (char*) rakMalloc_Ex( unreadBytes, __FILE__, __LINE__ );

			// Read partLength bytes, reported to OnFileProgress

			inBitStream.Read((char*)firstDataChunk, unreadBytes );

		}
		else
			firstDataChunk=0;

		fileListReceiver->downloadHandler->OnFileProgress(&onFileStruct, partCount, partTotal, unreadBytes, firstDataChunk);

		if (usedAlloca==false)
			RakNet::OP_DELETE_ARRAY(firstDataChunk, __FILE__, __LINE__);
	}

	return true;
}
Example #14
0
Packet* PacketizedTCP::Receive( void )
{
	PushNotificationsToQueues();

	unsigned int i;
	for (i=0; i < messageHandlerList.Size(); i++)
		messageHandlerList[i]->Update();

	Packet *outgoingPacket=ReturnOutgoingPacket();
	if (outgoingPacket)
		return outgoingPacket;

	Packet *incomingPacket;
	incomingPacket = TCPInterface::Receive();
	unsigned int index;

	while (incomingPacket)
	{
		if (connections.Has(incomingPacket->systemAddress))
			index = connections.GetIndexAtKey(incomingPacket->systemAddress);
		else
			index=(unsigned int) -1;
		if ((unsigned int)index==(unsigned int)-1)
		{
			DeallocatePacket(incomingPacket);
			incomingPacket = TCPInterface::Receive();
			continue;
		}


		if (incomingPacket->deleteData==true)
		{
			// Came from network
			SystemAddress systemAddressFromPacket;
			if (index < connections.Size())
			{
				DataStructures::ByteQueue *bq = connections[index];
				// Buffer data
				bq->WriteBytes((const char*) incomingPacket->data,incomingPacket->length, __FILE__,__LINE__);
				systemAddressFromPacket=incomingPacket->systemAddress;
				PTCPHeader dataLength;

				// Peek the header to see if a full message is waiting
				bq->ReadBytes((char*) &dataLength,sizeof(PTCPHeader),true);
				if (RakNet::BitStream::DoEndianSwap())
					RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &dataLength,sizeof(dataLength));
				// Header indicates packet length. If enough data is available, read out and return one packet
				if (bq->GetBytesWritten()>=dataLength+sizeof(PTCPHeader))
				{
					do 
					{
						bq->IncrementReadOffset(sizeof(PTCPHeader));
						outgoingPacket = RakNet::OP_NEW<Packet>(__FILE__, __LINE__);
						outgoingPacket->length=dataLength;
						outgoingPacket->bitSize=BYTES_TO_BITS(dataLength);
						outgoingPacket->guid=UNASSIGNED_RAKNET_GUID;
						outgoingPacket->systemAddress=systemAddressFromPacket;
						outgoingPacket->deleteData=false; // Did not come from the network
						outgoingPacket->data=(unsigned char*) rakMalloc_Ex(dataLength, __FILE__, __LINE__);
						if (outgoingPacket->data==0)
						{
							notifyOutOfMemory(__FILE__, __LINE__);
							RakNet::OP_DELETE(outgoingPacket,__FILE__,__LINE__);
							return 0;
						}
						bq->ReadBytes((char*) outgoingPacket->data,dataLength,false);

						waitingPackets.Push(outgoingPacket, __FILE__, __LINE__ );

						// Peek the header to see if a full message is waiting
						if (bq->ReadBytes((char*) &dataLength,sizeof(PTCPHeader),true))
						{
							if (RakNet::BitStream::DoEndianSwap())
								RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &dataLength,sizeof(dataLength));
						}
						else
							break;
					} while (bq->GetBytesWritten()>=dataLength+sizeof(PTCPHeader));
				}
				else
				{

					unsigned int oldWritten = bq->GetBytesWritten()-incomingPacket->length;
					unsigned int newWritten = bq->GetBytesWritten();

					// Return ID_DOWNLOAD_PROGRESS
					if (newWritten/65536!=oldWritten/65536)
					{
						outgoingPacket = RakNet::OP_NEW<Packet>(__FILE__, __LINE__);
						outgoingPacket->length=sizeof(MessageID) +
							sizeof(unsigned int)*2 +
							sizeof(unsigned int) +
							65536;
						outgoingPacket->bitSize=BYTES_TO_BITS(incomingPacket->length);
						outgoingPacket->guid=UNASSIGNED_RAKNET_GUID;
						outgoingPacket->systemAddress=incomingPacket->systemAddress;
						outgoingPacket->deleteData=false;
						outgoingPacket->data=(unsigned char*) rakMalloc_Ex(outgoingPacket->length, __FILE__, __LINE__);
						if (outgoingPacket->data==0)
						{
							notifyOutOfMemory(__FILE__, __LINE__);
							RakNet::OP_DELETE(outgoingPacket,__FILE__,__LINE__);
							return 0;
						}

						outgoingPacket->data[0]=(MessageID)ID_DOWNLOAD_PROGRESS;
						unsigned int totalParts=dataLength/65536;
						unsigned int partIndex=newWritten/65536;
						unsigned int oneChunkSize=65536;
						memcpy(outgoingPacket->data+sizeof(MessageID), &partIndex, sizeof(unsigned int));
						memcpy(outgoingPacket->data+sizeof(MessageID)+sizeof(unsigned int)*1, &totalParts, sizeof(unsigned int));
						memcpy(outgoingPacket->data+sizeof(MessageID)+sizeof(unsigned int)*2, &oneChunkSize, sizeof(unsigned int));
						bq->IncrementReadOffset(sizeof(PTCPHeader));
						bq->ReadBytes((char*) outgoingPacket->data+sizeof(MessageID)+sizeof(unsigned int)*3,oneChunkSize,true);
						bq->DecrementReadOffset(sizeof(PTCPHeader));

						waitingPackets.Push(outgoingPacket, __FILE__, __LINE__ );
					}
				}

			}

			DeallocatePacket(incomingPacket);
			incomingPacket=0;
		}
		else
			waitingPackets.Push(incomingPacket, __FILE__, __LINE__ );

		incomingPacket = TCPInterface::Receive();
	}

	return ReturnOutgoingPacket();
}
Example #15
0
QVariant StpProtocol::fieldData(int index, FieldAttrib attrib,
                                int streamIndex) const
{
    QString str[] = {"Topology Change", "Topology Change Acknowledgment"};

    switch (index)
    {
        case stp_protocol_id:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Protocol Identifier");
                case FieldValue:
                    return data_.protocol_id();
                case FieldTextValue:
                    return QString("0x%1").arg(data_.protocol_id(),
                                               4, BASE_HEX, QChar('0'));
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data_.protocol_id(),
                                 (uchar*)fv.data());
                    return fv;
                }
                case FieldBitSize:
                    return BYTES_TO_BITS(2);
                default:
                    break;
            }
            break;
        }
        case stp_version_id:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Version Identifier");
                case FieldValue:
                    return data_.protocol_version_id();
                case FieldTextValue:
                    return QString("%1").arg(
                                data_.protocol_version_id());
                case FieldFrameValue:
                    return QByteArray(1,
                                      (char)data_.protocol_version_id());
                case FieldBitSize:
                    return BYTES_TO_BITS(1);
                default:
                    break;
            }
            break;
        }
        case stp_bpdu_type:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("BPDU Type");
                case FieldValue:
                    return data_.bpdu_type();
                case FieldTextValue:
                    return QString("0x%1").arg(data_.bpdu_type(),
                                               2, BASE_HEX, QChar('0'));
                case FieldFrameValue:
                    return QByteArray(1, (char)data_.bpdu_type());
                case FieldBitSize:
                    return BYTES_TO_BITS(1);
                default:
                    break;
            }
            break;
        }
        case stp_flags:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("BPDU Flags");
                case FieldValue:
                    return data_.flags();
                case FieldTextValue:
                {
                    QString strTemp = "(";
                    if((data_.flags() & ONE_BIT(0))) strTemp += str[0] + ", ";
                    if((data_.flags() & ONE_BIT(7))) strTemp += str[1] + ", ";
                    strTemp += ")";
                    strTemp.replace(", )", ")");
                    return strTemp;
                }
                case FieldFrameValue:
                    return QByteArray(1, (char)data_.flags());
                case FieldBitSize:
                    return BYTES_TO_BITS(1);
                default:
                    break;
            }
            break;
        }
        case stp_root_id:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Root Identifier");
                case FieldValue:
                    return (quint64) data_.root_id();
                case FieldTextValue:
                {
                    // Root ID contain two value:
                    // Root ID Priority(first 2 bytes)
                    // and Root ID MAC (last 6 bytes). (IEEE802.1D-2008)
                    quint16 priority = (
                        data_.root_id() & 0xFFFF000000000000ULL) >> (BYTES_TO_BITS(6));
                    quint64 mac = data_.root_id() & 0x0000FFFFFFFFFFFFULL;
                    return QString("Priority: %1 / MAC: %2")
                            .arg(QString::number(priority),
                        uintToMacStr(mac));
                }
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(8));
                    qToBigEndian((quint64)data_.root_id(), (uchar*)fv.data());
                    return fv;
                }
                case FieldBitSize:
                    return BYTES_TO_BITS(8);
                default:
                    break;
            }
            break;
        }
        case stp_root_path_cost:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Root Path Cost");
                case FieldValue:
                    return data_.root_path_cost();
                case FieldTextValue:
                    return QString("%1").arg(data_.root_path_cost());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(4));
                    qToBigEndian(data_.root_path_cost(), (uchar*)fv.data());
                    return fv;
                }
                case FieldBitSize:
                    return BYTES_TO_BITS(4);
                default:
                    break;
            }
            break;
        }
        case stp_bridge_id:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Bridge Identifier");
                case FieldValue:
                    return (quint64) data_.bridge_id();
                case FieldTextValue:
                {
                    // Bridge ID contain two value:
                    // Bridge ID Priority(first 2 bytes)
                    // and Bridge ID MAC (last 6 bytes). (IEEE802.1D-2008)
                    quint16 priority = (data_.bridge_id() & 0xFFFF000000000000ULL
                                        ) >> (BYTES_TO_BITS(6));
                    quint64 mac = data_.bridge_id() & 0x0000FFFFFFFFFFFFULL;
                    return QString("Priority: %1 / MAC: %2").arg(QString::number(priority),
                                                  uintToMacStr(mac));
                }
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(8));
                    qToBigEndian((quint64)data_.bridge_id(), (uchar*)fv.data());
                    return fv;
                }
                case FieldBitSize:
                    return BYTES_TO_BITS(8);
                default:
                    break;
            }
            break;
        }
        case stp_port_id:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Port Identifier");
                case FieldValue:
                    return data_.port_id();
                case FieldTextValue:
                    return QString("0x%1").arg(data_.port_id(), 4,
                                               BASE_HEX, QChar('0'));
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data_.port_id(), (uchar*)fv.data());
                    return fv;
                }
                case FieldBitSize:
                    return BYTES_TO_BITS(2);
                default:
                    break;
            }
            break;
        }
        case stp_message_age:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Message Age");
                case FieldValue:
                    return data_.message_age();
                case FieldTextValue:
                    return QString("%1").arg(data_.message_age());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)(data_.message_age()),
                                 (uchar*)fv.data());
                    return fv;
                }
                case FieldBitSize:
                    return BYTES_TO_BITS(2);
                default:
                    break;
            }
            break;
        }
        case stp_max_age:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Max Age");
                case FieldValue:
                    return data_.max_age();
                case FieldTextValue:
                    return QString("%1").arg(data_.max_age());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data_.max_age(), (uchar*)fv.data());
                    return fv;
                }
                case FieldBitSize:
                    return BYTES_TO_BITS(2);
                default:
                    break;
            }
            break;
        }
        case stp_hello_time:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Hello Time");
                case FieldValue:
                    return data_.hello_time();
                case FieldTextValue:
                    return QString("%1").arg(data_.hello_time());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data_.hello_time(), (uchar*)fv.data());
                    return fv;
                }
                case FieldBitSize:
                    return BYTES_TO_BITS(2);
                default:
                    break;
            }
            break;
        }
        case stp_forward_delay:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Forward Delay");
                case FieldValue:
                    return data_.forward_delay();
                case FieldTextValue:
                    return QString("%1").arg(data_.forward_delay());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data_.forward_delay(),
                                 (uchar*)fv.data());
                    return fv;
                }
                case FieldBitSize:
                    return BYTES_TO_BITS(2);
                default:
                    break;
            }
            break;
        }
        default:
            break;
    }
    return AbstractProtocol::fieldData(index, attrib, streamIndex);
}
Example #16
0
int main(void)
{
	client=server=0;

	text= new char [BIG_PACKET_SIZE];
	quit=false;
	RakNetTime nextStatTime = RakNet::GetTime() + 1000;
	char ch;

	printf("This is a test I use to test the packet splitting capabilities of RakNet\n");
	printf("All it does is send a large block of data to the feedback loop\n");
	printf("Difficulty: Beginner\n\n");

	printf("Enter 's' to run as server, 'c' to run as client, space to run local.\n");
	gets(text);
	ch=text[0];
	if (ch=='c')
	{
		client=RakNetworkFactory::GetRakPeerInterface();
		printf("Working as client\n");
		printf("Enter remote IP: ");
		gets(text);
		if (text[0]==0)
			strcpy(text, "216.224.123.180");
	}
	else if (ch=='s')
	{
		server=RakNetworkFactory::GetRakPeerInterface();
		printf("Working as server\n");
	}
	else
	{
		client=RakNetworkFactory::GetRakPeerInterface();
		server=RakNetworkFactory::GetRakPeerInterface();;
		strcpy(text, "127.0.0.1");
	}
	if (client)
	{
		SocketDescriptor socketDescriptor(0,0);
		client->Startup(1, 0, &socketDescriptor, 1);
		client->SetSplitMessageProgressInterval(100); // Get ID_DOWNLOAD_PROGRESS notifications
		client->Connect(text, 60000, 0, 0);
	}
	if (server)
	{
		SocketDescriptor socketDescriptor(60000,0);
		server->SetMaximumIncomingConnections(32);
		server->Startup(32, 0, &socketDescriptor, 1);
	}
	RakSleep(500);

	// Always apply the network simulator on two systems, never just one, with half the values on each.
	// Otherwise the flow control gets confused.
	//if (client)
	// client->ApplyNetworkSimulator(128000, 0, 0);
	//if (server)
	//	server->ApplyNetworkSimulator(128000, 0, 0);

	RakNetTime start,stop;

	start=RakNet::GetTime();
	Packet *packet;
	while (!quit)
	{
		if (server)
		{
			for (packet = server->Receive(); packet; server->DeallocatePacket(packet), packet=server->Receive())
			{
				if (packet->data[0]==ID_NEW_INCOMING_CONNECTION)
				{
					for (int i=0; i < BIG_PACKET_SIZE; i++)
						text[i]=i%256;
					text[0]=(char)255; // So it doesn't register as an internal ID
					server->Send(text, BIG_PACKET_SIZE, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false);
					// Keep the stat from updating until the messages move to the thread or it quits right away
					nextStatTime=RakNet::GetTime()+1000;
				}
				if (packet->data[0]==ID_CONNECTION_LOST)
					printf("ID_CONNECTION_LOST from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_DISCONNECTION_NOTIFICATION)
					printf("ID_DISCONNECTION_NOTIFICATION from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_NEW_INCOMING_CONNECTION)
					printf("ID_NEW_INCOMING_CONNECTION from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
					printf("ID_CONNECTION_REQUEST_ACCEPTED from %s\n", packet->systemAddress.ToString());
			}
		}
		if (client)
		{
			packet = client->Receive();
			while (packet)
			{
				if (packet->data[0]==ID_DOWNLOAD_PROGRESS)
				{
					RakNet::BitStream progressBS(packet->data, packet->length, false);
					progressBS.IgnoreBits(8); // ID_DOWNLOAD_PROGRESS
					unsigned int progress;
					unsigned int total;
					unsigned int partLength;
					RakNetStatistics *rss=client->GetStatistics(client->GetSystemAddressFromIndex(0));

					// Disable endian swapping on reading this, as it's generated locally in ReliabilityLayer.cpp
					progressBS.ReadBits( (unsigned char* ) &progress, BYTES_TO_BITS(sizeof(progress)), true );
					progressBS.ReadBits( (unsigned char* ) &total, BYTES_TO_BITS(sizeof(total)), true );
					progressBS.ReadBits( (unsigned char* ) &partLength, BYTES_TO_BITS(sizeof(partLength)), true );

					printf("Progress: msgID=%i Progress %i/%i Partsize=%i Full=%i\n",
						(unsigned char) packet->data[0],
						progress,
						total,
						partLength,
						rss->bandwidthExceeded);
				}
				else if (packet->data[0]>=ID_USER_PACKET_ENUM)
				{
					if (packet->data[0]==255)
					{
						bool dataValid=true;
						for (int i=1; i < BIG_PACKET_SIZE; i++)
						{
							if (packet->data[i]!=i%256)
							{
								dataValid=false;
								break;
							}
						}

						if (dataValid)
							printf("Test succeeded. %i bytes.\n", packet->length);
						else
							printf("Test failed. %i bytes.\n", packet->length);
					}
					else
						printf("Unknown packet %i: Test failed. %i bytes.\n", packet->data[0], packet->length);

					quit=true;
				}
				else if (packet->data[0]==ID_CONNECTION_LOST)
					printf("ID_CONNECTION_LOST from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_DISCONNECTION_NOTIFICATION)
					printf("ID_DISCONNECTION_NOTIFICATION from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_NEW_INCOMING_CONNECTION)
					printf("ID_NEW_INCOMING_CONNECTION from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
					printf("ID_CONNECTION_REQUEST_ACCEPTED from %s\n", packet->systemAddress.ToString());

				client->DeallocatePacket(packet);
				packet = client->Receive();
			}
		}

		if (RakNet::GetTime() > nextStatTime)
		{
			nextStatTime=RakNet::GetTime()+1000;
			RakNetStatistics *rssSender;
			RakNetStatistics *rssReceiver;
			if (server)
			{
				unsigned int i;
				unsigned short numSystems;
				server->GetConnectionList(0,&numSystems);
				if (numSystems>0)
				{
					printf("KPBS,ploss: ");
					for (i=0; i < numSystems; i++)
					{
						rssSender=server->GetStatistics(server->GetSystemAddressFromIndex(i));
						printf("%i:%.0f,%.1f ", i+1,rssSender->bitsPerSecondSent/1000, 100.0f * ( float ) rssSender->messagesTotalBitsResent / ( float ) rssSender->totalBitsSent);
					}
					printf("\n");
				}

				/*
				if (rssSender)
				{
				printf("Snd: %i waiting. %i waiting on ack. Got %i acks. KBPS=%.1f. Ploss=%.1f. Full=%i\n", rssSender->messageSendBuffer[HIGH_PRIORITY], rssSender->messagesOnResendQueue,rssSender->acknowlegementsReceived, rssSender->bitsPerSecond/1000, 100.0f * ( float ) rssSender->messagesTotalBitsResent / ( float ) rssSender->totalBitsSent, rssSender->bandwidthExceeded);
				if (client==0)
				printf("\n");
				if (sentPacket && rssSender->messageSendBuffer[HIGH_PRIORITY]==0 && rssSender->messagesOnResendQueue==0 && client==0)
				{
				RakNetStatistics *rss=server->GetStatistics(server->GetSystemAddressFromIndex(0));
				StatisticsToString(rss, text, 2);
				printf("%s", text);
				printf("Sender quitting with no messages on resend queue.\n");
				quit=true;
				}
				}
				*/
			}
			if (client)
			{
				rssReceiver=client->GetStatistics(client->GetSystemAddressFromIndex(0));
				if (rssReceiver)
					printf("Receiver: %i acks waiting.\n", rssReceiver->acknowlegementsPending);
			}
		}

		RakSleep(100);
	}
	stop=RakNet::GetTime();
	double seconds = (double)(stop-start)/1000.0;

	if (server)
	{
		RakNetStatistics *rssSender=server->GetStatistics(server->GetSystemAddressFromIndex(0));
		StatisticsToString(rssSender, text, 2);
		printf("%s", text);
	}

	printf("%i bytes per second transfered. Press enter to quit\n", (int)((double)(BIG_PACKET_SIZE) / seconds )) ;
	gets(text);

	delete []text;
	RakNetworkFactory::DestroyRakPeerInterface(client);
	RakNetworkFactory::DestroyRakPeerInterface(server);

	return 0;
}
Example #17
0
static int convert_variable_type(Dwarf_Die *vr_die,
				 struct probe_trace_arg *tvar,
				 const char *cast)
{
	struct probe_trace_arg_ref **ref_ptr = &tvar->ref;
	Dwarf_Die type;
	char buf[16];
	int ret;

	/* TODO: check all types */
	if (cast && strcmp(cast, "string") != 0) {
		/* Non string type is OK */
		tvar->type = strdup(cast);
		return (tvar->type == NULL) ? -ENOMEM : 0;
	}

	if (die_get_bit_size(vr_die) != 0) {
		/* This is a bitfield */
		ret = snprintf(buf, 16, "b%d@%d/%zd", die_get_bit_size(vr_die),
				die_get_bit_offset(vr_die),
				BYTES_TO_BITS(die_get_byte_size(vr_die)));
		goto formatted;
	}

	if (die_get_real_type(vr_die, &type) == NULL) {
		pr_warning("Failed to get a type information of %s.\n",
			   dwarf_diename(vr_die));
		return -ENOENT;
	}

	pr_debug("%s type is %s.\n",
		 dwarf_diename(vr_die), dwarf_diename(&type));

	if (cast && strcmp(cast, "string") == 0) {	/* String type */
		ret = dwarf_tag(&type);
		if (ret != DW_TAG_pointer_type &&
		    ret != DW_TAG_array_type) {
			pr_warning("Failed to cast into string: "
				   "%s(%s) is not a pointer nor array.\n",
				   dwarf_diename(vr_die), dwarf_diename(&type));
			return -EINVAL;
		}
		if (ret == DW_TAG_pointer_type) {
			if (die_get_real_type(&type, &type) == NULL) {
				pr_warning("Failed to get a type"
					   " information.\n");
				return -ENOENT;
			}
			while (*ref_ptr)
				ref_ptr = &(*ref_ptr)->next;
			/* Add new reference with offset +0 */
			*ref_ptr = zalloc(sizeof(struct probe_trace_arg_ref));
			if (*ref_ptr == NULL) {
				pr_warning("Out of memory error\n");
				return -ENOMEM;
			}
		}
		if (!die_compare_name(&type, "char") &&
		    !die_compare_name(&type, "unsigned char")) {
			pr_warning("Failed to cast into string: "
				   "%s is not (unsigned) char *.\n",
				   dwarf_diename(vr_die));
			return -EINVAL;
		}
		tvar->type = strdup(cast);
		return (tvar->type == NULL) ? -ENOMEM : 0;
	}

	ret = BYTES_TO_BITS(die_get_byte_size(&type));
	if (!ret)
		/* No size ... try to use default type */
		return 0;

	/* Check the bitwidth */
	if (ret > MAX_BASIC_TYPE_BITS) {
		pr_info("%s exceeds max-bitwidth. Cut down to %d bits.\n",
			dwarf_diename(&type), MAX_BASIC_TYPE_BITS);
		ret = MAX_BASIC_TYPE_BITS;
	}
	ret = snprintf(buf, 16, "%c%d",
		       die_is_signed_type(&type) ? 's' : 'u', ret);

formatted:
	if (ret < 0 || ret >= 16) {
		if (ret >= 16)
			ret = -E2BIG;
		pr_warning("Failed to convert variable type: %s\n",
			   strerror(-ret));
		return ret;
	}
	tvar->type = strdup(buf);
	if (tvar->type == NULL)
		return -ENOMEM;
	return 0;
}
Example #18
0
int32_t psa_asymmetric_encrypt_test(security_t caller)
{
    int                     num_checks = sizeof(check1)/sizeof(check1[0]);
    int32_t                 i, status;
    const uint8_t           *key_data;
    uint8_t                 *salt;
    size_t                  length;
    psa_key_policy_t        policy;

    /* Initialize the PSA crypto library*/
    status = val->crypto_function(VAL_CRYPTO_INIT);
    TEST_ASSERT_EQUAL(status, PSA_SUCCESS, TEST_CHECKPOINT_NUM(1));

    for (i = 0; i < num_checks; i++)
    {
        val->print(PRINT_TEST, "[Check %d] ", g_test_count++);
        val->print(PRINT_TEST, check1[i].test_desc, 0);

        /* Initialize a key policy structure to a default that forbids all
         * usage of the key
         */
        val->crypto_function(VAL_CRYPTO_KEY_POLICY_INIT, &policy);

        /* Setting up the watchdog timer for each check */
        status = val->wd_reprogram_timer(WD_CRYPTO_TIMEOUT);
        TEST_ASSERT_EQUAL(status, VAL_STATUS_SUCCESS, TEST_CHECKPOINT_NUM(2));

        /* Set the standard fields of a policy structure */
        val->crypto_function(VAL_CRYPTO_KEY_POLICY_SET_USAGE, &policy, check1[i].usage,
                                                                          check1[i].key_alg);

        memset(output, 0, sizeof(output));

        /* Set the key data based on key type */
        if (PSA_KEY_TYPE_IS_RSA(check1[i].key_type))
        {
            if (check1[i].key_type == PSA_KEY_TYPE_RSA_KEYPAIR)
            {
                if (check1[i].expected_bit_length == BYTES_TO_BITS(384))
                    key_data = rsa_384_keypair;
                else if (check1[i].expected_bit_length == BYTES_TO_BITS(256))
                    key_data = rsa_256_keypair;
                else if (check1[i].expected_bit_length == BYTES_TO_BITS(128))
                    key_data = rsa_128_keypair;
                else
                    return VAL_STATUS_INVALID;
            }
            else
            {
                if (check1[i].expected_bit_length == BYTES_TO_BITS(384))
                    key_data = rsa_384_keydata;
                else if (check1[i].expected_bit_length == BYTES_TO_BITS(256))
                    key_data = rsa_256_keydata;
                else if (check1[i].expected_bit_length == BYTES_TO_BITS(128))
                    key_data = rsa_128_keydata;
                else
                    return VAL_STATUS_INVALID;
            }
        }
        else if (PSA_KEY_TYPE_IS_ECC(check1[i].key_type))
        {
            if (PSA_KEY_TYPE_IS_ECC_KEYPAIR(check1[i].key_type))
                key_data = ec_keypair;
            else
                key_data = ec_keydata;
        }
        else
            key_data = check1[i].key_data;

        /* Allocate a key slot for a transient key */
        status = val->crypto_function(VAL_CRYPTO_ALLOCATE_KEY, &check1[i].key_handle);
        TEST_ASSERT_EQUAL(status, PSA_SUCCESS, TEST_CHECKPOINT_NUM(3));

        /* Set the usage policy on a key slot */
        status = val->crypto_function(VAL_CRYPTO_SET_KEY_POLICY, check1[i].key_handle,
                    &policy);
        TEST_ASSERT_EQUAL(status, PSA_SUCCESS, TEST_CHECKPOINT_NUM(4));

        /* Import the key data into the key slot */
        status = val->crypto_function(VAL_CRYPTO_IMPORT_KEY, check1[i].key_handle,
                    check1[i].key_type, key_data, check1[i].key_length);
        TEST_ASSERT_EQUAL(status, PSA_SUCCESS, TEST_CHECKPOINT_NUM(5));

        if (is_buffer_empty(check1[i].salt, check1[i].salt_length) == TRUE)
            salt = NULL;
        else
            salt = check1[i].salt;

        /* Encrypt a short message with a public key */
        status = val->crypto_function(VAL_CRYPTO_ASYMMTERIC_ENCRYPT, check1[i].key_handle,
                    check1[i].key_alg, check1[i].input, check1[i].input_length, salt,
                    check1[i].salt_length, output, check1[i].output_size, &length);
        TEST_ASSERT_EQUAL(status, check1[i].expected_status, TEST_CHECKPOINT_NUM(6));

        if (check1[i].expected_status != PSA_SUCCESS)
            continue;

        /* Check if the output length matches with the expected output length */
        TEST_ASSERT_EQUAL(length, check1[i].expected_output_length, TEST_CHECKPOINT_NUM(7));

        /* We test encryption by checking that encrypt-then-decrypt gives back
         * the original plaintext because of the non-optional random
         * part of encryption process which prevents using fixed vectors. */
        if ((check1[i].usage & PSA_KEY_USAGE_DECRYPT) == PSA_KEY_USAGE_DECRYPT)
        {
            status = val->crypto_function(VAL_CRYPTO_ASYMMTERIC_DECRYPT,
                        check1[i].key_handle, check1[i].key_alg, output, length, salt,
                        check1[i].salt_length, output, check1[i].output_size, &length);
            TEST_ASSERT_EQUAL(status, PSA_SUCCESS, TEST_CHECKPOINT_NUM(8));

            /* Check if the output length matches with the input length */
            TEST_ASSERT_EQUAL(length, check1[i].input_length, TEST_CHECKPOINT_NUM(9));

            /* Check if the output matches with the given input data */
            TEST_ASSERT_MEMCMP(output, check1[i].input, length, TEST_CHECKPOINT_NUM(10));
        }
    }

    return VAL_STATUS_SUCCESS;
}
void FileListTransfer::OnReferencePush(Packet *packet, bool fullFile)
{
	// fullFile is always true for TCP, since TCP does not return SPLIT_PACKET_NOTIFICATION

	RakNet::BitStream refPushAck;
	refPushAck.Write((MessageID)ID_FILE_LIST_REFERENCE_PUSH_ACK);
	SendUnified(&refPushAck,HIGH_PRIORITY, RELIABLE, 0, packet->systemAddress, false);

	FileListTransferCBInterface::OnFileStruct onFileStruct;
	RakNet::BitStream inBitStream(packet->data, packet->length, false);
	inBitStream.IgnoreBits(8);

	unsigned int partCount=0;
	unsigned int partTotal=1;
	unsigned int partLength=0;
	onFileStruct.fileData=0;
	if (fullFile==false)
	{
		// Disable endian swapping on reading this, as it's generated locally in ReliabilityLayer.cpp
		inBitStream.ReadBits( (unsigned char* ) &partCount, BYTES_TO_BITS(sizeof(partCount)), true );
		inBitStream.ReadBits( (unsigned char* ) &partTotal, BYTES_TO_BITS(sizeof(partTotal)), true );
		inBitStream.ReadBits( (unsigned char* ) &partLength, BYTES_TO_BITS(sizeof(partLength)), true );
		inBitStream.IgnoreBits(8);
		// The header is appended to every chunk, which we continue to read after this statement block
	}

	inBitStream.Read(onFileStruct.context);
	inBitStream.Read(onFileStruct.setID);
	FileListReceiver *fileListReceiver;
	if (fileListReceivers.Has(onFileStruct.setID)==false)
	{
		return;
	}
	fileListReceiver=fileListReceivers.Get(onFileStruct.setID);
	if (fileListReceiver->allowedSender!=packet->systemAddress)
	{
#ifdef _DEBUG
		RakAssert(0);
#endif
		return;
	}

#ifdef _DEBUG
	RakAssert(fileListReceiver->gotSetHeader==true);
#endif

	if (stringCompressor->DecodeString(onFileStruct.fileName, 512, &inBitStream)==false)
	{
#ifdef _DEBUG
		RakAssert(0);
#endif
		return;
	}

	inBitStream.ReadCompressed(onFileStruct.fileIndex);
	inBitStream.ReadCompressed(onFileStruct.finalDataLength);
	unsigned int offset;
	unsigned int chunkLength;
	inBitStream.ReadCompressed(offset);
	inBitStream.ReadCompressed(chunkLength);
//	if (chunkLength==0)
//		return;
	bool lastChunk;
	inBitStream.Read(lastChunk);
	bool finished = lastChunk && fullFile;

	if (fullFile==false)
		fileListReceiver->partLength=partLength;

	FLR_MemoryBlock mb;
	if (fileListReceiver->pushedFiles.Has(onFileStruct.fileIndex)==false)
	{
		if (chunkLength > 1000000000 || onFileStruct.finalDataLength > 1000000000)
		{
			RakAssert("FileListTransfer::OnReferencePush: file too large" && 0);
			return;
		}

		mb.allocatedLength=onFileStruct.finalDataLength;
		mb.block = (char*) rakMalloc_Ex(onFileStruct.finalDataLength, __FILE__, __LINE__);
		if (mb.block==0)
		{
			notifyOutOfMemory(__FILE__, __LINE__);
			return;
		}

		fileListReceiver->pushedFiles.SetNew(onFileStruct.fileIndex, mb);
	}
	else
		mb=fileListReceiver->pushedFiles.Get(onFileStruct.fileIndex);

	if (offset+chunkLength > mb.allocatedLength)
	{
		// Overrun
		RakAssert("FileListTransfer::OnReferencePush: Write would overrun allocated block" && 0);
		return;
	}

	// Read header uncompressed so the data is byte aligned, for speed
	onFileStruct.compressedTransmissionLength=(unsigned int) onFileStruct.finalDataLength;

	unsigned int unreadBits = inBitStream.GetNumberOfUnreadBits();
	unsigned int unreadBytes = BITS_TO_BYTES(unreadBits);
	unsigned int amountToRead;
	if (fullFile)
		amountToRead=chunkLength;
	else
		amountToRead=unreadBytes;

	inBitStream.AlignReadToByteBoundary();
	if (fullFile || (rakPeerInterface->GetSplitMessageProgressInterval() != 0 && (int)partCount==rakPeerInterface->GetSplitMessageProgressInterval()))
	{
		inBitStream.Read(mb.block+offset, amountToRead);
	}

	onFileStruct.setCount=fileListReceiver->setCount;
	onFileStruct.setTotalCompressedTransmissionLength=fileListReceiver->setTotalCompressedTransmissionLength;
	onFileStruct.setTotalFinalLength=fileListReceiver->setTotalFinalLength;
	onFileStruct.fileData=mb.block;

	if (finished)
	{
		if (fileListReceiver->downloadHandler->OnFile(&onFileStruct))
			rakFree_Ex(onFileStruct.fileData, __FILE__, __LINE__ );
		fileListReceiver->pushedFiles.Delete(onFileStruct.fileIndex);

		fileListReceiver->filesReceived++;

		// If this set is done, free the memory for it.
		if ((int) fileListReceiver->setCount==fileListReceiver->filesReceived)
		{
			if (fileListReceiver->downloadHandler->OnDownloadComplete()==false)
			{
				fileListReceiver->downloadHandler->OnDereference();
				fileListReceivers.Delete(onFileStruct.setID);
				if (fileListReceiver->deleteDownloadHandler)
					RakNet::OP_DELETE(fileListReceiver->downloadHandler, __FILE__, __LINE__);
				RakNet::OP_DELETE(fileListReceiver, __FILE__, __LINE__);
			}
		}
	}
	else
	{
		unsigned int totalNotifications;
		unsigned int currentNotificationIndex;
		unsigned int unreadBytes;

		if (rakPeerInterface==0 || rakPeerInterface->GetSplitMessageProgressInterval()==0)
		{
			totalNotifications = onFileStruct.finalDataLength / chunkLength + 1;
			currentNotificationIndex = offset / chunkLength;
			unreadBytes = mb.allocatedLength - ((offset+1)*chunkLength);
		}
		else
		{
			totalNotifications = onFileStruct.finalDataLength / fileListReceiver->partLength + 1;
			if (fullFile==false)
				currentNotificationIndex = (offset+partCount*fileListReceiver->partLength) / fileListReceiver->partLength ;
			else
				currentNotificationIndex = (offset+chunkLength) / fileListReceiver->partLength ;
			unreadBytes = onFileStruct.finalDataLength - ((currentNotificationIndex+1) * fileListReceiver->partLength);
		}
		fileListReceiver->downloadHandler->OnFileProgress(&onFileStruct, currentNotificationIndex, totalNotifications, unreadBytes, mb.block);
	}

	return;
}
Example #20
0
static inline
enum bt_btr_status read_basic_string_type_and_call(
		struct bt_btr *btr, bool begin)
{
	size_t buf_at_bytes;
	const uint8_t *result;
	size_t available_bytes;
	const uint8_t *first_chr;
	enum bt_btr_status status = BT_BTR_STATUS_OK;

	if (!at_least_one_bit_left(btr)) {
		BT_LOGV("Reached end of data: btr-addr=%p", btr);
		status = BT_BTR_STATUS_EOF;
		goto end;
	}

	assert(buf_at_from_addr(btr) % 8 == 0);
	available_bytes = BITS_TO_BYTES_FLOOR(available_bits(btr));
	buf_at_bytes = BITS_TO_BYTES_FLOOR(buf_at_from_addr(btr));
	assert(btr->buf.addr);
	first_chr = &btr->buf.addr[buf_at_bytes];
	result = memchr(first_chr, '\0', available_bytes);

	if (begin && btr->user.cbs.types.string_begin) {
		BT_LOGV("Calling user function (string, beginning).");
		status = btr->user.cbs.types.string_begin(
			btr->cur_basic_field_type, btr->user.data);
		BT_LOGV("User function returned: status=%s",
			bt_btr_status_string(status));
		if (status != BT_BTR_STATUS_OK) {
			BT_LOGW("User function failed: btr-addr=%p, status=%s",
				btr, bt_btr_status_string(status));
			goto end;
		}
	}

	if (!result) {
		/* No null character yet */
		if (btr->user.cbs.types.string) {
			BT_LOGV("Calling user function (substring).");
			status = btr->user.cbs.types.string(
				(const char *) first_chr,
				available_bytes, btr->cur_basic_field_type,
				btr->user.data);
			BT_LOGV("User function returned: status=%s",
				bt_btr_status_string(status));
			if (status != BT_BTR_STATUS_OK) {
				BT_LOGW("User function failed: "
					"btr-addr=%p, status=%s",
					btr, bt_btr_status_string(status));
				goto end;
			}
		}

		consume_bits(btr, BYTES_TO_BITS(available_bytes));
		btr->state = BTR_STATE_READ_BASIC_CONTINUE;
		status = BT_BTR_STATUS_EOF;
	} else {
		/* Found the null character */
		size_t result_len = (size_t) (result - first_chr);

		if (btr->user.cbs.types.string && result_len) {
			BT_LOGV("Calling user function (substring).");
			status = btr->user.cbs.types.string(
				(const char *) first_chr,
				result_len, btr->cur_basic_field_type,
				btr->user.data);
			BT_LOGV("User function returned: status=%s",
				bt_btr_status_string(status));
			if (status != BT_BTR_STATUS_OK) {
				BT_LOGW("User function failed: "
					"btr-addr=%p, status=%s",
					btr, bt_btr_status_string(status));
				goto end;
			}
		}

		if (btr->user.cbs.types.string_end) {
			BT_LOGV("Calling user function (string, end).");
			status = btr->user.cbs.types.string_end(
				btr->cur_basic_field_type, btr->user.data);
			BT_LOGV("User function returned: status=%s",
				bt_btr_status_string(status));
			if (status != BT_BTR_STATUS_OK) {
				BT_LOGW("User function failed: "
					"btr-addr=%p, status=%s",
					btr, bt_btr_status_string(status));
				goto end;
			}
		}

		consume_bits(btr, BYTES_TO_BITS(result_len + 1));

		if (stack_empty(btr->stack)) {
			/* Root is a basic type */
			btr->state = BTR_STATE_DONE;
		} else {
			/* Go to next field */
			stack_top(btr->stack)->index++;
			btr->state = BTR_STATE_NEXT_FIELD;
			btr->last_bo = btr->cur_bo;
		}
	}

end:
	return status;
}
Example #21
0
int main(void)
{
	client=server=0;

	text= new char [BIG_PACKET_SIZE];
	quit=false;
	char ch;

	printf("This is a test I use to test the packet splitting capabilities of RakNet\n");
	printf("All it does is send a large block of data to the feedback loop\n");
	printf("Difficulty: Beginner\n\n");

	printf("Enter 's' to run as server, 'c' to run as client, space to run local.\n");
	ch=' ';
	gets(text);
	ch=text[0];

	if (ch=='c')
	{
		client=RakNetworkFactory::GetRakPeerInterface();
		printf("Working as client\n");
		printf("Enter remote IP: ");
		gets(text);
		if (text[0]==0)
			strcpy(text, "127.0.0.1");
		//	strcpy(text, "94.198.81.195"); // dx in Europe
	}
	else if (ch=='s')
	{
		server=RakNetworkFactory::GetRakPeerInterface();
		printf("Working as server\n");
	}
	else
	{
		client=RakNetworkFactory::GetRakPeerInterface();
		server=RakNetworkFactory::GetRakPeerInterface();;
		strcpy(text, "127.0.0.1");
	}
	if (client)
	{
		client->SetTimeoutTime(2000,UNASSIGNED_SYSTEM_ADDRESS);
		SocketDescriptor socketDescriptor(0,0);
		client->Startup(1, 10, &socketDescriptor, 1);
		client->SetSplitMessageProgressInterval(10000); // Get ID_DOWNLOAD_PROGRESS notifications
		client->Connect(text, 60000, 0, 0);
	}
	if (server)
	{
		server->SetTimeoutTime(2000,UNASSIGNED_SYSTEM_ADDRESS);
		SocketDescriptor socketDescriptor(60000,0);
		server->SetMaximumIncomingConnections(4);
		server->Startup(4, 10, &socketDescriptor, 1);
	}
	RakSleep(500);

	// Always apply the network simulator on two systems, never just one, with half the values on each.
	// Otherwise the flow control gets confused.
	//if (client)
	// client->ApplyNetworkSimulator(128000, 0, 0);
	//if (server)
	//	server->ApplyNetworkSimulator(128000, 0, 0);

	RakNetTime start,stop;

	RakNetTime nextStatTime = RakNet::GetTime() + 1000;
	Packet *packet;
	start=RakNet::GetTimeMS();
	while (!quit)
	{
		if (server)
		{
			for (packet = server->Receive(); packet; server->DeallocatePacket(packet), packet=server->Receive())
			{
				if (packet->data[0]==ID_NEW_INCOMING_CONNECTION)
				{
					printf("Starting send\n");
					start=RakNet::GetTimeMS();
					if (BIG_PACKET_SIZE<=100000)
					{
						for (int i=0; i < BIG_PACKET_SIZE; i++)
							text[i]=255-(i&255);
					}
					else
						text[0]=(unsigned char) 255;
					server->Send(text, BIG_PACKET_SIZE, LOW_PRIORITY, RELIABLE_ORDERED_WITH_ACK_RECEIPT, 0, packet->systemAddress, false);
					// Keep the stat from updating until the messages move to the thread or it quits right away
					nextStatTime=RakNet::GetTime()+1000;
				}
				if (packet->data[0]==ID_CONNECTION_LOST)
					printf("ID_CONNECTION_LOST from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_DISCONNECTION_NOTIFICATION)
					printf("ID_DISCONNECTION_NOTIFICATION from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_NEW_INCOMING_CONNECTION)
					printf("ID_NEW_INCOMING_CONNECTION from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
					printf("ID_CONNECTION_REQUEST_ACCEPTED from %s\n", packet->systemAddress.ToString());
			}

			if (kbhit())
			{
				char ch=getch();
				if (ch==' ')
				{
					printf("Sending medium priority message\n");
					char t[1];
					t[0]=(unsigned char) 254;
					server->Send(t, 1, MEDIUM_PRIORITY, RELIABLE_ORDERED, 1, UNASSIGNED_SYSTEM_ADDRESS, true);
				}
			}
		}
		if (client)
		{
			packet = client->Receive();
			while (packet)
			{
				if (packet->data[0]==ID_DOWNLOAD_PROGRESS)
				{
					RakNet::BitStream progressBS(packet->data, packet->length, false);
					progressBS.IgnoreBits(8); // ID_DOWNLOAD_PROGRESS
					unsigned int progress;
					unsigned int total;
					unsigned int partLength;

					// Disable endian swapping on reading this, as it's generated locally in ReliabilityLayer.cpp
					progressBS.ReadBits( (unsigned char* ) &progress, BYTES_TO_BITS(sizeof(progress)), true );
					progressBS.ReadBits( (unsigned char* ) &total, BYTES_TO_BITS(sizeof(total)), true );
					progressBS.ReadBits( (unsigned char* ) &partLength, BYTES_TO_BITS(sizeof(partLength)), true );

					printf("Progress: msgID=%i Progress %i/%i Partsize=%i\n",
						(unsigned char) packet->data[0],
						progress,
						total,
						partLength);
				}
				else if (packet->data[0]==255)
				{
					if (packet->length!=BIG_PACKET_SIZE)
					{
						printf("Test failed. %i bytes (wrong number of bytes).\n", packet->length);
						quit=true;
						break;
					}
					if (BIG_PACKET_SIZE<=100000)
					{
						for (int i=0; i < BIG_PACKET_SIZE; i++)
						{
							if  (packet->data[i]!=255-(i&255))
							{
								printf("Test failed. %i bytes (bad data).\n", packet->length);
								quit=true;
								break;
							}
						}
					}

					if (quit==false)
					{
						printf("Test succeeded. %i bytes.\n", packet->length);
						quit=true;
					}

				}
				else if (packet->data[0]==254)
				{
 					printf("Got high priority message.\n");
				}
				else if (packet->data[0]==ID_CONNECTION_LOST)
					printf("ID_CONNECTION_LOST from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_DISCONNECTION_NOTIFICATION)
					printf("ID_DISCONNECTION_NOTIFICATION from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_NEW_INCOMING_CONNECTION)
					printf("ID_NEW_INCOMING_CONNECTION from %s\n", packet->systemAddress.ToString());
				else if (packet->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
				{
					start=RakNet::GetTimeMS();
					printf("ID_CONNECTION_REQUEST_ACCEPTED from %s\n", packet->systemAddress.ToString());
				}

				client->DeallocatePacket(packet);
				packet = client->Receive();
			}
		}

		if (RakNet::GetTime() > nextStatTime)
		{
			nextStatTime=RakNet::GetTime()+1000;
			RakNetStatistics rssSender;
			RakNetStatistics rssReceiver;
			if (server)
			{
				unsigned int i;
				unsigned short numSystems;
				server->GetConnectionList(0,&numSystems);
				if (numSystems>0)
				{
					for (i=0; i < numSystems; i++)
					{
						server->GetStatistics(server->GetSystemAddressFromIndex(i), &rssSender);
						StatisticsToString(&rssSender, text,2);
						printf("==== System %i ====\n", i+1);
						printf("%s\n\n", text);
					}
				}
			}
			if (client && server==0)
			{
				client->GetStatistics(client->GetSystemAddressFromIndex(0), &rssReceiver);
				StatisticsToString(&rssReceiver, text,2);
				printf("%s\n\n", text);
			}
		}

		RakSleep(100);
	}
	stop=RakNet::GetTime();
	double seconds = (double)(stop-start)/1000.0;

	if (server)
	{
		RakNetStatistics *rssSender2=server->GetStatistics(server->GetSystemAddressFromIndex(0));
		StatisticsToString(rssSender2, text, 1);
		printf("%s", text);
	}

	printf("%i bytes per second (%.2f seconds). Press enter to quit\n", (int)((double)(BIG_PACKET_SIZE) / seconds ), seconds) ;
	gets(text);

	delete []text;
	RakNetworkFactory::DestroyRakPeerInterface(client);
	RakNetworkFactory::DestroyRakPeerInterface(server);

	return 0;
}
static int convert_variable_type(Dwarf_Die *vr_die,
				 struct probe_trace_arg *tvar,
				 const char *cast)
{
	struct probe_trace_arg_ref **ref_ptr = &tvar->ref;
	Dwarf_Die type;
	char buf[16];
	int bsize, boffs, total;
	int ret;

	
	if (cast && strcmp(cast, "string") != 0) {
		
		tvar->type = strdup(cast);
		return (tvar->type == NULL) ? -ENOMEM : 0;
	}

	bsize = dwarf_bitsize(vr_die);
	if (bsize > 0) {
		
		boffs = dwarf_bitoffset(vr_die);
		total = dwarf_bytesize(vr_die);
		if (boffs < 0 || total < 0)
			return -ENOENT;
		ret = snprintf(buf, 16, "b%d@%d/%zd", bsize, boffs,
				BYTES_TO_BITS(total));
		goto formatted;
	}

	if (die_get_real_type(vr_die, &type) == NULL) {
		pr_warning("Failed to get a type information of %s.\n",
			   dwarf_diename(vr_die));
		return -ENOENT;
	}

	pr_debug("%s type is %s.\n",
		 dwarf_diename(vr_die), dwarf_diename(&type));

	if (cast && strcmp(cast, "string") == 0) {	
		ret = dwarf_tag(&type);
		if (ret != DW_TAG_pointer_type &&
		    ret != DW_TAG_array_type) {
			pr_warning("Failed to cast into string: "
				   "%s(%s) is not a pointer nor array.\n",
				   dwarf_diename(vr_die), dwarf_diename(&type));
			return -EINVAL;
		}
		if (ret == DW_TAG_pointer_type) {
			if (die_get_real_type(&type, &type) == NULL) {
				pr_warning("Failed to get a type"
					   " information.\n");
				return -ENOENT;
			}
			while (*ref_ptr)
				ref_ptr = &(*ref_ptr)->next;
			
			*ref_ptr = zalloc(sizeof(struct probe_trace_arg_ref));
			if (*ref_ptr == NULL) {
				pr_warning("Out of memory error\n");
				return -ENOMEM;
			}
		}
		if (!die_compare_name(&type, "char") &&
		    !die_compare_name(&type, "unsigned char")) {
			pr_warning("Failed to cast into string: "
				   "%s is not (unsigned) char *.\n",
				   dwarf_diename(vr_die));
			return -EINVAL;
		}
		tvar->type = strdup(cast);
		return (tvar->type == NULL) ? -ENOMEM : 0;
	}

	ret = dwarf_bytesize(&type);
	if (ret <= 0)
		
		return 0;
	ret = BYTES_TO_BITS(ret);

	
	if (ret > MAX_BASIC_TYPE_BITS) {
		pr_info("%s exceeds max-bitwidth. Cut down to %d bits.\n",
			dwarf_diename(&type), MAX_BASIC_TYPE_BITS);
		ret = MAX_BASIC_TYPE_BITS;
	}
	ret = snprintf(buf, 16, "%c%d",
		       die_is_signed_type(&type) ? 's' : 'u', ret);

formatted:
	if (ret < 0 || ret >= 16) {
		if (ret >= 16)
			ret = -E2BIG;
		pr_warning("Failed to convert variable type: %s\n",
			   strerror(-ret));
		return ret;
	}
	tvar->type = strdup(buf);
	if (tvar->type == NULL)
		return -ENOMEM;
	return 0;
}
Example #23
0
PluginReceiveResult Router::OnReceive(Packet *packet)
{
	if (packet->data[0]==ID_ROUTE_AND_MULTICAST ||
		(packet->length>5 && packet->data[0]==ID_TIMESTAMP && packet->data[5]==ID_ROUTE_AND_MULTICAST))
	{
#ifdef _DO_PRINTF
		RAKNET_DEBUG_PRINTF("%i got routed message from %i\n", peer->GetExternalID(packet->systemAddress).port, packet->systemAddress.port);
#endif
		RakNetTime timestamp;
		PacketPriority priority;
		PacketReliability reliability;
		unsigned char orderingChannel;
		SystemAddress originalSender;
		RakNet::BitStream out;
		BitSize_t outStartingOffset;
		unsigned int payloadBitLength;
		unsigned payloadWriteByteOffset;
		RakNet::BitStream incomingBitstream(packet->data, packet->length, false);
		incomingBitstream.IgnoreBits(8);
		
		if (packet->data[0]==ID_TIMESTAMP)
		{
			incomingBitstream.Read(timestamp);
			out.Write((MessageID)ID_TIMESTAMP);
			out.Write(timestamp);
			incomingBitstream.IgnoreBits(8);
		}

		// Read the send parameters
		unsigned char c;
		incomingBitstream.ReadCompressed(c);
		priority=(PacketPriority)c;
		incomingBitstream.ReadCompressed(c);
		reliability=(PacketReliability)c;
		incomingBitstream.ReadCompressed(orderingChannel);
		incomingBitstream.Read(payloadBitLength);
		
		out.Write((MessageID)ID_ROUTE_AND_MULTICAST);
		out.WriteCompressed((unsigned char)priority);
		out.WriteCompressed((unsigned char)reliability);
		out.WriteCompressed((unsigned char)orderingChannel);
		out.Write(payloadBitLength);
		out.AlignWriteToByteBoundary();
		incomingBitstream.AlignReadToByteBoundary();
		payloadWriteByteOffset=(unsigned int) BITS_TO_BYTES(out.GetWriteOffset());
		out.Write(&incomingBitstream, payloadBitLength); // This write also does a read on incomingBitStream

		if (restrictByType)
		{
			RakNet::BitStream t(out.GetData()+payloadWriteByteOffset, sizeof(unsigned char), false);
			MessageID messageID;
			t.Read(messageID);
			if (allowedTypes.HasData(messageID)==false)
				return RR_STOP_PROCESSING_AND_DEALLOCATE; // Don't route restricted types
		}

		incomingBitstream.Read(originalSender);
		out.Write(originalSender);
		outStartingOffset=out.GetWriteOffset();

		// Deserialize the root
		bool hasData=false;
		SystemAddress recipient;
		unsigned short numberOfChildren;
		incomingBitstream.Read(hasData);
		incomingBitstream.Read(recipient); // This should be our own address
		if (incomingBitstream.ReadCompressed(numberOfChildren)==false)
		{
#ifdef _DEBUG
			RakAssert(0);
#endif
			return RR_STOP_PROCESSING_AND_DEALLOCATE;
		}

		unsigned childIndex;
		bool childHasData=false;
		SystemAddress childRecipient;
		unsigned short childNumberOfChildren;
		SystemAddress immediateRecipient;
		immediateRecipient=UNASSIGNED_SYSTEM_ADDRESS;
		int pendingNodeCount=0;

		for (childIndex=0; childIndex < numberOfChildren; childIndex++)
		{
			while (pendingNodeCount!=-1)
			{
				// Copy out the serialized subtree for this child
				incomingBitstream.Read(childHasData);
				incomingBitstream.Read(childRecipient);
				if (!incomingBitstream.ReadCompressed(childNumberOfChildren))
					return RR_STOP_PROCESSING_AND_DEALLOCATE;
				if (immediateRecipient==UNASSIGNED_SYSTEM_ADDRESS)
				{
					immediateRecipient=childRecipient;
				}

				pendingNodeCount+=childNumberOfChildren-1;

				out.Write(childHasData);
				out.Write(childRecipient);
				out.WriteCompressed(childNumberOfChildren);
			}

#ifdef _DO_PRINTF
			RAKNET_DEBUG_PRINTF("%i routing to %i\n", peer->GetExternalID(packet->systemAddress).port, immediateRecipient.port);
#endif

			// Send what we got so far
			SendUnified(&out, priority, reliability, orderingChannel, immediateRecipient, false);

			// Restart writing the per recipient data
			out.SetWriteOffset(outStartingOffset);

			// Reread the top level node
			immediateRecipient=UNASSIGNED_SYSTEM_ADDRESS;

			pendingNodeCount=0;

		}

		// Write the user payload to the packet struct if this is a destination and change the sender and return true
		if (hasData)
		{
#ifdef _DO_PRINTF
			RAKNET_DEBUG_PRINTF("%i returning payload to user\n", peer->GetExternalID(packet->systemAddress).port);
#endif

			if (packet->data[0]==ID_TIMESTAMP )
			{
				memcpy( packet->data + sizeof(RakNetTime)+sizeof(unsigned char), out.GetData()+payloadWriteByteOffset, BITS_TO_BYTES(payloadBitLength) );
				packet->bitSize=BYTES_TO_BITS(sizeof(RakNetTime)+sizeof(unsigned char))+payloadBitLength;
			}
			else
			{
				memcpy( packet->data, out.GetData()+payloadWriteByteOffset, BITS_TO_BYTES(payloadBitLength) );
				packet->bitSize=payloadBitLength;
			}
			packet->length=(unsigned int) BITS_TO_BYTES(packet->bitSize);
			packet->systemAddress.systemIndex=(SystemIndex)-1;
			packet->systemAddress=originalSender;

			return RR_CONTINUE_PROCESSING;
		}

		// Absorb
		return RR_STOP_PROCESSING_AND_DEALLOCATE;
	}

	return RR_CONTINUE_PROCESSING;
}
Example #24
0
size_t bt_btr_start(struct bt_btr *btr,
	struct bt_field_type *type, const uint8_t *buf,
	size_t offset, size_t packet_offset, size_t sz,
	enum bt_btr_status *status)
{
	assert(btr);
	assert(BYTES_TO_BITS(sz) >= offset);
	reset(btr);
	btr->buf.addr = buf;
	btr->buf.offset = offset;
	btr->buf.at = 0;
	btr->buf.packet_offset = packet_offset;
	btr->buf.buf_sz = sz;
	btr->buf.sz = BYTES_TO_BITS(sz) - offset;
	*status = BT_BTR_STATUS_OK;

	BT_LOGV("Starting decoding: btr-addr=%p, ft-addr=%p, "
		"buf-addr=%p, buf-size=%zu, offset=%zu, "
		"packet-offset=%zu",
		btr, type, buf, sz, offset, packet_offset);

	/* Set root type */
	if (is_compound_type(type)) {
		/* Compound type: push on visit stack */
		int stack_ret;

		if (btr->user.cbs.types.compound_begin) {
			BT_LOGV("Calling user function (compound, begin).");
			*status = btr->user.cbs.types.compound_begin(
				type, btr->user.data);
			BT_LOGV("User function returned: status=%s",
				bt_btr_status_string(*status));
			if (*status != BT_BTR_STATUS_OK) {
				BT_LOGW("User function failed: btr-addr=%p, status=%s",
					btr, bt_btr_status_string(*status));
				goto end;
			}
		}

		stack_ret = stack_push_with_len(btr, type);
		if (stack_ret) {
			/* stack_push_with_len() logs errors */
			*status = BT_BTR_STATUS_ERROR;
			goto end;
		}

		btr->state = BTR_STATE_ALIGN_COMPOUND;
	} else {
		/* Basic type: set as current basic type */
		btr->cur_basic_field_type = type;
		bt_get(btr->cur_basic_field_type);
		btr->state = BTR_STATE_ALIGN_BASIC;
	}

	/* Run the machine! */
	BT_LOGV_STR("Running the state machine.");

	while (true) {
		*status = handle_state(btr);
		if (*status != BT_BTR_STATUS_OK ||
				btr->state == BTR_STATE_DONE) {
			break;
		}
	}

	/* Update packet offset for next time */
	update_packet_offset(btr);

end:
	return btr->buf.at;
}
Example #25
0
int32_t psa_import_key_test(security_t caller)
{
    uint32_t         length, i;
    uint8_t          data[BUFFER_SIZE];
    const uint8_t    *key_data;
    psa_key_policy_t policy;
    psa_key_type_t   key_type;
    size_t           bits;
    int              num_checks = sizeof(check1)/sizeof(check1[0]);
    int32_t          status;

    /* Initialize the PSA crypto library*/
    status = val->crypto_function(VAL_CRYPTO_INIT);
    TEST_ASSERT_EQUAL(status, PSA_SUCCESS, TEST_CHECKPOINT_NUM(1));

    /* Set the key data buffer to the input base on algorithm */
    for (i = 0; i < num_checks; i++)
    {
        val->print(PRINT_TEST, "[Check %d] ", g_test_count++);
        val->print(PRINT_TEST, check1[i].test_desc, 0);

        /* Setting up the watchdog timer for each check */
        status = val->wd_reprogram_timer(WD_CRYPTO_TIMEOUT);
        TEST_ASSERT_EQUAL(status, VAL_STATUS_SUCCESS, TEST_CHECKPOINT_NUM(2));

        /* Initialize a key policy structure to a default that forbids all
         * usage of the key
         */
        val->crypto_function(VAL_CRYPTO_KEY_POLICY_INIT, &policy);

        if (PSA_KEY_TYPE_IS_RSA(check1[i].key_type))
        {
            if (check1[i].key_type == PSA_KEY_TYPE_RSA_KEYPAIR)
            {
                if (check1[i].expected_bit_length == BYTES_TO_BITS(384))
                    key_data = rsa_384_keypair;
                else if (check1[i].expected_bit_length == BYTES_TO_BITS(256))
                    key_data = rsa_256_keypair;
                else
                    return VAL_STATUS_INVALID;
            }
            else
            {
                if (check1[i].expected_bit_length == BYTES_TO_BITS(384))
                    key_data = rsa_384_keydata;
                else if (check1[i].expected_bit_length == BYTES_TO_BITS(256))
                    key_data = rsa_256_keydata;
                else
                    return VAL_STATUS_INVALID;
            }
        }
        else if (PSA_KEY_TYPE_IS_ECC(check1[i].key_type))
        {
            if (PSA_KEY_TYPE_IS_ECC_KEYPAIR(check1[i].key_type))
                key_data = ec_keypair;
            else
                key_data = ec_keydata;
        }
        else
            key_data = check1[i].key_data;

        /* Set the standard fields of a policy structure */
        val->crypto_function(VAL_CRYPTO_KEY_POLICY_SET_USAGE, &policy, check1[i].usage,
                                                                          check1[i].key_alg);

        /* Allocate a key slot for a transient key */
        status = val->crypto_function(VAL_CRYPTO_ALLOCATE_KEY, &check1[i].key_handle);
        TEST_ASSERT_EQUAL(status, PSA_SUCCESS, TEST_CHECKPOINT_NUM(3));

        /* Set the usage policy on a key slot */
        status = val->crypto_function(VAL_CRYPTO_SET_KEY_POLICY, check1[i].key_handle, &policy);
        TEST_ASSERT_EQUAL(status, PSA_SUCCESS, TEST_CHECKPOINT_NUM(4));

        /* Import the key data into the key slot */
        status = val->crypto_function(VAL_CRYPTO_IMPORT_KEY, check1[i].key_handle,
                                check1[i].key_type, key_data, check1[i].key_length);
        TEST_ASSERT_EQUAL(status, check1[i].expected_status, TEST_CHECKPOINT_NUM(5));

        if (check1[i].expected_status != PSA_SUCCESS)
            continue;

        /* Get basic metadata about a key */
        status = val->crypto_function(VAL_CRYPTO_GET_KEY_INFORMATION, check1[i].key_handle,
                                      &key_type, &bits);
        TEST_ASSERT_EQUAL(status, PSA_SUCCESS, TEST_CHECKPOINT_NUM(6));

        TEST_ASSERT_EQUAL(key_type, check1[i].key_type, TEST_CHECKPOINT_NUM(7));

        TEST_ASSERT_EQUAL(bits, check1[i].expected_bit_length, TEST_CHECKPOINT_NUM(8));

        /* Export a key in binary format */
        status = val->crypto_function(VAL_CRYPTO_EXPORT_KEY, check1[i].key_handle, data,
                                      BUFFER_SIZE, &length);
        TEST_ASSERT_EQUAL(status, PSA_SUCCESS, TEST_CHECKPOINT_NUM(9));

        TEST_ASSERT_EQUAL(length, check1[i].expected_key_length, TEST_CHECKPOINT_NUM(10));

        if (PSA_KEY_TYPE_IS_UNSTRUCTURED(check1[i].key_type))
        {
            TEST_ASSERT_MEMCMP(data, check1[i].key_data, length, TEST_CHECKPOINT_NUM(11));
        }
        else if (PSA_KEY_TYPE_IS_RSA(check1[i].key_type) || PSA_KEY_TYPE_IS_ECC(check1[i].key_type))
        {
            TEST_ASSERT_MEMCMP(key_data, data, length, TEST_CHECKPOINT_NUM(12));
        }
        else
        {
            return VAL_STATUS_INVALID;
        }
    }

    return VAL_STATUS_SUCCESS;
}