Example #1
0
void ProtocolGameBase::sendInventory()
{
	std::map<uint16_t, uint16_t> items = player->getAllItemsClientId();

	NetworkMessage msg;
	msg.addByte(0xF5);
	msg.add<uint16_t>(items.size() + 11);

	for (uint16_t i = 1; i <= 11; i++) {
		msg.add<uint16_t>(i);
		msg.addByte(0);
		msg.add<uint16_t>(1);

	}

	for (const auto& it : items) {
		msg.add<uint16_t>(it.first);
		msg.addByte(0);
		msg.add<uint16_t>(it.second);

	}

	writeToOutputBuffer(msg);

}
Example #2
0
	void SendMessage(MessageConnection *connection)
	{
		NetworkMessage *msg = connection->StartNewMessage(191 /*A custom message number*/, 
		                                                  4 + extraBytes + 4 /*size of this message in bytes*/);
		msg->priority = 100;
		msg->reliable = true;
		msg->inOrder = true;
		msg->contentID = 1;
		DataSerializer ds(msg->data, msg->Size());
		++lastMessageNumber;
		ds.Add<u32>(lastMessageNumber);

		u32 checksum = 0;
		for(int i = 0; i < extraBytes; ++i)
		{
			u8 byte = (u8)rand();
			ds.Add<u8>(byte);

			// Just run some bit-twiddling algorithm over all the bits to generate a checksum.
			checksum ^= byte;
			checksum <<= NumBitsSet(byte);
		}
		ds.Add<u32>(checksum);
		connection->EndAndQueueMessage(msg);
	}
Example #3
0
TEST_F(NetworkTest, SendMessageWhenMessageIsTooLong) {
  NetworkMessage message;
  message.resize(256);
  NetworkPtr network = Network::Create(system);

  EXPECT_THROW(network->SendMessage(13, message), exception::detail::MessageTooLongException);
}
Example #4
0
bool ProtocolOld::parseFirstPacket(NetworkMessage& msg)
{
	if(g_game.getGameState() == GAME_STATE_SHUTDOWN)
	{
		getConnection()->closeConnection();
		return false;
	}

	/*uint16_t clientOS =*/ msg.GetU16();
	uint16_t version = msg.GetU16();
	msg.SkipBytes(12);

	if(version <= 760)
		disconnectClient(0x0A, "Only clients with protocol " CLIENT_VERSION_STR " allowed!");

	if(!RSA_decrypt(msg))
	{
		getConnection()->closeConnection();
		return false;
	}

	uint32_t key[4];
	key[0] = msg.GetU32();
	key[1] = msg.GetU32();
	key[2] = msg.GetU32();
	key[3] = msg.GetU32();
	enableXTEAEncryption();
	setXTEAKey(key);

	if(version <= 822)
		disableChecksum();

	disconnectClient(0x0A, "Only clients with protocol " CLIENT_VERSION_STR " allowed!");
	return false;
}
Example #5
0
void ProtocolGameBase::sendChannel(uint16_t channelId, const std::string& channelName, const UsersMap* channelUsers, const InvitedMap* invitedUsers)
{
	NetworkMessage msg;
	msg.addByte(0xAC);

	msg.add<uint16_t>(channelId);
	msg.addString(channelName);

	if (channelUsers) {
		msg.add<uint16_t>(channelUsers->size());
		for (const auto& it : *channelUsers) {
			msg.addString(it.second->getName());
		}
	} else {
		msg.add<uint16_t>(0x00);
	}

	if (invitedUsers) {
		msg.add<uint16_t>(invitedUsers->size());
		for (const auto& it : *invitedUsers) {
			msg.addString(it.second->getName());
		}
	} else {
		msg.add<uint16_t>(0x00);
	}
	writeToOutputBuffer(msg);
}
Example #6
0
void RMENet::OnReceivePing(NetworkMessage *nmsg)
{
	// Send pong
	NetworkMessage* omsg = AllocMessage();
	omsg->AddByte(0x02);
	connection->Send(omsg);
}
	NetworkMessage* NetworkMessage::DeserializePacket( OS::StreamReader& s)
	{
		byte d[4];
		s.read(d, 4);
		NetworkMessageType v=(NetworkMessageType)core::BitConverter::ToUInt32(d);
		NetworkMessage* ret = 0;
		switch (v)
		{
		case NetworkMessageType::SpeedChange:
			ret = new SpeedChangeMessage();
			break;
		case NetworkMessageType::HeadChange:
			ret = new HeadChangeMessage();
			break;
		case NetworkMessageType::Stop:
			ret = new StopMessage();
			break;
		case NetworkMessageType::VideoImage:
			ret = new VideoImageMessage();
			break;
		}
		if (ret != 0)
			if(!ret->Deserialize(s))
			{
				delete ret;
				ret=0;
			}
		return ret;
	}
Example #8
0
void NetworkServer::BroadcastMessage(unsigned long id, bool reliable, bool inOrder, unsigned long priority, 
                                     unsigned long contentID, const char *data, size_t numBytes,
                                     MessageConnection *exclude)
{
	PolledTimer timer;
	Lockable<ConnectionMap>::LockType clientsLock = clients.Acquire();
	if (timer.MSecsElapsed() >= 50.f)
	{
		LOG(LogWaits, "NetworkServer::BroadcastMessage: Accessing the connection list took %f msecs.",
			timer.MSecsElapsed());
	}

	for(ConnectionMap::iterator iter = clientsLock->begin(); iter != clientsLock->end(); ++iter)
	{
		MessageConnection *connection = iter->second;
		assert(connection);
		if (connection == exclude || !connection->IsWriteOpen())
			continue;

		NetworkMessage *msg = connection->StartNewMessage(id, numBytes);
		msg->reliable = reliable;
		msg->inOrder = inOrder;
		msg->priority = priority;
		msg->contentID = contentID;
		assert(msg->data);
		assert(msg->Size() == numBytes);
		memcpy(msg->data, data, numBytes);
		connection->EndAndQueueMessage(msg);
	}
}
Example #9
0
/*! Receive a NetworkMessage. Workes like recv, but buffer and size is
    taken from the NetworkMessage
    \see Socket::recv
 */
int DgramSocket::recvFrom(NetworkMessage &msg,SocketAddress &from)
{
    NetworkMessage::Header hdr;
    peek(&hdr,sizeof(hdr));
    msg.setSize(osgntohl(hdr.size));
    return recvFrom(msg.getBuffer(),msg.getSize(),from);
}
Example #10
0
NetworkMessage *MessageConnection::StartNewMessage(unsigned long id, size_t numBytes)
{
    NetworkMessage *msg = AllocateNewMessage();
    if (!msg)
    {
        LOG(LogError, "MessageConnection::SendMessage: StartNewMessage failed! Discarding message send.");
        return 0; // Failed to allocate a new message. This is caused only by memory allocation issues.
    }

    msg->id = id;
    msg->reliable = false;
    msg->contentID = 0;
    msg->obsolete = false;

    // Give the new message the lowest priority by default.
    msg->priority = 0;

    // By default, the message is not fragmented. Later when admitting the message into the send queue, the need for
    // fragmentation is examined and this field will be updated if needed.
    msg->transfer = 0;

#ifdef KNET_NETWORK_PROFILING
    msg->profilerName = "";
#endif

    msg->Resize(numBytes);

    return msg;
}
void ProtocolSpectator::parseSpectatorSay(NetworkMessage& msg)
{
	SpeakClasses type = (SpeakClasses)msg.getByte();
	uint16_t channelId = 0;

	if (type == TALKTYPE_CHANNEL_Y) {
		channelId = msg.get<uint16_t>();
	} else {
		return;
	}

	const std::string text = msg.getString();

	if (text.length() > 255 || channelId != CHANNEL_CAST || !client) {
		return;
	}

	if (client) {
		if (client->isSpectatorMuted(spectatorId)) {
			sendTextMessage(TextMessage(MESSAGE_STATUS_SMALL, "You have been muted."));
			return;
		}

		if (parseCoomand(text)) {
			return;
		}

		g_dispatcher.addTask(createTask(std::bind(&ProtocolCaster::broadcastSpectatorMessage, client, spectatorName, text)));
	}
}
Example #12
0
void UdpMulticastChannel::respond_nack(const NackMessage& nack_msg )
{
    NetworkMessage* msg = outgoing->get_message(NetworkChannel::get_host_name(),nack_msg.message_num());
    for(int i = 0; i < nack_msg.missing_packets_size(); i++)
        this->sender->sync_send(msg->get_packet(nack_msg.missing_packets(i))->SerializeAsString());

}
void
newsoul::DistributedSocket::onMessageReceived(const MessageData * data)
{
    if (m_DataTimeout.isValid())
        newsoul()->reactor()->removeTimeout(m_DataTimeout);

  switch(data->type)
  {
    #define MAP_MESSAGE(ID, TYPE, EVENT) \
      case ID: \
      { \
        NNLOG("newsoul.messages.distributed", "Received distributed message " #TYPE "."); \
        TYPE msg; \
        msg.setDistributedSocket(this); \
        msg.parse_network_packet(data->data, data->length); \
        EVENT(&msg); \
        break; \
      }
    #include "distributedeventtable.h"
    #undef MAP_MESSAGE

    default:
        NNLOG("newsoul.distrib.warn", "Received unknown distributed message, type: %u, length: %u", data->type, data->length);
        NetworkMessage msg;
        msg.parse_network_packet(data->data, data->length);
  }
}
Example #14
0
void ProtocolOld::onRecvFirstMessage(NetworkMessage& msg)
{
	if(g_game.getGameState() == GAMESTATE_SHUTDOWN)
	{
		getConnection()->close();
		return;
	}

	msg.skip(2);
	uint16_t version = msg.get<uint16_t>();

	msg.skip(12);
	if(version <= 760)
		disconnectClient(0x0A, "Only clients with protocol " CLIENT_VERSION_STRING " allowed!");

	if(!RSA_decrypt(msg))
	{
		getConnection()->close();
		return;
	}

	uint32_t key[4] = {msg.get<uint32_t>(), msg.get<uint32_t>(), msg.get<uint32_t>(), msg.get<uint32_t>()};
	enableXTEAEncryption();
	setXTEAKey(key);

	if(version <= 822)
		disableChecksum();

	disconnectClient(0x0A, "Only clients with protocol " CLIENT_VERSION_STRING " allowed!");
}
Example #15
0
void ProtocolGameBase::sendCancelWalk()
{
	NetworkMessage msg;
	msg.addByte(0xB5);
	msg.addByte(player->getDirection());
	writeToOutputBuffer(msg);
}
Example #16
0
TEST_F(NetworkTest, RecvMessageTwoParts) {
  EXPECT_CALL(*system, Recv(13, _, 1, 0))
      .WillOnce(Invoke([](int, void *buffer, size_t, int) {
        char *buf = (char*) buffer;
        buf[0] = 5;
        return 1;
      }));
  EXPECT_CALL(*system, Recv(13, _, 5, 0))
      .WillOnce(Invoke([](int, void *buffer, size_t, int) {
        char *buf = (char*) buffer;
        strncpy(buf, "te", 2);
        return 2;
      }));
  EXPECT_CALL(*system, Recv(13, _, 3, 0))
      .WillOnce(Invoke([](int, void *buffer, size_t, int) {
        char *buf = (char*) buffer;
        strncpy(buf, "st", 3);
        return 3;
      }));
  EXPECT_CALL(*system, Poll(_, 1, detail::TimeoutSeconds * 1000))
      .WillOnce(Return(1))
      .WillOnce(Return(1))
      .WillOnce(Return(1));

  NetworkPtr network = Network::Create(system);

  NetworkMessage nm = network->RecvMessage(13);
  ASSERT_EQ(5, nm.size());
  EXPECT_STREQ(nm.data(), "test");
}
Example #17
0
	void process_message(TCPConnection * conn) {				
		NetworkMessage * msg = conn->getMessages()->front();
		// std::cout << "Client " << this << " Received Message: " << std::endl;
		msg->print();
		conn->getMessages()->pop_front();	

		this->send(new ClientJoinMessage("lolz", 90));
	}
Example #18
0
void ProtocolGameBase::sendMapDescription(const Position& pos)
{
	NetworkMessage msg;
	msg.addByte(0x64);
	msg.addPosition(player->getPosition());
	GetMapDescription(pos.x - 8, pos.y - 6, pos.z, 18, 14, msg);
	writeToOutputBuffer(msg);
}
Example #19
0
void MessageConnection::HandleInboundMessage(packet_id_t packetID, const char *data, size_t numBytes)
{
    AssertInWorkerThreadContext();

    if (!socket)
        return; // Ignore all messages from connections that have already died.

    assert(data && numBytes > 0);

    // Read the message ID.
    DataDeserializer reader(data, numBytes);
    message_id_t messageID = reader.ReadVLE<VLE8_16_32>(); ///\todo Check that there actually is enough space to read.
    if (messageID == DataDeserializer::VLEReadError)
    {
        LOG(LogError, "Error parsing messageID of a message in socket %s. Data size: %d bytes.", socket->ToString().c_str(), (int)numBytes);
        throw NetException("MessageConnection::HandleInboundMessage: Network error occurred when deserializing message ID VLE field!");
    }
    LOG(LogData, "Received message with ID %d and size %d from peer %s.", (int)packetID, (int)numBytes, socket->ToString().c_str());

    char str[256];
    sprintf(str, "messageIn.%u", (unsigned int)messageID);
    ADDEVENT(str, (float)reader.BytesLeft(), "bytes");

    // Pass the message to TCP/UDP -specific message handler.
    bool childHandledMessage = HandleMessage(packetID, messageID, data + reader.BytePos(), reader.BytesLeft());
    if (childHandledMessage)
        return; // If the derived class handled the message, no need to propagate it further.

    switch(messageID)
    {
    case MsgIdPingRequest:
        HandlePingRequestMessage(data + reader.BytePos(), reader.BytesLeft());
        break;
    case MsgIdPingReply:
        HandlePingReplyMessage(data + reader.BytePos(), reader.BytesLeft());
        break;
    default:
    {
        NetworkMessage *msg = AllocateNewMessage();
        msg->Resize(numBytes);
        assert(reader.BitPos() == 0);
        memcpy(msg->data, data + reader.BytePos(), reader.BytesLeft());
        msg->dataSize = reader.BytesLeft();
        msg->id = messageID;
        msg->contentID = 0;
        msg->receivedPacketID = packetID;
        bool success = inboundMessageQueue.Insert(msg);
        if (!success)
        {
            LOG(LogError, "Failed to add a new message of ID %d and size %dB to inbound queue! Queue was full.",
                (int)messageID, (int)msg->dataSize);
            FreeMessage(msg);
        }
    }
    break;
    }
}
Example #20
0
void ProtocolGameBase::AddPlayerSkills(NetworkMessage& msg)
{
	msg.addByte(0xA1);

	for (uint8_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) {
		msg.add<uint16_t>(std::min<int32_t>(player->getSkillLevel(i), std::numeric_limits<uint16_t>::max()));
		msg.add<uint16_t>(player->getBaseSkill(i));
		msg.addByte(player->getSkillPercent(i));
	}
}
Example #21
0
void ProtocolGameBase::AddCreatureLight(NetworkMessage& msg, const Creature* creature)
{
	LightInfo lightInfo;
	creature->getCreatureLight(lightInfo);

	msg.addByte(0x8D);
	msg.add<uint32_t>(creature->getID());
	msg.addByte((player->isAccessPlayer() ? 0xFF : lightInfo.level));
	msg.addByte(lightInfo.color);
}
Example #22
0
//tile
void ProtocolGameBase::RemoveTileThing(NetworkMessage& msg, const Position& pos, uint32_t stackpos)
{
	if (stackpos >= 10) {
		return;
	}

	msg.addByte(0x6C);
	msg.addPosition(pos);
	msg.addByte(stackpos);
}
Example #23
0
void LiveServer::UpdateOperation(int percent)
{
	for(PeerList::iterator citer = connected_clients.begin(); citer != connected_clients.end(); ++citer)
	{
		NetworkMessage* msg = AllocMessage();
		msg->AddByte(PACKET_UPDATE_OPERATION);
		msg->AddU32(percent);
		(*citer)->Send(msg);
	}
}
Example #24
0
void LiveServer::StartOperation(wxString msg)
{
	for(PeerList::iterator citer = connected_clients.begin(); citer != connected_clients.end(); ++citer)
	{
		NetworkMessage* nmsg = AllocMessage();
		nmsg->AddByte(PACKET_START_OPERATION);
		nmsg->AddString(nstr(msg));
		(*citer)->Send(nmsg);
	}
}
Example #25
0
void ProtocolGameBase::sendBasicData()
{
	NetworkMessage msg;
	msg.addByte(0x9F);
	msg.addByte(player->isPremium() ? 0x01 : 0x00);
	msg.add<uint32_t>(std::numeric_limits<uint32_t>::max());
	msg.addByte(player->getVocation()->getClientId());
	msg.add<uint16_t>(0x00);
	writeToOutputBuffer(msg);
}
Example #26
0
///---------------------------------------------------------------------------------
/// Join Request
///---------------------------------------------------------------------------------
NETWORK_MESSAGE_DEFINITION_WITH_OPTIONS( MSG_TYPE_JOIN_REQUEST, MO_RELIABLE )
{
    DeveloperConsole::WriteLine( "Join request from " + sender.m_addr.GetAddrStr(), INFO_TEXT_COLOR );

    char* id = nullptr;
    msg.ReadString( id );

    AddConnectionResult result = ACR_DENIED;
    NetworkConnection* conn = sender.m_session->AddConnection( sender.m_addr, std::string( id ), result );

    if (conn && result == ACR_ACCEPTED)
    {

        NetworkMessage acceptMsg( MSG_TYPE_JOIN_ACCEPT );

        uint8_t maxConnections = (uint8_t) sender.m_session->GetMaxConnections();
        acceptMsg.WriteBytes( (void*)&maxConnections, sizeof( maxConnections ) );

        uint8_t connIdx = conn->GetConnectionIndex();
        acceptMsg.WriteBytes( (void*)&connIdx, sizeof( connIdx ) );

        uint8_t hostIdx = 0;
        acceptMsg.WriteBytes( (void*)&hostIdx, sizeof( hostIdx ) );

        std::string hostID = sender.m_session->GetHost()->GetUniqueID();
        acceptMsg.WriteString( hostID.c_str() );

        uint8_t invalidIdx = CONNECTION_INVALID_INDEX;
        acceptMsg.WriteBytes( (void*)&invalidIdx, sizeof( invalidIdx ) );

        conn->AddMessage( acceptMsg );
    }
    else
    {
        uint8_t denyReason;
        NetworkMessage* denyMsg = new NetworkMessage( MSG_TYPE_JOIN_DENY );
        switch (result)
        {
        case ACR_DENIED:
            denyReason = 0;
            break;
        case ACR_FULL:
            denyReason = 1;
            break;
        case ACR_ID_TAKEN:
            denyReason = 2;
            break;
        default:
            break;
        }

        denyMsg->WriteBytes( (void*)&denyReason, sizeof( denyReason ) );
        sender.m_session->SendDirectMessage( denyMsg, &sender.m_addr );
    }
}
Example #27
0
void PlayerChat::sendThem(NetworkMessage & message, NetworkLink * but) const
{
    if (PreferencesManager::getInstance()->value("isClient",true).toBool())
        message.sendAll(but);
    else
    {
        NetworkLink * to = m_player->link();
        if (to != but)
            message.sendTo(to);
    }
}
Example #28
0
	void SendPingReplyMessage(MessageConnection *connection, const char *receivedPingData, size_t receivedPingDataNumBytes)
	{
		DataDeserializer dd(receivedPingData, receivedPingDataNumBytes);
		NetworkMessage *msg = connection->StartNewMessage(customPingReplyMessageId, 2);
		msg->priority = 100;
		msg->reliable = false;
		DataSerializer ds(msg->data, msg->Size());
		u16 pingNumber = dd.Read<u16>();
		ds.Add<u16>(pingNumber);
		connection->EndAndQueueMessage(msg);
		cout << "Received PING_" << pingNumber << ". Sent PONG_" << pingNumber << "." << endl;
	}
Example #29
0
	void SendPingMessage(MessageConnection *connection)
	{
		NetworkMessage *msg = connection->StartNewMessage(customPingMessageId, 2);
		msg->priority = 100;
		msg->reliable = false;
		DataSerializer ds(msg->data, msg->Size());
		++sentPingNumber;
		ds.Add<u16>(sentPingNumber);
		connection->EndAndQueueMessage(msg);
		pingSendTime = Clock::Tick();
		cout << "Sent PING_" << sentPingNumber << "." << endl;
	}
Example #30
0
void LiveServer::BroadcastChat(wxString speaker, wxString message)
{
	for(PeerList::iterator citer = connected_clients.begin(); citer != connected_clients.end(); ++citer)
	{
		NetworkMessage* nmsg = AllocMessage();
		nmsg->AddByte(PACKET_SERVER_TALK);
		nmsg->AddString(nstr(speaker));
		nmsg->AddString(nstr(message));
		(*citer)->Send(nmsg);
	}
	log->Chat(name, message);
}