Exemple #1
0
// Try to get a single packet from a stream of data.
// Returns 0 if the packet was successfully processed, or
// -1 on an error, in which case the state is unchanged.
static ssize_t
dataReceivedSingle(NetConnection *conn, const uint8 *data,
		size_t dataLen) {
	uint32 packetLen;
	PacketType type;
	int result;
	
	if (dataLen < sizeof (PacketHeader)) {
		// Incomplete packet. We'll have to wait for the rest.
		return 0;
	}
	
	packetLen = packetLength((const Packet *) data);
	type = packetType((const Packet *) data);

	if (!validPacketType(type)) {
		log_add(log_Warning, "Packet with invalid type %d received.\n", type);
		errno = EBADMSG;
		return -1;
	}

	if (packetLen < packetTypeData[type].len) {
		// Bad len field of packet.
		log_add(log_Warning, "Packet with bad length field received (type="
				"%s, lenfield=%d.\n", packetTypeData[type].name,
				packetLen);
		errno = EBADMSG;
		return -1;
	}

	if (dataLen < packetLen) {
		// Incomplete packet. We'll have to wait for the rest.
		return 0;
	}

#ifdef NETPLAY_STATISTICS
	NetConnection_getStatistics(conn)->packetsReceived++;
	NetConnection_getStatistics(conn)->packetTypeReceived[type]++;
#endif

#ifdef NETPLAY_DEBUG
	if (type != PACKET_BATTLEINPUT && type != PACKET_CHECKSUM) {
		// Reporting BattleInput and Checksum would get so spammy that it
		// would slow down the battle.
		log_add(log_Debug, "NETPLAY: [%d] <== Received packet of type %s.\n",
				NetConnection_getPlayerNr(conn), packetTypeData[type].name);
	}
#endif
	
	result = packetTypeData[type].handler(conn, data);
	if (result == -1) {
		// An error occured. errno is set by the handler.
		return -1;
	}

	return packetLen;
}
//-----------------------------------------------------------------------------
// checks the packetLength according to the data unit's buffer size
bool CCSDS::PACKET::Packet::checkPacketLength() const throw(UTIL::Exception)
//-----------------------------------------------------------------------------
{
  return (packetLength() == (bufferSize() - PRIMARY_HEADER_BYTE_SIZE - 1));
}
//-----------------------------------------------------------------------------
// sets the packetLength according to the data unit's buffer size
void CCSDS::PACKET::Packet::setPacketLength() throw(UTIL::Exception)
//-----------------------------------------------------------------------------
{
  packetLength(bufferSize() - PRIMARY_HEADER_BYTE_SIZE - 1);
}