[Patch 2/4] Network rework: packet writing, sending and cleanups

NetworkPacket.cpp:
* Remove some deprecated functions, we must use streaming interface
* m_data converted from u8* to std::vector<u8>
* Add an exporter to forge packet to Connection object
* implement operator << std::wstring. n
* implement operator << std::string
* dynamic resize when write packet content.
* fix string writing and performances.
* create ServerCommandFactory, used by client to get useful informations about packet processing (sending).
  * Reliability
  * Transmit channel
* Implement putRawString for some ugly char (_INIT packet), and use it.
* Many packet read and write migrated
* Implement oldForgePacket to interface writing with current connection
* fix U8/char/bool writing
* fix string writing and performances.
* add some missing functions
* Use v3s16 read instead of reading x,y,z separately
* Add irr::video::SColor support into packets
* Add some missing handlers
* Add a template function to increase offset
* Throw a serialization error on packet reading (must be improved)

PacketFactories:
* Create ServerCommandFactory, used by client to get useful informations about packet processing (sending).
* Create ClientCommandFactory, used by server to get useful informations about packet processing (sending).

Client.cpp:
* implement NetworkPacket ::Send interface.
* Move packet handlers to a dedicated file
* Remove Client::Send(SharedBuffer)

Server.cpp:
* implement NetworkPacket ::Send interface.
* Rewrite all packets using NetworkPacket
* Move packet handlers to a dedicated file
* Remove Server::Send(SharedBuffer)

ClientIface.cpp:
* Remove sendToAll(SharedBuffer<u8>)

Connection.hpp rework:
* Remove duplicate include
* Remove duplicate negation
* Remove a useless variable
* Improve code performance by using a m_peers_list instead of scanning m_peers map
* Remove Connection::Send(SharedBuffer)
* Fix useafterfree into NetworkPacket Sending
* Remove unused Connection::sendToAll

Test.cpp:
* Remove dead code
* Update tests to use NetworkPackets

Misc:
* add new wrappers to Send packets in client, using NetworkPacket
* Add NetworkPacket methods for Connection
* coding style fix
* dead code since changes cleanup
* Use v3s16 read instead of reading x,y,z separately in some packets
* Use different files to handle packets received by client and server
* Cleanup: Remove useless includes

ok @Zeno-
Tested by @Zeno- @VanessaE and @nerzhul on running servers
This commit is contained in:
Loic Blot 2015-01-16 11:37:49 +01:00
parent efa977518a
commit ed04e8e9e4
22 changed files with 3921 additions and 4182 deletions

@ -361,7 +361,6 @@ set(common_SRCS
cavegen.cpp cavegen.cpp
clientiface.cpp clientiface.cpp
collision.cpp collision.cpp
connection.cpp
content_abm.cpp content_abm.cpp
content_mapnode.cpp content_mapnode.cpp
content_nodemeta.cpp content_nodemeta.cpp
@ -429,9 +428,10 @@ set(common_SRCS
version.cpp version.cpp
voxel.cpp voxel.cpp
voxelalgorithms.cpp voxelalgorithms.cpp
network/connection.cpp
network/networkpacket.cpp network/networkpacket.cpp
network/packethandlers/server.cpp
network/serveropcodes.cpp network/serveropcodes.cpp
network/toserverpacket.cpp
${JTHREAD_SRCS} ${JTHREAD_SRCS}
${common_SCRIPT_SRCS} ${common_SCRIPT_SRCS}
${UTIL_SRCS} ${UTIL_SRCS}
@ -496,7 +496,7 @@ set(minetest_SRCS
wieldmesh.cpp wieldmesh.cpp
client/clientlauncher.cpp client/clientlauncher.cpp
network/clientopcodes.cpp network/clientopcodes.cpp
network/toclientpacket.cpp network/packethandlers/client.cpp
${minetest_SCRIPT_SRCS} ${minetest_SCRIPT_SRCS}
) )
list(SORT minetest_SRCS) list(SORT minetest_SRCS)

File diff suppressed because it is too large Load Diff

@ -20,7 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#ifndef CLIENT_HEADER #ifndef CLIENT_HEADER
#define CLIENT_HEADER #define CLIENT_HEADER
#include "connection.h" #include "network/connection.h"
#include "environment.h" #include "environment.h"
#include "irrlichttypes_extrabloated.h" #include "irrlichttypes_extrabloated.h"
#include "jthread/jmutex.h" #include "jthread/jmutex.h"
@ -34,7 +34,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "localplayer.h" #include "localplayer.h"
#include "hud.h" #include "hud.h"
#include "particles.h" #include "particles.h"
#include "network/toclientpacket.h" #include "network/networkpacket.h"
struct MeshMakeData; struct MeshMakeData;
class MapBlockMesh; class MapBlockMesh;
@ -346,57 +346,57 @@ public:
* Command Handlers * Command Handlers
*/ */
void handleCommand(ToClientPacket* pkt); void handleCommand(NetworkPacket* pkt);
void handleCommand_Null(ToClientPacket* pkt) {}; void handleCommand_Null(NetworkPacket* pkt) {};
void handleCommand_Deprecated(ToClientPacket* pkt); void handleCommand_Deprecated(NetworkPacket* pkt);
void handleCommand_Init(ToClientPacket* pkt); void handleCommand_Init(NetworkPacket* pkt);
void handleCommand_AccessDenied(ToClientPacket* pkt); void handleCommand_AccessDenied(NetworkPacket* pkt);
void handleCommand_RemoveNode(ToClientPacket* pkt); void handleCommand_RemoveNode(NetworkPacket* pkt);
void handleCommand_AddNode(ToClientPacket* pkt); void handleCommand_AddNode(NetworkPacket* pkt);
void handleCommand_BlockData(ToClientPacket* pkt); void handleCommand_BlockData(NetworkPacket* pkt);
void handleCommand_Inventory(ToClientPacket* pkt); void handleCommand_Inventory(NetworkPacket* pkt);
void handleCommand_TimeOfDay(ToClientPacket* pkt); void handleCommand_TimeOfDay(NetworkPacket* pkt);
void handleCommand_ChatMessage(ToClientPacket* pkt); void handleCommand_ChatMessage(NetworkPacket* pkt);
void handleCommand_ActiveObjectRemoveAdd(ToClientPacket* pkt); void handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt);
void handleCommand_ActiveObjectMessages(ToClientPacket* pkt); void handleCommand_ActiveObjectMessages(NetworkPacket* pkt);
void handleCommand_Movement(ToClientPacket* pkt); void handleCommand_Movement(NetworkPacket* pkt);
void handleCommand_HP(ToClientPacket* pkt); void handleCommand_HP(NetworkPacket* pkt);
void handleCommand_Breath(ToClientPacket* pkt); void handleCommand_Breath(NetworkPacket* pkt);
void handleCommand_MovePlayer(ToClientPacket* pkt); void handleCommand_MovePlayer(NetworkPacket* pkt);
void handleCommand_PlayerItem(ToClientPacket* pkt); void handleCommand_PlayerItem(NetworkPacket* pkt);
void handleCommand_DeathScreen(ToClientPacket* pkt); void handleCommand_DeathScreen(NetworkPacket* pkt);
void handleCommand_AnnounceMedia(ToClientPacket* pkt); void handleCommand_AnnounceMedia(NetworkPacket* pkt);
void handleCommand_Media(ToClientPacket* pkt); void handleCommand_Media(NetworkPacket* pkt);
void handleCommand_ToolDef(ToClientPacket* pkt); void handleCommand_ToolDef(NetworkPacket* pkt);
void handleCommand_NodeDef(ToClientPacket* pkt); void handleCommand_NodeDef(NetworkPacket* pkt);
void handleCommand_CraftItemDef(ToClientPacket* pkt); void handleCommand_CraftItemDef(NetworkPacket* pkt);
void handleCommand_ItemDef(ToClientPacket* pkt); void handleCommand_ItemDef(NetworkPacket* pkt);
void handleCommand_PlaySound(ToClientPacket* pkt); void handleCommand_PlaySound(NetworkPacket* pkt);
void handleCommand_StopSound(ToClientPacket* pkt); void handleCommand_StopSound(NetworkPacket* pkt);
void handleCommand_Privileges(ToClientPacket* pkt); void handleCommand_Privileges(NetworkPacket* pkt);
void handleCommand_InventoryFormSpec(ToClientPacket* pkt); void handleCommand_InventoryFormSpec(NetworkPacket* pkt);
void handleCommand_DetachedInventory(ToClientPacket* pkt); void handleCommand_DetachedInventory(NetworkPacket* pkt);
void handleCommand_ShowFormSpec(ToClientPacket* pkt); void handleCommand_ShowFormSpec(NetworkPacket* pkt);
void handleCommand_SpawnParticle(ToClientPacket* pkt); void handleCommand_SpawnParticle(NetworkPacket* pkt);
void handleCommand_AddParticleSpawner(ToClientPacket* pkt); void handleCommand_AddParticleSpawner(NetworkPacket* pkt);
void handleCommand_DeleteParticleSpawner(ToClientPacket* pkt); void handleCommand_DeleteParticleSpawner(NetworkPacket* pkt);
void handleCommand_HudAdd(ToClientPacket* pkt); void handleCommand_HudAdd(NetworkPacket* pkt);
void handleCommand_HudRemove(ToClientPacket* pkt); void handleCommand_HudRemove(NetworkPacket* pkt);
void handleCommand_HudChange(ToClientPacket* pkt); void handleCommand_HudChange(NetworkPacket* pkt);
void handleCommand_HudSetFlags(ToClientPacket* pkt); void handleCommand_HudSetFlags(NetworkPacket* pkt);
void handleCommand_HudSetParam(ToClientPacket* pkt); void handleCommand_HudSetParam(NetworkPacket* pkt);
void handleCommand_HudSetSky(ToClientPacket* pkt); void handleCommand_HudSetSky(NetworkPacket* pkt);
void handleCommand_OverrideDayNightRatio(ToClientPacket* pkt); void handleCommand_OverrideDayNightRatio(NetworkPacket* pkt);
void handleCommand_LocalPlayerAnimations(ToClientPacket* pkt); void handleCommand_LocalPlayerAnimations(NetworkPacket* pkt);
void handleCommand_EyeOffset(ToClientPacket* pkt); void handleCommand_EyeOffset(NetworkPacket* pkt);
void ProcessData(u8 *data, u32 datasize, u16 sender_peer_id); void ProcessData(u8 *data, u32 datasize, u16 sender_peer_id);
// Returns true if something was received // Returns true if something was received
bool AsyncProcessPacket(); bool AsyncProcessPacket();
bool AsyncProcessData(); bool AsyncProcessData();
void Send(u16 channelnum, SharedBuffer<u8> data, bool reliable); void Send(NetworkPacket* pkt);
void interact(u8 action, const PointedThing& pointed); void interact(u8 action, const PointedThing& pointed);

@ -25,7 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "player.h" #include "player.h"
#include "settings.h" #include "settings.h"
#include "mapblock.h" #include "mapblock.h"
#include "connection.h" #include "network/connection.h"
#include "environment.h" #include "environment.h"
#include "map.h" #include "map.h"
#include "emerge.h" #include "emerge.h"
@ -625,27 +625,30 @@ void ClientInterface::UpdatePlayerList()
} }
} }
void ClientInterface::send(u16 peer_id,u8 channelnum, void ClientInterface::send(u16 peer_id, u8 channelnum,
SharedBuffer<u8> data, bool reliable) NetworkPacket* pkt, bool reliable, bool deletepkt)
{ {
m_con->Send(peer_id, channelnum, data, reliable); m_con->Send(peer_id, channelnum, pkt, reliable);
if (deletepkt)
delete pkt;
} }
void ClientInterface::sendToAll(u16 channelnum, void ClientInterface::sendToAll(u16 channelnum,
SharedBuffer<u8> data, bool reliable) NetworkPacket* pkt, bool reliable)
{ {
JMutexAutoLock clientslock(m_clients_mutex); JMutexAutoLock clientslock(m_clients_mutex);
for(std::map<u16, RemoteClient*>::iterator for(std::map<u16, RemoteClient*>::iterator
i = m_clients.begin(); i = m_clients.begin();
i != m_clients.end(); ++i) i != m_clients.end(); ++i) {
{
RemoteClient *client = i->second; RemoteClient *client = i->second;
if (client->net_proto_version != 0) if (client->net_proto_version != 0) {
{ m_con->Send(client->peer_id, channelnum, pkt, reliable);
m_con->Send(client->peer_id, channelnum, data, reliable);
} }
} }
delete pkt;
} }
RemoteClient* ClientInterface::getClientNoEx(u16 peer_id, ClientState state_min) RemoteClient* ClientInterface::getClientNoEx(u16 peer_id, ClientState state_min)

@ -24,6 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "constants.h" #include "constants.h"
#include "serialization.h" // for SER_FMT_VER_INVALID #include "serialization.h" // for SER_FMT_VER_INVALID
#include "jthread/jmutex.h" #include "jthread/jmutex.h"
#include "network/networkpacket.h"
#include <list> #include <list>
#include <vector> #include <vector>
@ -393,10 +394,10 @@ public:
std::vector<std::string> getPlayerNames(); std::vector<std::string> getPlayerNames();
/* send message to client */ /* send message to client */
void send(u16 peer_id, u8 channelnum, SharedBuffer<u8> data, bool reliable); void send(u16 peer_id, u8 channelnum, NetworkPacket* pkt, bool reliable, bool deletepkt=true);
/* send to all clients */ /* send to all clients */
void sendToAll(u16 channelnum, SharedBuffer<u8> data, bool reliable); void sendToAll(u16 channelnum, NetworkPacket* pkt, bool reliable);
/* delete a client */ /* delete a client */
void DeleteClient(u16 peer_id); void DeleteClient(u16 peer_id);

@ -108,3 +108,77 @@ const ToClientCommandHandler toClientCommandTable[TOCLIENT_NUM_MSG_TYPES] =
{ "TOCLIENT_LOCAL_PLAYER_ANIMATIONS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_LocalPlayerAnimations }, // 0x51 { "TOCLIENT_LOCAL_PLAYER_ANIMATIONS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_LocalPlayerAnimations }, // 0x51
{ "TOCLIENT_EYE_OFFSET", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_EyeOffset }, // 0x52 { "TOCLIENT_EYE_OFFSET", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_EyeOffset }, // 0x52
}; };
const static ServerCommandFactory null_command_factory = { "TOSERVER_NULL", 0, false };
const ServerCommandFactory serverCommandFactoryTable[TOSERVER_NUM_MSG_TYPES] =
{
null_command_factory, // 0x00
null_command_factory, // 0x01
null_command_factory, // 0x02
null_command_factory, // 0x03
null_command_factory, // 0x04
null_command_factory, // 0x05
null_command_factory, // 0x06
null_command_factory, // 0x07
null_command_factory, // 0x08
null_command_factory, // 0x09
null_command_factory, // 0x0a
null_command_factory, // 0x0b
null_command_factory, // 0x0c
null_command_factory, // 0x0d
null_command_factory, // 0x0e
null_command_factory, // 0x0f
{ "TOSERVER_INIT", 1, false }, // 0x10
{ "TOSERVER_INIT2", 1, true }, // 0x11
null_command_factory, // 0x12
null_command_factory, // 0x13
null_command_factory, // 0x14
null_command_factory, // 0x15
null_command_factory, // 0x16
null_command_factory, // 0x17
null_command_factory, // 0x18
null_command_factory, // 0x19
null_command_factory, // 0x1a
null_command_factory, // 0x1b
null_command_factory, // 0x1c
null_command_factory, // 0x1d
null_command_factory, // 0x1e
null_command_factory, // 0x1f
null_command_factory, // 0x20
null_command_factory, // 0x21
null_command_factory, // 0x22
{ "TOSERVER_PLAYERPOS", 0, false }, // 0x23
{ "TOSERVER_GOTBLOCKS", 2, true }, // 0x24
{ "TOSERVER_DELETEDBLOCKS", 2, true }, // 0x25
null_command_factory, // 0x26
{ "TOSERVER_CLICK_OBJECT", 0, false }, // 0x27
{ "TOSERVER_GROUND_ACTION", 0, false }, // 0x28
{ "TOSERVER_RELEASE", 0, false }, // 0x29
null_command_factory, // 0x2a
null_command_factory, // 0x2b
null_command_factory, // 0x2c
null_command_factory, // 0x2d
null_command_factory, // 0x2e
null_command_factory, // 0x2f
{ "TOSERVER_SIGNTEXT", 0, false }, // 0x30
{ "TOSERVER_INVENTORY_ACTION", 0, true }, // 0x31
{ "TOSERVER_CHAT_MESSAGE", 0, true }, // 0x32
{ "TOSERVER_SIGNNODETEXT", 0, false }, // 0x33
{ "TOSERVER_CLICK_ACTIVEOBJECT", 0, false }, // 0x34
{ "TOSERVER_DAMAGE", 0, true }, // 0x35
{ "TOSERVER_PASSWORD", 0, true }, // 0x36
{ "TOSERVER_PLAYERITEM", 0, true }, // 0x37
{ "TOSERVER_RESPAWN", 0, true }, // 0x38
{ "TOSERVER_INTERACT", 0, true }, // 0x39
{ "TOSERVER_REMOVED_SOUNDS", 1, true }, // 0x3a
{ "TOSERVER_NODEMETA_FIELDS", 0, true }, // 0x3b
{ "TOSERVER_INVENTORY_FIELDS", 0, true }, // 0x3c
null_command_factory, // 0x3d
null_command_factory, // 0x3e
null_command_factory, // 0x3f
{ "TOSERVER_REQUEST_MEDIA", 1, true }, // 0x40
{ "TOSERVER_RECEIVED_MEDIA", 1, true }, // 0x41
{ "TOSERVER_BREATH", 0, true }, // 0x42
{ "TOSERVER_CLIENT_READY", 0, true }, // 0x43
};

@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "client.h" #include "client.h"
#include "networkprotocol.h" #include "networkprotocol.h"
#include "toclientpacket.h" #include "networkpacket.h"
enum ToClientConnectionState { enum ToClientConnectionState {
TOCLIENT_STATE_NOT_CONNECTED, TOCLIENT_STATE_NOT_CONNECTED,
@ -33,11 +33,20 @@ enum ToClientConnectionState {
struct ToClientCommandHandler struct ToClientCommandHandler
{ {
char const* name; const char* name;
ToClientConnectionState state; ToClientConnectionState state;
void (Client::*handler)(ToClientPacket* pkt); void (Client::*handler)(NetworkPacket* pkt);
};
struct ServerCommandFactory
{
const char* name;
u16 channel;
bool reliable;
}; };
extern const ToClientCommandHandler toClientCommandTable[TOCLIENT_NUM_MSG_TYPES]; extern const ToClientCommandHandler toClientCommandTable[TOCLIENT_NUM_MSG_TYPES];
extern const ServerCommandFactory serverCommandFactoryTable[TOSERVER_NUM_MSG_TYPES];
#endif #endif

@ -29,7 +29,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "util/string.h" #include "util/string.h"
#include "settings.h" #include "settings.h"
#include "profiler.h" #include "profiler.h"
#include "main.h" // for profiling
namespace con namespace con
{ {
@ -134,7 +133,7 @@ std::list<SharedBuffer<u8> > makeSplitPacket(
u16 chunk_count = 0; u16 chunk_count = 0;
do{ do{
end = start + maximum_data_size - 1; end = start + maximum_data_size - 1;
if(end > data.getSize() - 1) if (end > data.getSize() - 1)
end = data.getSize() - 1; end = data.getSize() - 1;
u32 payload_size = end - start + 1; u32 payload_size = end - start + 1;
@ -173,7 +172,7 @@ std::list<SharedBuffer<u8> > makeAutoSplitPacket(
{ {
u32 original_header_size = 1; u32 original_header_size = 1;
std::list<SharedBuffer<u8> > list; std::list<SharedBuffer<u8> > list;
if(data.getSize() + original_header_size > chunksize_max) if (data.getSize() + original_header_size > chunksize_max)
{ {
list = makeSplitPacket(data, chunksize_max, split_seqnum); list = makeSplitPacket(data, chunksize_max, split_seqnum);
split_seqnum++; split_seqnum++;
@ -246,7 +245,7 @@ RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1])); u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
/*dout_con<<"findPacket(): finding seqnum="<<seqnum /*dout_con<<"findPacket(): finding seqnum="<<seqnum
<<", comparing to s="<<s<<std::endl;*/ <<", comparing to s="<<s<<std::endl;*/
if(s == seqnum) if (s == seqnum)
break; break;
} }
return i; return i;
@ -258,7 +257,7 @@ RPBSearchResult ReliablePacketBuffer::notFound()
bool ReliablePacketBuffer::getFirstSeqnum(u16& result) bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
{ {
JMutexAutoLock listlock(m_list_mutex); JMutexAutoLock listlock(m_list_mutex);
if(m_list.empty()) if (m_list.empty())
return false; return false;
BufferedPacket p = *m_list.begin(); BufferedPacket p = *m_list.begin();
result = readU16(&p.data[BASE_HEADER_SIZE+1]); result = readU16(&p.data[BASE_HEADER_SIZE+1]);
@ -268,7 +267,7 @@ bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
BufferedPacket ReliablePacketBuffer::popFirst() BufferedPacket ReliablePacketBuffer::popFirst()
{ {
JMutexAutoLock listlock(m_list_mutex); JMutexAutoLock listlock(m_list_mutex);
if(m_list.empty()) if (m_list.empty())
throw NotFoundException("Buffer is empty"); throw NotFoundException("Buffer is empty");
BufferedPacket p = *m_list.begin(); BufferedPacket p = *m_list.begin();
m_list.erase(m_list.begin()); m_list.erase(m_list.begin());
@ -286,7 +285,7 @@ BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
{ {
JMutexAutoLock listlock(m_list_mutex); JMutexAutoLock listlock(m_list_mutex);
RPBSearchResult r = findPacket(seqnum); RPBSearchResult r = findPacket(seqnum);
if(r == notFound()){ if (r == notFound()) {
LOG(dout_con<<"Sequence number: " << seqnum LOG(dout_con<<"Sequence number: " << seqnum
<< " not found in reliable buffer"<<std::endl); << " not found in reliable buffer"<<std::endl);
throw NotFoundException("seqnum not found in buffer"); throw NotFoundException("seqnum not found in buffer");
@ -326,7 +325,7 @@ void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
// Find the right place for the packet and insert it there // Find the right place for the packet and insert it there
// If list is empty, just add it // If list is empty, just add it
if(m_list.empty()) if (m_list.empty())
{ {
m_list.push_back(p); m_list.push_back(p);
m_oldest_non_answered_ack = seqnum; m_oldest_non_answered_ack = seqnum;
@ -417,7 +416,7 @@ std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
for(std::list<BufferedPacket>::iterator i = m_list.begin(); for(std::list<BufferedPacket>::iterator i = m_list.begin();
i != m_list.end(); ++i) i != m_list.end(); ++i)
{ {
if(i->time >= timeout) { if (i->time >= timeout) {
timed_outs.push_back(*i); timed_outs.push_back(*i);
//this packet will be sent right afterwards reset timeout here //this packet will be sent right afterwards reset timeout here
@ -458,7 +457,7 @@ SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]); u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
// Add if doesn't exist // Add if doesn't exist
if(m_buf.find(seqnum) == m_buf.end()) if (m_buf.find(seqnum) == m_buf.end())
{ {
IncomingSplitPacket *sp = new IncomingSplitPacket(); IncomingSplitPacket *sp = new IncomingSplitPacket();
sp->chunk_count = chunk_count; sp->chunk_count = chunk_count;
@ -469,11 +468,11 @@ SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
IncomingSplitPacket *sp = m_buf[seqnum]; IncomingSplitPacket *sp = m_buf[seqnum];
// TODO: These errors should be thrown or something? Dunno. // TODO: These errors should be thrown or something? Dunno.
if(chunk_count != sp->chunk_count) if (chunk_count != sp->chunk_count)
LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
<<" != sp->chunk_count="<<sp->chunk_count <<" != sp->chunk_count="<<sp->chunk_count
<<std::endl); <<std::endl);
if(reliable != sp->reliable) if (reliable != sp->reliable)
LOG(derr_con<<"Connection: WARNING: reliable="<<reliable LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
<<" != sp->reliable="<<sp->reliable <<" != sp->reliable="<<sp->reliable
<<std::endl); <<std::endl);
@ -481,7 +480,7 @@ SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
// If chunk already exists, ignore it. // If chunk already exists, ignore it.
// Sometimes two identical packets may arrive when there is network // Sometimes two identical packets may arrive when there is network
// lag and the server re-sends stuff. // lag and the server re-sends stuff.
if(sp->chunks.find(chunk_num) != sp->chunks.end()) if (sp->chunks.find(chunk_num) != sp->chunks.end())
return SharedBuffer<u8>(); return SharedBuffer<u8>();
// Cut chunk data out of packet // Cut chunk data out of packet
@ -493,7 +492,7 @@ SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
sp->chunks[chunk_num] = chunkdata; sp->chunks[chunk_num] = chunkdata;
// If not all chunks are received, return empty buffer // If not all chunks are received, return empty buffer
if(sp->allReceived() == false) if (sp->allReceived() == false)
return SharedBuffer<u8>(); return SharedBuffer<u8>();
// Calculate total size // Calculate total size
@ -533,10 +532,10 @@ void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
{ {
IncomingSplitPacket *p = i->second; IncomingSplitPacket *p = i->second;
// Reliable ones are not removed by timeout // Reliable ones are not removed by timeout
if(p->reliable == true) if (p->reliable == true)
continue; continue;
p->time += dtime; p->time += dtime;
if(p->time >= timeout) if (p->time >= timeout)
remove_queue.push_back(i->first); remove_queue.push_back(i->first);
} }
} }
@ -919,7 +918,7 @@ void Peer::RTTStatistics(float rtt, std::string profiler_id,
m_rtt.max_rtt = rtt; m_rtt.max_rtt = rtt;
/* do average calculation */ /* do average calculation */
if(m_rtt.avg_rtt < 0.0) if (m_rtt.avg_rtt < 0.0)
m_rtt.avg_rtt = rtt; m_rtt.avg_rtt = rtt;
else else
m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) + m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
@ -941,7 +940,7 @@ void Peer::RTTStatistics(float rtt, std::string profiler_id,
if (jitter >= m_rtt.jitter_max) if (jitter >= m_rtt.jitter_max)
m_rtt.jitter_max = jitter; m_rtt.jitter_max = jitter;
if(m_rtt.jitter_avg < 0.0) if (m_rtt.jitter_avg < 0.0)
m_rtt.jitter_avg = jitter; m_rtt.jitter_avg = jitter;
else else
m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) + m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
@ -1027,9 +1026,9 @@ void UDPPeer::reportRTT(float rtt)
RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10); RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR; float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
if(timeout < RESEND_TIMEOUT_MIN) if (timeout < RESEND_TIMEOUT_MIN)
timeout = RESEND_TIMEOUT_MIN; timeout = RESEND_TIMEOUT_MIN;
if(timeout > RESEND_TIMEOUT_MAX) if (timeout > RESEND_TIMEOUT_MAX)
timeout = RESEND_TIMEOUT_MAX; timeout = RESEND_TIMEOUT_MAX;
JMutexAutoLock usage_lock(m_exclusive_access_mutex); JMutexAutoLock usage_lock(m_exclusive_access_mutex);
@ -1039,7 +1038,7 @@ void UDPPeer::reportRTT(float rtt)
bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data) bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
{ {
m_ping_timer += dtime; m_ping_timer += dtime;
if(m_ping_timer >= PING_TIMEOUT) if (m_ping_timer >= PING_TIMEOUT)
{ {
// Create and send PING packet // Create and send PING packet
writeU8(&data[0], TYPE_CONTROL); writeU8(&data[0], TYPE_CONTROL);
@ -1358,7 +1357,7 @@ void ConnectionSendThread::runTimeouts(float dtime)
if (!peer) if (!peer)
continue; continue;
if(dynamic_cast<UDPPeer*>(&peer) == 0) if (dynamic_cast<UDPPeer*>(&peer) == 0)
continue; continue;
PROFILE(std::stringstream peerIdentifier); PROFILE(std::stringstream peerIdentifier);
@ -1371,7 +1370,7 @@ void ConnectionSendThread::runTimeouts(float dtime)
/* /*
Check peer timeout Check peer timeout
*/ */
if(peer->isTimedOut(m_timeout)) if (peer->isTimedOut(m_timeout))
{ {
infostream<<m_connection->getDesc() infostream<<m_connection->getDesc()
<<"RunTimeouts(): Peer "<<peer->id <<"RunTimeouts(): Peer "<<peer->id
@ -1477,7 +1476,7 @@ void ConnectionSendThread::rawSend(const BufferedPacket &packet)
LOG(dout_con <<m_connection->getDesc() LOG(dout_con <<m_connection->getDesc()
<< " rawSend: " << packet.data.getSize() << " rawSend: " << packet.data.getSize()
<< " bytes sent" << std::endl); << " bytes sent" << std::endl);
} catch(SendFailedException &e){ } catch(SendFailedException &e) {
LOG(derr_con<<m_connection->getDesc() LOG(derr_con<<m_connection->getDesc()
<<"Connection::rawSend(): SendFailedException: " <<"Connection::rawSend(): SendFailedException: "
<<packet.address.serializeString()<<std::endl); <<packet.address.serializeString()<<std::endl);
@ -1509,7 +1508,7 @@ bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
SharedBuffer<u8> data, bool reliable) SharedBuffer<u8> data, bool reliable)
{ {
PeerHelper peer = m_connection->getPeerNoEx(peer_id); PeerHelper peer = m_connection->getPeerNoEx(peer_id);
if(!peer) { if (!peer) {
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
<<" INFO: dropped packet for non existent peer_id: " <<" INFO: dropped packet for non existent peer_id: "
<< peer_id << std::endl); << peer_id << std::endl);
@ -1518,7 +1517,7 @@ bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
} }
Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]); Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
if(reliable) if (reliable)
{ {
bool have_sequence_number_for_raw_packet = true; bool have_sequence_number_for_raw_packet = true;
u16 seqnum = u16 seqnum =
@ -1586,7 +1585,7 @@ void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
{ {
assert(c.reliable); assert(c.reliable);
switch(c.type){ switch(c.type) {
case CONNCMD_NONE: case CONNCMD_NONE:
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
<<"UDP processing reliable CONNCMD_NONE"<<std::endl); <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
@ -1640,7 +1639,7 @@ void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
{ {
assert(!c.reliable); assert(!c.reliable);
switch(c.type){ switch(c.type) {
case CONNCMD_NONE: case CONNCMD_NONE:
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
<<" UDP processing CONNCMD_NONE"<<std::endl); <<" UDP processing CONNCMD_NONE"<<std::endl);
@ -1697,7 +1696,7 @@ void ConnectionSendThread::serve(Address bind_address)
m_connection->m_udpSocket.Bind(bind_address); m_connection->m_udpSocket.Bind(bind_address);
m_connection->SetPeerID(PEER_ID_SERVER); m_connection->SetPeerID(PEER_ID_SERVER);
} }
catch(SocketException &e){ catch(SocketException &e) {
// Create event // Create event
ConnectionEvent ce; ConnectionEvent ce;
ce.bindFailed(); ce.bindFailed();
@ -1728,8 +1727,8 @@ void ConnectionSendThread::connect(Address address)
// Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
m_connection->SetPeerID(PEER_ID_INEXISTENT); m_connection->SetPeerID(PEER_ID_INEXISTENT);
SharedBuffer<u8> data(0); NetworkPacket* pkt = new NetworkPacket(0,0);
m_connection->Send(PEER_ID_SERVER, 0, data, true); m_connection->Send(PEER_ID_SERVER, 0, pkt, true);
} }
void ConnectionSendThread::disconnect() void ConnectionSendThread::disconnect()
@ -1782,7 +1781,7 @@ void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
assert(channelnum < CHANNEL_COUNT); assert(channelnum < CHANNEL_COUNT);
PeerHelper peer = m_connection->getPeerNoEx(peer_id); PeerHelper peer = m_connection->getPeerNoEx(peer_id);
if(!peer) if (!peer)
{ {
LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
<< ">>>NOT<<< found on sending packet" << ">>>NOT<<< found on sending packet"
@ -1948,7 +1947,7 @@ void ConnectionSendThread::sendPackets(float dtime)
"reliable packets are not allowed in outgoing queue!"); "reliable packets are not allowed in outgoing queue!");
PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id); PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
if(!peer) { if (!peer) {
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
<<" Outgoing queue: peer_id="<<packet.peer_id <<" Outgoing queue: peer_id="<<packet.peer_id
<< ">>>NOT<<< found on sending packet" << ">>>NOT<<< found on sending packet"
@ -1966,7 +1965,7 @@ void ConnectionSendThread::sendPackets(float dtime)
} }
else if ( else if (
( peer->m_increment_packets_remaining > 0) || ( peer->m_increment_packets_remaining > 0) ||
(StopRequested())){ (StopRequested())) {
rawSendAsPacket(packet.peer_id, packet.channelnum, rawSendAsPacket(packet.peer_id, packet.channelnum,
packet.data, packet.reliable); packet.data, packet.reliable);
peer->m_increment_packets_remaining--; peer->m_increment_packets_remaining--;
@ -2107,152 +2106,149 @@ void ConnectionReceiveThread::receive()
/* first of all read packets from socket */ /* first of all read packets from socket */
/* check for incoming data available */ /* check for incoming data available */
while( (loop_count < 10) && while( (loop_count < 10) &&
(m_connection->m_udpSocket.WaitData(50))) (m_connection->m_udpSocket.WaitData(50))) {
{
loop_count++; loop_count++;
try{ try {
if (packet_queued) if (packet_queued) {
{ bool data_left = true;
bool no_data_left = false; u16 peer_id;
u16 peer_id; SharedBuffer<u8> resultdata;
SharedBuffer<u8> resultdata; while(data_left) {
while(!no_data_left) try {
{ data_left = getFromBuffers(peer_id, resultdata);
try { if (data_left) {
no_data_left = !getFromBuffers(peer_id, resultdata); ConnectionEvent e;
if (!no_data_left) { e.dataReceived(peer_id, resultdata);
ConnectionEvent e; m_connection->putEvent(e);
e.dataReceived(peer_id, resultdata); }
m_connection->putEvent(e); }
catch(ProcessedSilentlyException &e) {
/* try reading again */
} }
} }
catch(ProcessedSilentlyException &e) { packet_queued = false;
/* try reading again */ }
Address sender;
s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
if ((received_size < BASE_HEADER_SIZE) ||
(readU32(&packetdata[0]) != m_connection->GetProtocolID()))
{
LOG(derr_con<<m_connection->getDesc()
<<"Receive(): Invalid incoming packet, "
<<"size: " << received_size
<<", protocol: "
<< ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
<< std::endl);
continue;
}
u16 peer_id = readPeerId(*packetdata);
u8 channelnum = readChannel(*packetdata);
if (channelnum > CHANNEL_COUNT-1) {
LOG(derr_con<<m_connection->getDesc()
<<"Receive(): Invalid channel "<<channelnum<<std::endl);
throw InvalidIncomingDataException("Channel doesn't exist");
}
/* preserve original peer_id for later usage */
u16 packet_peer_id = peer_id;
/* Try to identify peer by sender address (may happen on join) */
if (peer_id == PEER_ID_INEXISTENT) {
peer_id = m_connection->lookupPeer(sender);
}
/* The peer was not found in our lists. Add it. */
if (peer_id == PEER_ID_INEXISTENT) {
peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
}
PeerHelper peer = m_connection->getPeerNoEx(peer_id);
if (!peer) {
LOG(dout_con<<m_connection->getDesc()
<<" got packet from unknown peer_id: "
<<peer_id<<" Ignoring."<<std::endl);
continue;
}
// Validate peer address
Address peer_address;
if (peer->getAddress(MTP_UDP, peer_address)) {
if (peer_address != sender) {
LOG(derr_con<<m_connection->getDesc()
<<m_connection->getDesc()
<<" Peer "<<peer_id<<" sending from different address."
" Ignoring."<<std::endl);
continue;
} }
} }
packet_queued = false; else {
}
Address sender; bool invalid_address = true;
s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize); if (invalid_address) {
LOG(derr_con<<m_connection->getDesc()
<<m_connection->getDesc()
<<" Peer "<<peer_id<<" unknown."
" Ignoring."<<std::endl);
continue;
}
}
if ((received_size < 0) ||
(received_size < BASE_HEADER_SIZE) ||
(readU32(&packetdata[0]) != m_connection->GetProtocolID()))
{
LOG(derr_con<<m_connection->getDesc()
<<"Receive(): Invalid incoming packet, "
<<"size: " << received_size
<<", protocol: "
<< ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
<< std::endl);
continue;
}
u16 peer_id = readPeerId(*packetdata); /* mark peer as seen with id */
u8 channelnum = readChannel(*packetdata); if (!(packet_peer_id == PEER_ID_INEXISTENT))
peer->setSentWithID();
if(channelnum > CHANNEL_COUNT-1){ peer->ResetTimeout();
LOG(derr_con<<m_connection->getDesc()
<<"Receive(): Invalid channel "<<channelnum<<std::endl);
throw InvalidIncomingDataException("Channel doesn't exist");
}
/* preserve original peer_id for later usage */ Channel *channel = 0;
u16 packet_peer_id = peer_id;
/* Try to identify peer by sender address (may happen on join) */ if (dynamic_cast<UDPPeer*>(&peer) != 0)
if(peer_id == PEER_ID_INEXISTENT) {
{ channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
peer_id = m_connection->lookupPeer(sender); }
}
/* The peer was not found in our lists. Add it. */ if (channel != 0) {
if(peer_id == PEER_ID_INEXISTENT) channel->UpdateBytesReceived(received_size);
{ }
peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
}
PeerHelper peer = m_connection->getPeerNoEx(peer_id); // Throw the received packet to channel->processPacket()
if (!peer) { // Make a new SharedBuffer from the data without the base headers
LOG(dout_con<<m_connection->getDesc() SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
<<" got packet from unknown peer_id: " memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
<<peer_id<<" Ignoring."<<std::endl); strippeddata.getSize());
continue;
}
// Validate peer address try{
// Process it (the result is some data with no headers made by us)
SharedBuffer<u8> resultdata = processPacket
(channel, strippeddata, peer_id, channelnum, false);
Address peer_address; LOG(dout_con<<m_connection->getDesc()
<<" ProcessPacket from peer_id: " << peer_id
<< ",channel: " << (channelnum & 0xFF) << ", returned "
<< resultdata.getSize() << " bytes" <<std::endl);
if (peer->getAddress(MTP_UDP, peer_address)) { ConnectionEvent e;
if (peer_address != sender) { e.dataReceived(peer_id, resultdata);
LOG(derr_con<<m_connection->getDesc() m_connection->putEvent(e);
<<m_connection->getDesc() }
<<" Peer "<<peer_id<<" sending from different address." catch(ProcessedSilentlyException &e) {
" Ignoring."<<std::endl); }
continue; catch(ProcessedQueued &e) {
packet_queued = true;
} }
} }
else { catch(InvalidIncomingDataException &e) {
bool invalid_address = true;
if (invalid_address) {
LOG(derr_con<<m_connection->getDesc()
<<m_connection->getDesc()
<<" Peer "<<peer_id<<" unknown."
" Ignoring."<<std::endl);
continue;
}
} }
catch(ProcessedSilentlyException &e) {
/* mark peer as seen with id */
if (!(packet_peer_id == PEER_ID_INEXISTENT))
peer->setSentWithID();
peer->ResetTimeout();
Channel *channel = 0;
if (dynamic_cast<UDPPeer*>(&peer) != 0)
{
channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
} }
if (channel != 0) {
channel->UpdateBytesReceived(received_size);
}
// Throw the received packet to channel->processPacket()
// Make a new SharedBuffer from the data without the base headers
SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
strippeddata.getSize());
try{
// Process it (the result is some data with no headers made by us)
SharedBuffer<u8> resultdata = processPacket
(channel, strippeddata, peer_id, channelnum, false);
LOG(dout_con<<m_connection->getDesc()
<<" ProcessPacket from peer_id: " << peer_id
<< ",channel: " << (channelnum & 0xFF) << ", returned "
<< resultdata.getSize() << " bytes" <<std::endl);
ConnectionEvent e;
e.dataReceived(peer_id, resultdata);
m_connection->putEvent(e);
}catch(ProcessedSilentlyException &e){
}catch(ProcessedQueued &e){
packet_queued = true;
}
}catch(InvalidIncomingDataException &e){
}
catch(ProcessedSilentlyException &e){
}
} }
} }
@ -2267,17 +2263,14 @@ bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst
if (!peer) if (!peer)
continue; continue;
if(dynamic_cast<UDPPeer*>(&peer) == 0) if (dynamic_cast<UDPPeer*>(&peer) == 0)
continue; continue;
for(u16 i=0; i<CHANNEL_COUNT; i++) for(u16 i=0; i<CHANNEL_COUNT; i++)
{ {
Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i]; Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
SharedBuffer<u8> resultdata; if (checkIncomingBuffers(channel, peer_id, dst)) {
bool got = checkIncomingBuffers(channel, peer_id, resultdata);
if(got){
dst = resultdata;
return true; return true;
} }
} }
@ -2291,7 +2284,7 @@ bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
u16 firstseqnum = 0; u16 firstseqnum = 0;
if (channel->incoming_reliables.getFirstSeqnum(firstseqnum)) if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
{ {
if(firstseqnum == channel->readNextIncomingSeqNum()) if (firstseqnum == channel->readNextIncomingSeqNum())
{ {
BufferedPacket p = channel->incoming_reliables.popFirst(); BufferedPacket p = channel->incoming_reliables.popFirst();
peer_id = readPeerId(*p.data); peer_id = readPeerId(*p.data);
@ -2329,7 +2322,7 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
throw ProcessedSilentlyException("Peer not found (possible timeout)"); throw ProcessedSilentlyException("Peer not found (possible timeout)");
} }
if(packetdata.getSize() < 1) if (packetdata.getSize() < 1)
throw InvalidIncomingDataException("packetdata.getSize() < 1"); throw InvalidIncomingDataException("packetdata.getSize() < 1");
u8 type = readU8(&(packetdata[0])); u8 type = readU8(&(packetdata[0]));
@ -2339,17 +2332,17 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
assert(0); assert(0);
} }
if(type == TYPE_CONTROL) if (type == TYPE_CONTROL)
{ {
if(packetdata.getSize() < 2) if (packetdata.getSize() < 2)
throw InvalidIncomingDataException("packetdata.getSize() < 2"); throw InvalidIncomingDataException("packetdata.getSize() < 2");
u8 controltype = readU8(&(packetdata[1])); u8 controltype = readU8(&(packetdata[1]));
if(controltype == CONTROLTYPE_ACK) if (controltype == CONTROLTYPE_ACK)
{ {
assert(channel != 0); assert(channel != 0);
if(packetdata.getSize() < 4) if (packetdata.getSize() < 4)
throw InvalidIncomingDataException throw InvalidIncomingDataException
("packetdata.getSize() < 4 (ACK header size)"); ("packetdata.getSize() < 4 (ACK header size)");
@ -2394,7 +2387,7 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
m_connection->TriggerSend(); m_connection->TriggerSend();
} }
} }
catch(NotFoundException &e){ catch(NotFoundException &e) {
LOG(derr_con<<m_connection->getDesc() LOG(derr_con<<m_connection->getDesc()
<<"WARNING: ACKed packet not " <<"WARNING: ACKed packet not "
"in outgoing queue" "in outgoing queue"
@ -2403,17 +2396,16 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
} }
throw ProcessedSilentlyException("Got an ACK"); throw ProcessedSilentlyException("Got an ACK");
} }
else if(controltype == CONTROLTYPE_SET_PEER_ID) else if (controltype == CONTROLTYPE_SET_PEER_ID) {
{
// Got a packet to set our peer id // Got a packet to set our peer id
if(packetdata.getSize() < 4) if (packetdata.getSize() < 4)
throw InvalidIncomingDataException throw InvalidIncomingDataException
("packetdata.getSize() < 4 (SET_PEER_ID header size)"); ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
u16 peer_id_new = readU16(&packetdata[2]); u16 peer_id_new = readU16(&packetdata[2]);
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
<<"Got new peer id: "<<peer_id_new<<"... "<<std::endl); <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
if(m_connection->GetPeerID() != PEER_ID_INEXISTENT) if (m_connection->GetPeerID() != PEER_ID_INEXISTENT)
{ {
LOG(derr_con<<m_connection->getDesc() LOG(derr_con<<m_connection->getDesc()
<<"WARNING: Not changing" <<"WARNING: Not changing"
@ -2435,21 +2427,21 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
throw ProcessedSilentlyException("Got a SET_PEER_ID"); throw ProcessedSilentlyException("Got a SET_PEER_ID");
} }
else if(controltype == CONTROLTYPE_PING) else if (controltype == CONTROLTYPE_PING)
{ {
// Just ignore it, the incoming data already reset // Just ignore it, the incoming data already reset
// the timeout counter // the timeout counter
LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl); LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
throw ProcessedSilentlyException("Got a PING"); throw ProcessedSilentlyException("Got a PING");
} }
else if(controltype == CONTROLTYPE_DISCO) else if (controltype == CONTROLTYPE_DISCO)
{ {
// Just ignore it, the incoming data already reset // Just ignore it, the incoming data already reset
// the timeout counter // the timeout counter
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
<<"DISCO: Removing peer "<<(peer_id)<<std::endl); <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
if(m_connection->deletePeer(peer_id, false) == false) if (m_connection->deletePeer(peer_id, false) == false)
{ {
derr_con<<m_connection->getDesc() derr_con<<m_connection->getDesc()
<<"DISCO: Peer not found"<<std::endl; <<"DISCO: Peer not found"<<std::endl;
@ -2457,7 +2449,7 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
throw ProcessedSilentlyException("Got a DISCO"); throw ProcessedSilentlyException("Got a DISCO");
} }
else if(controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW) else if (controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
{ {
dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer(); dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
throw ProcessedSilentlyException("Got non legacy control"); throw ProcessedSilentlyException("Got non legacy control");
@ -2469,9 +2461,9 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
throw InvalidIncomingDataException("Invalid control type"); throw InvalidIncomingDataException("Invalid control type");
} }
} }
else if(type == TYPE_ORIGINAL) else if (type == TYPE_ORIGINAL)
{ {
if(packetdata.getSize() <= ORIGINAL_HEADER_SIZE) if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
throw InvalidIncomingDataException throw InvalidIncomingDataException
("packetdata.getSize() <= ORIGINAL_HEADER_SIZE"); ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
@ -2482,7 +2474,7 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize()); memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
return payload; return payload;
} }
else if(type == TYPE_SPLIT) else if (type == TYPE_SPLIT)
{ {
Address peer_address; Address peer_address;
@ -2501,7 +2493,7 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
SharedBuffer<u8> data = SharedBuffer<u8> data =
peer->addSpiltPacket(channelnum,packet,reliable); peer->addSpiltPacket(channelnum,packet,reliable);
if(data.getSize() != 0) if (data.getSize() != 0)
{ {
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
<<"RETURNING TYPE_SPLIT: Constructed full data, " <<"RETURNING TYPE_SPLIT: Constructed full data, "
@ -2515,14 +2507,14 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
//TODO throw some error //TODO throw some error
} }
} }
else if(type == TYPE_RELIABLE) else if (type == TYPE_RELIABLE)
{ {
assert(channel != 0); assert(channel != 0);
// Recursive reliable packets not allowed // Recursive reliable packets not allowed
if(reliable) if (reliable)
throw InvalidIncomingDataException("Found nested reliable packets"); throw InvalidIncomingDataException("Found nested reliable packets");
if(packetdata.getSize() < RELIABLE_HEADER_SIZE) if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
throw InvalidIncomingDataException throw InvalidIncomingDataException
("packetdata.getSize() < RELIABLE_HEADER_SIZE"); ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
@ -2739,7 +2731,7 @@ PeerHelper Connection::getPeer(u16 peer_id)
JMutexAutoLock peerlock(m_peers_mutex); JMutexAutoLock peerlock(m_peers_mutex);
std::map<u16, Peer*>::iterator node = m_peers.find(peer_id); std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
if(node == m_peers.end()){ if (node == m_peers.end()) {
throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)"); throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
} }
@ -2754,7 +2746,7 @@ PeerHelper Connection::getPeerNoEx(u16 peer_id)
JMutexAutoLock peerlock(m_peers_mutex); JMutexAutoLock peerlock(m_peers_mutex);
std::map<u16, Peer*>::iterator node = m_peers.find(peer_id); std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
if(node == m_peers.end()){ if (node == m_peers.end()) {
return PeerHelper(NULL); return PeerHelper(NULL);
} }
@ -2773,7 +2765,7 @@ u16 Connection::lookupPeer(Address& sender)
for(; j != m_peers.end(); ++j) for(; j != m_peers.end(); ++j)
{ {
Peer *peer = j->second; Peer *peer = j->second;
if(peer->isActive()) if (peer->isActive())
continue; continue;
Address tocheck; Address tocheck;
@ -2807,10 +2799,11 @@ bool Connection::deletePeer(u16 peer_id, bool timeout)
/* lock list as short as possible */ /* lock list as short as possible */
{ {
JMutexAutoLock peerlock(m_peers_mutex); JMutexAutoLock peerlock(m_peers_mutex);
if(m_peers.find(peer_id) == m_peers.end()) if (m_peers.find(peer_id) == m_peers.end())
return false; return false;
peer = m_peers[peer_id]; peer = m_peers[peer_id];
m_peers.erase(peer_id); m_peers.erase(peer_id);
m_peer_ids.remove(peer_id);
} }
Address peer_address; Address peer_address;
@ -2830,7 +2823,7 @@ bool Connection::deletePeer(u16 peer_id, bool timeout)
ConnectionEvent Connection::getEvent() ConnectionEvent Connection::getEvent()
{ {
if(m_event_queue.empty()){ if (m_event_queue.empty()) {
ConnectionEvent e; ConnectionEvent e;
e.type = CONNEVENT_NONE; e.type = CONNEVENT_NONE;
return e; return e;
@ -2840,9 +2833,9 @@ ConnectionEvent Connection::getEvent()
ConnectionEvent Connection::waitEvent(u32 timeout_ms) ConnectionEvent Connection::waitEvent(u32 timeout_ms)
{ {
try{ try {
return m_event_queue.pop_front(timeout_ms); return m_event_queue.pop_front(timeout_ms);
} catch(ItemNotFoundException &ex){ } catch(ItemNotFoundException &ex) {
ConnectionEvent e; ConnectionEvent e;
e.type = CONNEVENT_NONE; e.type = CONNEVENT_NONE;
return e; return e;
@ -2851,8 +2844,7 @@ ConnectionEvent Connection::waitEvent(u32 timeout_ms)
void Connection::putCommand(ConnectionCommand &c) void Connection::putCommand(ConnectionCommand &c)
{ {
if (!m_shutting_down) if (!m_shutting_down) {
{
m_command_queue.push_back(c); m_command_queue.push_back(c);
m_sendThread.Trigger(); m_sendThread.Trigger();
} }
@ -2876,14 +2868,14 @@ bool Connection::Connected()
{ {
JMutexAutoLock peerlock(m_peers_mutex); JMutexAutoLock peerlock(m_peers_mutex);
if(m_peers.size() != 1) if (m_peers.size() != 1)
return false; return false;
std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER); std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
if(node == m_peers.end()) if (node == m_peers.end())
return false; return false;
if(m_peer_id == PEER_ID_INEXISTENT) if (m_peer_id == PEER_ID_INEXISTENT)
return false; return false;
return true; return true;
@ -2898,12 +2890,12 @@ void Connection::Disconnect()
u32 Connection::Receive(u16 &peer_id, SharedBuffer<u8> &data) u32 Connection::Receive(u16 &peer_id, SharedBuffer<u8> &data)
{ {
for(;;){ for(;;) {
ConnectionEvent e = waitEvent(m_bc_receive_timeout); ConnectionEvent e = waitEvent(m_bc_receive_timeout);
if(e.type != CONNEVENT_NONE) if (e.type != CONNEVENT_NONE)
LOG(dout_con<<getDesc()<<": Receive: got event: " LOG(dout_con<<getDesc()<<": Receive: got event: "
<<e.describe()<<std::endl); <<e.describe()<<std::endl);
switch(e.type){ switch(e.type) {
case CONNEVENT_NONE: case CONNEVENT_NONE:
throw NoIncomingDataException("No incoming data"); throw NoIncomingDataException("No incoming data");
case CONNEVENT_DATA_RECEIVED: case CONNEVENT_DATA_RECEIVED:
@ -2912,12 +2904,12 @@ u32 Connection::Receive(u16 &peer_id, SharedBuffer<u8> &data)
return e.data.getSize(); return e.data.getSize();
case CONNEVENT_PEER_ADDED: { case CONNEVENT_PEER_ADDED: {
UDPPeer tmp(e.peer_id, e.address, this); UDPPeer tmp(e.peer_id, e.address, this);
if(m_bc_peerhandler) if (m_bc_peerhandler)
m_bc_peerhandler->peerAdded(&tmp); m_bc_peerhandler->peerAdded(&tmp);
continue; } continue; }
case CONNEVENT_PEER_REMOVED: { case CONNEVENT_PEER_REMOVED: {
UDPPeer tmp(e.peer_id, e.address, this); UDPPeer tmp(e.peer_id, e.address, this);
if(m_bc_peerhandler) if (m_bc_peerhandler)
m_bc_peerhandler->deletingPeer(&tmp, e.timeout); m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
continue; } continue; }
case CONNEVENT_BIND_FAILED: case CONNEVENT_BIND_FAILED:
@ -2928,22 +2920,14 @@ u32 Connection::Receive(u16 &peer_id, SharedBuffer<u8> &data)
throw NoIncomingDataException("No incoming data"); throw NoIncomingDataException("No incoming data");
} }
void Connection::SendToAll(u8 channelnum, SharedBuffer<u8> data, bool reliable)
{
assert(channelnum < CHANNEL_COUNT);
ConnectionCommand c;
c.sendToAll(channelnum, data, reliable);
putCommand(c);
}
void Connection::Send(u16 peer_id, u8 channelnum, void Connection::Send(u16 peer_id, u8 channelnum,
SharedBuffer<u8> data, bool reliable) NetworkPacket* pkt, bool reliable)
{ {
assert(channelnum < CHANNEL_COUNT); assert(channelnum < CHANNEL_COUNT);
ConnectionCommand c; ConnectionCommand c;
c.send(peer_id, channelnum, data, reliable);
c.send(peer_id, channelnum, pkt->oldForgePacket(), reliable);
putCommand(c); putCommand(c);
} }
@ -3013,37 +2997,37 @@ u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
/* /*
Find an unused peer id Find an unused peer id
*/ */
{
JMutexAutoLock lock(m_peers_mutex); JMutexAutoLock lock(m_peers_mutex);
bool out_of_ids = false; bool out_of_ids = false;
for(;;) for(;;) {
{ // Check if exists
// Check if exists if (m_peers.find(peer_id_new) == m_peers.end())
if(m_peers.find(peer_id_new) == m_peers.end())
break;
// Check for overflow
if(peer_id_new == overflow){
out_of_ids = true;
break;
}
peer_id_new++;
}
if(out_of_ids){
errorstream<<getDesc()<<" ran out of peer ids"<<std::endl;
return PEER_ID_INEXISTENT;
}
// Create a peer break;
Peer *peer = 0; // Check for overflow
peer = new UDPPeer(peer_id_new, sender, this); if (peer_id_new == overflow) {
out_of_ids = true;
m_peers[peer->id] = peer; break;
}
peer_id_new++;
} }
m_next_remote_peer_id = (peer_id_new +1) % MAX_UDP_PEERS; if (out_of_ids) {
errorstream << getDesc() << " ran out of peer ids" << std::endl;
return PEER_ID_INEXISTENT;
}
LOG(dout_con<<getDesc() // Create a peer
<<"createPeer(): giving peer_id="<<peer_id_new<<std::endl); Peer *peer = 0;
peer = new UDPPeer(peer_id_new, sender, this);
m_peers[peer->id] = peer;
m_peer_ids.push_back(peer->id);
m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
LOG(dout_con << getDesc()
<< "createPeer(): giving peer_id=" << peer_id_new << std::endl);
ConnectionCommand cmd; ConnectionCommand cmd;
SharedBuffer<u8> reply(4); SharedBuffer<u8> reply(4);
@ -3051,7 +3035,7 @@ u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID); writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
writeU16(&reply[2], peer_id_new); writeU16(&reply[2], peer_id_new);
cmd.createPeer(peer_id_new,reply); cmd.createPeer(peer_id_new,reply);
this->putCommand(cmd); putCommand(cmd);
// Create peer addition event // Create peer addition event
ConnectionEvent e; ConnectionEvent e;
@ -3119,22 +3103,10 @@ UDPPeer* Connection::createServerPeer(Address& address)
{ {
JMutexAutoLock lock(m_peers_mutex); JMutexAutoLock lock(m_peers_mutex);
m_peers[peer->id] = peer; m_peers[peer->id] = peer;
m_peer_ids.push_back(peer->id);
} }
return peer; return peer;
} }
std::list<u16> Connection::getPeerIDs()
{
std::list<u16> retval;
JMutexAutoLock lock(m_peers_mutex);
for(std::map<u16, Peer*>::iterator j = m_peers.begin();
j != m_peers.end(); ++j)
{
retval.push_back(j->first);
}
return retval;
}
} // namespace } // namespace

@ -24,6 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "socket.h" #include "socket.h"
#include "exceptions.h" #include "exceptions.h"
#include "constants.h" #include "constants.h"
#include "network/networkpacket.h"
#include "util/pointer.h" #include "util/pointer.h"
#include "util/container.h" #include "util/container.h"
#include "util/thread.h" #include "util/thread.h"
@ -130,14 +131,14 @@ inline bool seqnum_higher(u16 totest, u16 base)
{ {
if (totest > base) if (totest > base)
{ {
if((totest - base) > (SEQNUM_MAX/2)) if ((totest - base) > (SEQNUM_MAX/2))
return false; return false;
else else
return true; return true;
} }
else else
{ {
if((base - totest) > (SEQNUM_MAX/2)) if ((base - totest) > (SEQNUM_MAX/2))
return true; return true;
else else
return false; return false;
@ -873,7 +874,7 @@ struct ConnectionEvent
std::string describe() std::string describe()
{ {
switch(type){ switch(type) {
case CONNEVENT_NONE: case CONNEVENT_NONE:
return "CONNEVENT_NONE"; return "CONNEVENT_NONE";
case CONNEVENT_DATA_RECEIVED: case CONNEVENT_DATA_RECEIVED:
@ -1026,15 +1027,14 @@ public:
ConnectionEvent waitEvent(u32 timeout_ms); ConnectionEvent waitEvent(u32 timeout_ms);
void putCommand(ConnectionCommand &c); void putCommand(ConnectionCommand &c);
void SetTimeoutMs(int timeout){ m_bc_receive_timeout = timeout; } void SetTimeoutMs(int timeout) { m_bc_receive_timeout = timeout; }
void Serve(Address bind_addr); void Serve(Address bind_addr);
void Connect(Address address); void Connect(Address address);
bool Connected(); bool Connected();
void Disconnect(); void Disconnect();
u32 Receive(u16 &peer_id, SharedBuffer<u8> &data); u32 Receive(u16 &peer_id, SharedBuffer<u8> &data);
void SendToAll(u8 channelnum, SharedBuffer<u8> data, bool reliable); void Send(u16 peer_id, u8 channelnum, NetworkPacket* pkt, bool reliable);
void Send(u16 peer_id, u8 channelnum, SharedBuffer<u8> data, bool reliable); u16 GetPeerID() { return m_peer_id; }
u16 GetPeerID(){ return m_peer_id; }
Address GetPeerAddress(u16 peer_id); Address GetPeerAddress(u16 peer_id);
float getPeerStat(u16 peer_id, rtt_stat_type type); float getPeerStat(u16 peer_id, rtt_stat_type type);
float getLocalStat(rate_stat_type type); float getLocalStat(rate_stat_type type);
@ -1051,14 +1051,14 @@ protected:
UDPPeer* createServerPeer(Address& sender); UDPPeer* createServerPeer(Address& sender);
bool deletePeer(u16 peer_id, bool timeout); bool deletePeer(u16 peer_id, bool timeout);
void SetPeerID(u16 id){ m_peer_id = id; } void SetPeerID(u16 id) { m_peer_id = id; }
void sendAck(u16 peer_id, u8 channelnum, u16 seqnum); void sendAck(u16 peer_id, u8 channelnum, u16 seqnum);
void PrintInfo(std::ostream &out); void PrintInfo(std::ostream &out);
void PrintInfo(); void PrintInfo();
std::list<u16> getPeerIDs(); std::list<u16> getPeerIDs() { return m_peer_ids; }
UDPSocket m_udpSocket; UDPSocket m_udpSocket;
MutexedQueue<ConnectionCommand> m_command_queue; MutexedQueue<ConnectionCommand> m_command_queue;
@ -1076,6 +1076,7 @@ private:
u32 m_protocol_id; u32 m_protocol_id;
std::map<u16, Peer*> m_peers; std::map<u16, Peer*> m_peers;
std::list<u16> m_peer_ids;
JMutex m_peers_mutex; JMutex m_peers_mutex;
ConnectionSendThread m_sendThread; ConnectionSendThread m_sendThread;
@ -1095,4 +1096,3 @@ private:
} // namespace } // namespace
#endif #endif

@ -1,6 +1,5 @@
/* /*
Minetest Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr> Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
@ -20,37 +19,54 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "networkpacket.h" #include "networkpacket.h"
#include "debug.h" #include "debug.h"
#include "exceptions.h"
#include "util/serialize.h" #include "util/serialize.h"
NetworkPacket::NetworkPacket(u8 *data, u32 datasize, u16 peer_id): NetworkPacket::NetworkPacket(u8 *data, u32 datasize, u16 peer_id):
m_peer_id(peer_id) m_read_offset(0), m_peer_id(peer_id)
{ {
m_read_offset = 0; m_read_offset = 0;
m_datasize = datasize - 2; m_datasize = datasize - 2;
// Copy data packet to remove opcode // split command and datas
m_data = new u8[m_datasize]; m_command = readU16(&data[0]);
m_data = std::vector<u8>(&data[2], &data[2 + m_datasize]);
}
memcpy(m_data, &data[2], m_datasize); NetworkPacket::NetworkPacket(u16 command, u32 datasize, u16 peer_id):
m_datasize(datasize), m_read_offset(0), m_command(command), m_peer_id(peer_id)
{
m_data.resize(m_datasize);
}
NetworkPacket::NetworkPacket(u16 command, u32 datasize):
m_datasize(datasize), m_read_offset(0), m_command(command), m_peer_id(0)
{
m_data.resize(m_datasize);
} }
NetworkPacket::~NetworkPacket() NetworkPacket::~NetworkPacket()
{ {
delete [] m_data; m_data.clear();
} }
char* NetworkPacket::getString(u32 from_offset) char* NetworkPacket::getString(u32 from_offset)
{ {
assert(from_offset < m_datasize); if (from_offset >= m_datasize)
throw SerializationError("Malformed packet read");
return (char*)&m_data[from_offset]; return (char*)&m_data[from_offset];
} }
char NetworkPacket::getChar(u32 offset) void NetworkPacket::putRawString(const char* src, u32 len)
{ {
assert(offset < m_datasize); if (m_read_offset + len * sizeof(char) >= m_datasize) {
m_datasize += len * sizeof(char);
m_data.resize(m_datasize);
}
return m_data[offset]; memcpy(&m_data[m_read_offset], src, len);
m_read_offset += len;
} }
NetworkPacket& NetworkPacket::operator>>(std::string& dst) NetworkPacket& NetworkPacket::operator>>(std::string& dst)
@ -64,14 +80,51 @@ NetworkPacket& NetworkPacket::operator>>(std::string& dst)
return *this; return *this;
} }
dst.reserve(strLen); dst.reserve(strLen);
dst.append((char*)&m_data[m_read_offset], strLen); dst.append((char*)&m_data[m_read_offset], strLen);
m_read_offset += strLen*sizeof(char); m_read_offset += strLen * sizeof(char);
return *this; return *this;
} }
NetworkPacket& NetworkPacket::operator<<(std::string src)
{
u16 msgsize = src.size();
if (msgsize > 0xFFFF) {
msgsize = 0xFFFF;
}
*this << msgsize;
if (m_read_offset + msgsize * sizeof(char) >= m_datasize) {
m_datasize += msgsize * sizeof(char);
m_data.resize(m_datasize);
}
memcpy(&m_data[m_read_offset], src.c_str(), msgsize);
m_read_offset += msgsize;
return *this;
}
void NetworkPacket::putLongString(std::string src)
{
u32 msgsize = src.size();
if (msgsize > 0xFFFFFFFF) {
msgsize = 0xFFFFFFFF;
}
*this << msgsize;
if (m_read_offset + msgsize * sizeof(char) >= m_datasize) {
m_datasize += msgsize * sizeof(char);
m_data.resize(m_datasize);
}
memcpy(&m_data[m_read_offset], src.c_str(), msgsize);
m_read_offset += msgsize;
}
NetworkPacket& NetworkPacket::operator>>(std::wstring& dst) NetworkPacket& NetworkPacket::operator>>(std::wstring& dst)
{ {
u16 strLen = readU16(&m_data[m_read_offset]); u16 strLen = readU16(&m_data[m_read_offset]);
@ -93,6 +146,23 @@ NetworkPacket& NetworkPacket::operator>>(std::wstring& dst)
return *this; return *this;
} }
NetworkPacket& NetworkPacket::operator<<(std::wstring src)
{
u16 msgsize = src.size();
if (msgsize > 0xFFFF) {
msgsize = 0xFFFF;
}
*this << msgsize;
// Write string
for (u16 i=0; i<msgsize; i++) {
*this << (u16) src[i];
}
return *this;
}
std::string NetworkPacket::readLongString() std::string NetworkPacket::readLongString()
{ {
u32 strLen = readU32(&m_data[m_read_offset]); u32 strLen = readU32(&m_data[m_read_offset]);
@ -114,151 +184,251 @@ std::string NetworkPacket::readLongString()
NetworkPacket& NetworkPacket::operator>>(char& dst) NetworkPacket& NetworkPacket::operator>>(char& dst)
{ {
dst = getChar(m_read_offset); if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
m_read_offset += sizeof(char); dst = readU8(&m_data[m_read_offset]);
incrOffset<char>();
return *this; return *this;
} }
u8* NetworkPacket::getU8Ptr(u32 from_offset) char NetworkPacket::getChar(u32 offset)
{ {
assert(from_offset < m_datasize); if (offset >= m_datasize)
throw SerializationError("Malformed packet read");
return (u8*)&m_data[from_offset]; return readU8(&m_data[offset]);
} }
u8 NetworkPacket::getU8(u32 offset) NetworkPacket& NetworkPacket::operator<<(char src)
{ {
assert(offset < m_datasize); checkDataSize<u8>();
return m_data[offset]; writeU8(&m_data[m_read_offset], src);
incrOffset<char>();
return *this;
} }
NetworkPacket& NetworkPacket::operator>>(u8& dst) NetworkPacket& NetworkPacket::operator<<(u8 src)
{ {
assert(m_read_offset < m_datasize); checkDataSize<u8>();
dst = m_data[m_read_offset];
m_read_offset += sizeof(u8); writeU8(&m_data[m_read_offset], src);
incrOffset<u8>();
return *this;
}
NetworkPacket& NetworkPacket::operator<<(bool src)
{
checkDataSize<u8>();
writeU8(&m_data[m_read_offset], src);
incrOffset<u8>();
return *this;
}
NetworkPacket& NetworkPacket::operator<<(u16 src)
{
checkDataSize<u16>();
writeU16(&m_data[m_read_offset], src);
incrOffset<u16>();
return *this;
}
NetworkPacket& NetworkPacket::operator<<(u32 src)
{
checkDataSize<u32>();
writeU32(&m_data[m_read_offset], src);
incrOffset<u32>();
return *this;
}
NetworkPacket& NetworkPacket::operator<<(u64 src)
{
checkDataSize<u64>();
writeU64(&m_data[m_read_offset], src);
incrOffset<u64>();
return *this;
}
NetworkPacket& NetworkPacket::operator<<(float src)
{
checkDataSize<float>();
writeF1000(&m_data[m_read_offset], src);
incrOffset<float>();
return *this; return *this;
} }
NetworkPacket& NetworkPacket::operator>>(bool& dst) NetworkPacket& NetworkPacket::operator>>(bool& dst)
{ {
assert(m_read_offset < m_datasize); if (m_read_offset >= m_datasize)
dst = m_data[m_read_offset]; throw SerializationError("Malformed packet read");
m_read_offset += sizeof(u8); dst = readU8(&m_data[m_read_offset]);
incrOffset<u8>();
return *this;
}
NetworkPacket& NetworkPacket::operator>>(u8& dst)
{
if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
dst = readU8(&m_data[m_read_offset]);
incrOffset<u8>();
return *this;
}
u8 NetworkPacket::getU8(u32 offset)
{
if (offset >= m_datasize)
throw SerializationError("Malformed packet read");
return readU8(&m_data[offset]);
}
u8* NetworkPacket::getU8Ptr(u32 from_offset)
{
if (m_datasize == 0) {
return NULL;
}
if (from_offset >= m_datasize)
throw SerializationError("Malformed packet read");
return (u8*)&m_data[from_offset];
}
NetworkPacket& NetworkPacket::operator>>(u16& dst)
{
if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
dst = readU16(&m_data[m_read_offset]);
incrOffset<u16>();
return *this; return *this;
} }
u16 NetworkPacket::getU16(u32 from_offset) u16 NetworkPacket::getU16(u32 from_offset)
{ {
assert(from_offset < m_datasize); if (from_offset >= m_datasize)
throw SerializationError("Malformed packet read");
return readU16(&m_data[from_offset]); return readU16(&m_data[from_offset]);
} }
NetworkPacket& NetworkPacket::operator>>(u16& dst)
{
dst = getU16(m_read_offset);
m_read_offset += sizeof(u16);
return *this;
}
u32 NetworkPacket::getU32(u32 from_offset)
{
assert(from_offset < m_datasize);
return readU32(&m_data[from_offset]);
}
NetworkPacket& NetworkPacket::operator>>(u32& dst) NetworkPacket& NetworkPacket::operator>>(u32& dst)
{ {
dst = getU32(m_read_offset); if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
m_read_offset += sizeof(u32); dst = readU32(&m_data[m_read_offset]);
incrOffset<u32>();
return *this; return *this;
} }
u64 NetworkPacket::getU64(u32 from_offset)
{
assert(from_offset < m_datasize);
return readU64(&m_data[from_offset]);
}
NetworkPacket& NetworkPacket::operator>>(u64& dst) NetworkPacket& NetworkPacket::operator>>(u64& dst)
{ {
dst = getU64(m_read_offset); if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
m_read_offset += sizeof(u64); dst = readU64(&m_data[m_read_offset]);
incrOffset<u64>();
return *this; return *this;
} }
float NetworkPacket::getF1000(u32 from_offset)
{
assert(from_offset < m_datasize);
return readF1000(&m_data[from_offset]);
}
NetworkPacket& NetworkPacket::operator>>(float& dst) NetworkPacket& NetworkPacket::operator>>(float& dst)
{ {
dst = getF1000(m_read_offset); if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
m_read_offset += sizeof(float); dst = readF1000(&m_data[m_read_offset]);
incrOffset<float>();
return *this; return *this;
} }
NetworkPacket& NetworkPacket::operator>>(v2f& dst) NetworkPacket& NetworkPacket::operator>>(v2f& dst)
{ {
assert(m_read_offset < m_datasize); if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
dst = readV2F1000(&m_data[m_read_offset]); dst = readV2F1000(&m_data[m_read_offset]);
m_read_offset += sizeof(v2f); incrOffset<v2f>();
return *this; return *this;
} }
NetworkPacket& NetworkPacket::operator>>(v3f& dst) NetworkPacket& NetworkPacket::operator>>(v3f& dst)
{ {
assert(m_read_offset < m_datasize); if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
dst = readV3F1000(&m_data[m_read_offset]); dst = readV3F1000(&m_data[m_read_offset]);
m_read_offset += sizeof(v3f); incrOffset<v3f>();
return *this; return *this;
} }
s16 NetworkPacket::getS16(u32 from_offset)
{
assert(from_offset < m_datasize);
return readS16(&m_data[from_offset]);
}
NetworkPacket& NetworkPacket::operator>>(s16& dst) NetworkPacket& NetworkPacket::operator>>(s16& dst)
{ {
dst = getS16(m_read_offset); if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
m_read_offset += sizeof(s16); dst = readS16(&m_data[m_read_offset]);
incrOffset<s16>();
return *this; return *this;
} }
s32 NetworkPacket::getS32(u32 from_offset) NetworkPacket& NetworkPacket::operator<<(s16 src)
{ {
assert(from_offset < m_datasize); *this << (u16) src;
return *this;
return readS32(&m_data[from_offset]);
} }
NetworkPacket& NetworkPacket::operator>>(s32& dst) NetworkPacket& NetworkPacket::operator>>(s32& dst)
{ {
dst = getS32(m_read_offset); if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
m_read_offset += sizeof(s32); dst = readS32(&m_data[m_read_offset]);
incrOffset<s32>();
return *this;
}
NetworkPacket& NetworkPacket::operator<<(s32 src)
{
*this << (u32) src;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(v3s16& dst)
{
if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
dst = readV3S16(&m_data[m_read_offset]);
incrOffset<v3s16>();
return *this; return *this;
} }
@ -266,36 +436,88 @@ NetworkPacket& NetworkPacket::operator>>(v2s32& dst)
{ {
dst = readV2S32(&m_data[m_read_offset]); dst = readV2S32(&m_data[m_read_offset]);
m_read_offset += sizeof(v2s32); incrOffset<v2s32>();
return *this; return *this;
} }
v3s16 NetworkPacket::getV3S16(u32 from_offset)
{
assert(from_offset < m_datasize);
return readV3S16(&m_data[from_offset]);
}
NetworkPacket& NetworkPacket::operator>>(v3s16& dst)
{
dst = getV3S16(m_read_offset);
m_read_offset += sizeof(v3s16);
return *this;
}
v3s32 NetworkPacket::getV3S32(u32 from_offset)
{
assert(from_offset < m_datasize);
return readV3S32(&m_data[from_offset]);
}
NetworkPacket& NetworkPacket::operator>>(v3s32& dst) NetworkPacket& NetworkPacket::operator>>(v3s32& dst)
{ {
dst = getV3S32(m_read_offset); if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
m_read_offset += sizeof(v3s32); dst = readV3S32(&m_data[m_read_offset]);
incrOffset<v3s32>();
return *this; return *this;
} }
NetworkPacket& NetworkPacket::operator<<(v2f src)
{
*this << (float) src.X;
*this << (float) src.Y;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(v3f src)
{
*this << (float) src.X;
*this << (float) src.Y;
*this << (float) src.Z;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(v3s16 src)
{
*this << (s16) src.X;
*this << (s16) src.Y;
*this << (s16) src.Z;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(v2s32 src)
{
*this << (s32) src.X;
*this << (s32) src.Y;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(v3s32 src)
{
*this << (s32) src.X;
*this << (s32) src.Y;
*this << (s32) src.Z;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(video::SColor& dst)
{
if (m_read_offset >= m_datasize)
throw SerializationError("Malformed packet read");
dst = readARGB8(&m_data[m_read_offset]);
incrOffset<u32>();
return *this;
}
NetworkPacket& NetworkPacket::operator<<(video::SColor src)
{
checkDataSize<u32>();
writeU32(&m_data[m_read_offset], src.color);
incrOffset<u32>();
return *this;
}
SharedBuffer<u8> NetworkPacket::oldForgePacket()
{
SharedBuffer<u8> sb(m_datasize + 2);
writeU16(&sb[0], m_command);
u8* datas = getU8Ptr(0);
if (datas != NULL)
memcpy(&sb[2], datas, m_datasize);
return sb;
}

@ -1,6 +1,5 @@
/* /*
Minetest Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr> Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
@ -21,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#ifndef NETWORKPACKET_HEADER #ifndef NETWORKPACKET_HEADER
#define NETWORKPACKET_HEADER #define NETWORKPACKET_HEADER
#include "util/pointer.h"
#include "util/numeric.h" #include "util/numeric.h"
#include "networkprotocol.h" #include "networkprotocol.h"
@ -29,57 +29,100 @@ class NetworkPacket
public: public:
NetworkPacket(u8 *data, u32 datasize, u16 peer_id); NetworkPacket(u8 *data, u32 datasize, u16 peer_id);
NetworkPacket(u16 command, u32 datasize, u16 peer_id);
NetworkPacket(u16 command, u32 datasize);
~NetworkPacket(); ~NetworkPacket();
// Getters // Getters
u32 getSize() { return m_datasize; } u32 getSize() { return m_datasize; }
u16 getPeerId() { return m_peer_id; } u16 getPeerId() { return m_peer_id; }
u16 getCommand() { return m_command; }
// Data extractors // Data extractors
char* getString(u32 from_offset); char* getString(u32 from_offset);
void putRawString(const char* src, u32 len);
NetworkPacket& operator>>(std::string& dst); NetworkPacket& operator>>(std::string& dst);
NetworkPacket& operator<<(std::string src);
void putLongString(std::string src);
NetworkPacket& operator>>(std::wstring& dst); NetworkPacket& operator>>(std::wstring& dst);
NetworkPacket& operator<<(std::wstring src);
std::string readLongString(); std::string readLongString();
char getChar(u32 offset); char getChar(u32 offset);
NetworkPacket& operator>>(char& dst); NetworkPacket& operator>>(char& dst);
NetworkPacket& operator<<(char src);
NetworkPacket& operator>>(bool& dst); NetworkPacket& operator>>(bool& dst);
NetworkPacket& operator<<(bool src);
u8 getU8(u32 offset); u8 getU8(u32 offset);
NetworkPacket& operator>>(u8& dst); NetworkPacket& operator>>(u8& dst);
NetworkPacket& operator<<(u8 src);
u8* getU8Ptr(u32 offset); u8* getU8Ptr(u32 offset);
u16 getU16(u32 from_offset); u16 getU16(u32 from_offset);
NetworkPacket& operator>>(u16& dst); NetworkPacket& operator>>(u16& dst);
u32 getU32(u32 from_offset); NetworkPacket& operator<<(u16 src);
NetworkPacket& operator>>(u32& dst); NetworkPacket& operator>>(u32& dst);
u64 getU64(u32 from_offset); NetworkPacket& operator<<(u32 src);
NetworkPacket& operator>>(u64& dst); NetworkPacket& operator>>(u64& dst);
NetworkPacket& operator<<(u64 src);
float getF1000(u32 offset);
NetworkPacket& operator>>(float& dst); NetworkPacket& operator>>(float& dst);
NetworkPacket& operator>>(v2f& dst); NetworkPacket& operator<<(float src);
NetworkPacket& operator>>(v3f& dst);
NetworkPacket& operator>>(v2f& dst);
NetworkPacket& operator<<(v2f src);
NetworkPacket& operator>>(v3f& dst);
NetworkPacket& operator<<(v3f src);
s16 getS16(u32 from_offset);
NetworkPacket& operator>>(s16& dst); NetworkPacket& operator>>(s16& dst);
s32 getS32(u32 from_offset); NetworkPacket& operator<<(s16 src);
NetworkPacket& operator>>(s32& dst); NetworkPacket& operator>>(s32& dst);
NetworkPacket& operator<<(s32 src);
NetworkPacket& operator>>(v2s32& dst); NetworkPacket& operator>>(v2s32& dst);
NetworkPacket& operator<<(v2s32 src);
v3s16 getV3S16(u32 from_offset);
NetworkPacket& operator>>(v3s16& dst); NetworkPacket& operator>>(v3s16& dst);
NetworkPacket& operator<<(v3s16 src);
v3s32 getV3S32(u32 from_offset);
NetworkPacket& operator>>(v3s32& dst); NetworkPacket& operator>>(v3s32& dst);
NetworkPacket& operator<<(v3s32 src);
protected: NetworkPacket& operator>>(video::SColor& dst);
u8 *m_data; NetworkPacket& operator<<(video::SColor src);
// Temp, we remove SharedBuffer when migration finished
SharedBuffer<u8> oldForgePacket();
private:
template<typename T> void checkDataSize()
{
if (m_read_offset + sizeof(T) > m_datasize) {
m_datasize += sizeof(T);
m_data.resize(m_datasize);
}
}
template<typename T> void incrOffset()
{
m_read_offset += sizeof(T);
}
std::vector<u8> m_data;
u32 m_datasize; u32 m_datasize;
u32 m_read_offset; u32 m_read_offset;
private: u16 m_command;
u16 m_peer_id; u16 m_peer_id;
}; };

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -93,3 +93,92 @@ const ToServerCommandHandler toServerCommandTable[TOSERVER_NUM_MSG_TYPES] =
{ "TOSERVER_BREATH", TOSERVER_STATE_INGAME, &Server::handleCommand_Breath }, // 0x42 { "TOSERVER_BREATH", TOSERVER_STATE_INGAME, &Server::handleCommand_Breath }, // 0x42
{ "TOSERVER_CLIENT_READY", TOSERVER_STATE_STARTUP, &Server::handleCommand_ClientReady }, // 0x43 { "TOSERVER_CLIENT_READY", TOSERVER_STATE_STARTUP, &Server::handleCommand_ClientReady }, // 0x43
}; };
const static ClientCommandFactory null_command_factory = { "TOCLIENT_NULL", 0, false };
const ClientCommandFactory clientCommandFactoryTable[TOCLIENT_NUM_MSG_TYPES] =
{
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
{ "TOCLIENT_INIT", 0, true }, // 0x10
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
{ "TOCLIENT_BLOCKDATA", 2, true }, // 0x20
{ "TOCLIENT_ADDNODE", 0, true }, // 0x21
{ "TOCLIENT_REMOVENODE", 0, true }, // 0x22
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
{ "TOCLIENT_INVENTORY", 0, true }, // 0x27
null_command_factory,
{ "TOCLIENT_TIME_OF_DAY", 0, true }, // 0x29
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
{ "TOCLIENT_CHAT_MESSAGE", 0, true }, // 0x30
{ "TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD", 0, true }, // 0x31
{ "TOCLIENT_ACTIVE_OBJECT_MESSAGES", 0, true }, // 0x32 Special packet, sent by 0 (rel) and 1 (unrel) channel
{ "TOCLIENT_HP", 0, true }, // 0x33
{ "TOCLIENT_MOVE_PLAYER", 0, true }, // 0x34
{ "TOCLIENT_ACCESS_DENIED", 0, true }, // 0x35
{ "TOCLIENT_PLAYERITEM", 0, false }, // 0x36 obsolete
{ "TOCLIENT_DEATHSCREEN", 0, true }, // 0x37
{ "TOCLIENT_MEDIA", 2, true }, // 0x38
{ "TOCLIENT_TOOLDEF", 0, false }, // 0x39 obsolete
{ "TOCLIENT_NODEDEF", 0, true }, // 0x3a
{ "TOCLIENT_CRAFTITEMDEF", 0, false }, // 0x3b obsolete
{ "TOCLIENT_ANNOUNCE_MEDIA", 0, true }, // 0x3c
{ "TOCLIENT_ITEMDEF", 0, true }, // 0x3d
null_command_factory,
{ "TOCLIENT_PLAY_SOUND", 0, true }, // 0x3f
{ "TOCLIENT_STOP_SOUND", 0, true }, // 0x40
{ "TOCLIENT_PRIVILEGES", 0, true }, // 0x41
{ "TOCLIENT_INVENTORY_FORMSPEC", 0, true }, // 0x42
{ "TOCLIENT_DETACHED_INVENTORY", 0, true }, // 0x43
{ "TOCLIENT_SHOW_FORMSPEC", 0, true }, // 0x44
{ "TOCLIENT_MOVEMENT", 0, true }, // 0x45
{ "TOCLIENT_SPAWN_PARTICLE", 0, true }, // 0x46
{ "TOCLIENT_ADD_PARTICLESPAWNER", 0, true }, // 0x47
{ "TOCLIENT_DELETE_PARTICLESPAWNER", 0, true }, // 0x48
{ "TOCLIENT_HUDADD", 1, true }, // 0x49
{ "TOCLIENT_HUDRM", 1, true }, // 0x4a
{ "TOCLIENT_HUDCHANGE", 0, true }, // 0x4b
{ "TOCLIENT_HUD_SET_FLAGS", 0, true }, // 0x4c
{ "TOCLIENT_HUD_SET_PARAM", 0, true }, // 0x4d
{ "TOCLIENT_BREATH", 0, true }, // 0x4e
{ "TOCLIENT_SET_SKY", 0, true }, // 0x4f
{ "TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO", 0, true }, // 0x50
{ "TOCLIENT_LOCAL_PLAYER_ANIMATIONS", 0, true }, // 0x51
{ "TOCLIENT_EYE_OFFSET", 0, true }, // 0x52
};

@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "server.h" #include "server.h"
#include "networkprotocol.h" #include "networkprotocol.h"
#include "toserverpacket.h" #include "networkpacket.h"
enum ToServerConnectionState { enum ToServerConnectionState {
TOSERVER_STATE_NOT_CONNECTED, TOSERVER_STATE_NOT_CONNECTED,
@ -35,9 +35,18 @@ struct ToServerCommandHandler
{ {
const std::string name; const std::string name;
ToServerConnectionState state; ToServerConnectionState state;
void (Server::*handler)(ToServerPacket* pkt); void (Server::*handler)(NetworkPacket* pkt);
};
struct ClientCommandFactory
{
const char* name;
u16 channel;
bool reliable;
}; };
extern const ToServerCommandHandler toServerCommandTable[TOSERVER_NUM_MSG_TYPES]; extern const ToServerCommandHandler toServerCommandTable[TOSERVER_NUM_MSG_TYPES];
extern const ClientCommandFactory clientCommandFactoryTable[TOCLIENT_NUM_MSG_TYPES];
#endif #endif

@ -1,28 +0,0 @@
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "toclientpacket.h"
#include "util/serialize.h"
ToClientPacket::ToClientPacket(u8 *data, u32 datasize, u16 peer_id):
NetworkPacket(data, datasize, peer_id)
{
m_command = (ToClientCommand)readU16(&data[0]);
}

@ -1,38 +0,0 @@
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef TOCLIENTPACKET_HEADER
#define TOCLIENTPACKET_HEADER
#include "util/numeric.h"
#include "networkprotocol.h"
#include "networkpacket.h"
class ToClientPacket: public NetworkPacket
{
public:
ToClientPacket(u8 *data, u32 datasize, u16 peer_id);
ToClientCommand getCommand() { return m_command; }
private:
ToClientCommand m_command;
};
#endif

@ -1,28 +0,0 @@
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "toserverpacket.h"
#include "util/serialize.h"
ToServerPacket::ToServerPacket(u8 *data, u32 datasize, u16 peer_id):
NetworkPacket(data, datasize, peer_id)
{
m_command = (ToServerCommand)readU16(&data[0]);
}

@ -1,38 +0,0 @@
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef TOSERVERPACKET_HEADER
#define TOSERVERPACKET_HEADER
#include "util/numeric.h"
#include "networkprotocol.h"
#include "networkpacket.h"
class ToServerPacket: public NetworkPacket
{
public:
ToServerPacket(u8 *data, u32 datasize, u16 peer_id);
ToServerCommand getCommand() { return m_command; }
private:
ToServerCommand m_command;
};
#endif

File diff suppressed because it is too large Load Diff

@ -20,7 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#ifndef SERVER_HEADER #ifndef SERVER_HEADER
#define SERVER_HEADER #define SERVER_HEADER
#include "connection.h" #include "network/connection.h"
#include "irr_v3d.h" #include "irr_v3d.h"
#include "map.h" #include "map.h"
#include "hud.h" #include "hud.h"
@ -33,7 +33,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "util/thread.h" #include "util/thread.h"
#include "environment.h" #include "environment.h"
#include "clientiface.h" #include "clientiface.h"
#include "network/toserverpacket.h" #include "network/networkpacket.h"
#include <string> #include <string>
#include <list> #include <list>
#include <map> #include <map>
@ -193,32 +193,34 @@ public:
* Command Handlers * Command Handlers
*/ */
void handleCommand(ToServerPacket* pkt); void handleCommand(NetworkPacket* pkt);
void handleCommand_Null(ToServerPacket* pkt) {}; void handleCommand_Null(NetworkPacket* pkt) {};
void handleCommand_Deprecated(ToServerPacket* pkt); void handleCommand_Deprecated(NetworkPacket* pkt);
void handleCommand_Init(ToServerPacket* pkt); void handleCommand_Init(NetworkPacket* pkt);
void handleCommand_Init2(ToServerPacket* pkt); void handleCommand_Init2(NetworkPacket* pkt);
void handleCommand_RequestMedia(ToServerPacket* pkt); void handleCommand_RequestMedia(NetworkPacket* pkt);
void handleCommand_ReceivedMedia(ToServerPacket* pkt); void handleCommand_ReceivedMedia(NetworkPacket* pkt);
void handleCommand_ClientReady(ToServerPacket* pkt); void handleCommand_ClientReady(NetworkPacket* pkt);
void handleCommand_GotBlocks(ToServerPacket* pkt); void handleCommand_GotBlocks(NetworkPacket* pkt);
void handleCommand_PlayerPos(ToServerPacket* pkt); void handleCommand_PlayerPos(NetworkPacket* pkt);
void handleCommand_DeletedBlocks(ToServerPacket* pkt); void handleCommand_DeletedBlocks(NetworkPacket* pkt);
void handleCommand_InventoryAction(ToServerPacket* pkt); void handleCommand_InventoryAction(NetworkPacket* pkt);
void handleCommand_ChatMessage(ToServerPacket* pkt); void handleCommand_ChatMessage(NetworkPacket* pkt);
void handleCommand_Damage(ToServerPacket* pkt); void handleCommand_Damage(NetworkPacket* pkt);
void handleCommand_Breath(ToServerPacket* pkt); void handleCommand_Breath(NetworkPacket* pkt);
void handleCommand_Password(ToServerPacket* pkt); void handleCommand_Password(NetworkPacket* pkt);
void handleCommand_PlayerItem(ToServerPacket* pkt); void handleCommand_PlayerItem(NetworkPacket* pkt);
void handleCommand_Respawn(ToServerPacket* pkt); void handleCommand_Respawn(NetworkPacket* pkt);
void handleCommand_Interact(ToServerPacket* pkt); void handleCommand_Interact(NetworkPacket* pkt);
void handleCommand_RemovedSounds(ToServerPacket* pkt); void handleCommand_RemovedSounds(NetworkPacket* pkt);
void handleCommand_NodeMetaFields(ToServerPacket* pkt); void handleCommand_NodeMetaFields(NetworkPacket* pkt);
void handleCommand_InventoryFields(ToServerPacket* pkt); void handleCommand_InventoryFields(NetworkPacket* pkt);
void ProcessData(u8 *data, u32 datasize, u16 peer_id); void ProcessData(u8 *data, u32 datasize, u16 peer_id);
void Send(NetworkPacket* pkt);
// Environment must be locked when called // Environment must be locked when called
void setTimeOfDay(u32 time); void setTimeOfDay(u32 time);

@ -24,7 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "player.h" #include "player.h"
#include "main.h" #include "main.h"
#include "socket.h" #include "socket.h"
#include "connection.h" #include "network/connection.h"
#include "serialization.h" #include "serialization.h"
#include "voxel.h" #include "voxel.h"
#include "collision.h" #include "collision.h"
@ -1986,168 +1986,57 @@ struct TestConnection: public TestBase
catch(con::NoIncomingDataException &e) catch(con::NoIncomingDataException &e)
{ {
} }
#if 1
/* /*
Simple send-receive test Simple send-receive test
*/ */
{ {
/*u8 data[] = "Hello World!"; NetworkPacket* pkt = new NetworkPacket((u8*) "Hello World !", 14, 0);
u32 datasize = sizeof(data);*/
SharedBuffer<u8> data = SharedBufferFromString("Hello World!"); SharedBuffer<u8> sentdata = pkt->oldForgePacket();
infostream<<"** running client.Send()"<<std::endl; infostream<<"** running client.Send()"<<std::endl;
client.Send(PEER_ID_SERVER, 0, data, true); client.Send(PEER_ID_SERVER, 0, pkt, true);
sleep_ms(50); sleep_ms(50);
u16 peer_id; u16 peer_id;
SharedBuffer<u8> recvdata; SharedBuffer<u8> recvdata;
infostream<<"** running server.Receive()"<<std::endl; infostream << "** running server.Receive()" << std::endl;
u32 size = server.Receive(peer_id, recvdata); u32 size = server.Receive(peer_id, recvdata);
infostream<<"** Server received: peer_id="<<peer_id infostream << "** Server received: peer_id=" << peer_id
<<", size="<<size << ", size=" << size
<<", data="<<*data << ", data=" << (const char*)pkt->getU8Ptr(0)
<<std::endl; << std::endl;
UASSERT(memcmp(*data, *recvdata, data.getSize()) == 0);
UASSERT(memcmp(*sentdata, *recvdata, recvdata.getSize()) == 0);
} }
#endif
u16 peer_id_client = 2; u16 peer_id_client = 2;
#if 0
/*
Send consequent packets in different order
Not compatible with new Connection, thus commented out.
*/
{
//u8 data1[] = "hello1";
//u8 data2[] = "hello2";
SharedBuffer<u8> data1 = SharedBufferFromString("hello1");
SharedBuffer<u8> data2 = SharedBufferFromString("Hello2");
Address client_address =
server.GetPeerAddress(peer_id_client);
infostream<<"*** Sending packets in wrong order (2,1,2)"
<<std::endl;
u8 chn = 0;
con::Channel *ch = &server.getPeer(peer_id_client)->channels[chn];
u16 sn = ch->next_outgoing_seqnum;
ch->next_outgoing_seqnum = sn+1;
server.Send(peer_id_client, chn, data2, true);
ch->next_outgoing_seqnum = sn;
server.Send(peer_id_client, chn, data1, true);
ch->next_outgoing_seqnum = sn+1;
server.Send(peer_id_client, chn, data2, true);
sleep_ms(50);
infostream<<"*** Receiving the packets"<<std::endl;
u16 peer_id;
SharedBuffer<u8> recvdata;
u32 size;
infostream<<"** running client.Receive()"<<std::endl;
peer_id = 132;
size = client.Receive(peer_id, recvdata);
infostream<<"** Client received: peer_id="<<peer_id
<<", size="<<size
<<", data="<<*recvdata
<<std::endl;
UASSERT(size == data1.getSize());
UASSERT(memcmp(*data1, *recvdata, data1.getSize()) == 0);
UASSERT(peer_id == PEER_ID_SERVER);
infostream<<"** running client.Receive()"<<std::endl;
peer_id = 132;
size = client.Receive(peer_id, recvdata);
infostream<<"** Client received: peer_id="<<peer_id
<<", size="<<size
<<", data="<<*recvdata
<<std::endl;
UASSERT(size == data2.getSize());
UASSERT(memcmp(*data2, *recvdata, data2.getSize()) == 0);
UASSERT(peer_id == PEER_ID_SERVER);
bool got_exception = false;
try
{
infostream<<"** running client.Receive()"<<std::endl;
peer_id = 132;
size = client.Receive(peer_id, recvdata);
infostream<<"** Client received: peer_id="<<peer_id
<<", size="<<size
<<", data="<<*recvdata
<<std::endl;
}
catch(con::NoIncomingDataException &e)
{
infostream<<"** No incoming data for client"<<std::endl;
got_exception = true;
}
UASSERT(got_exception);
}
#endif
#if 0
/*
Send large amounts of packets (infinite test)
Commented out because of infinity.
*/
{
infostream<<"Sending large amounts of packets (infinite test)"<<std::endl;
int sendcount = 0;
for(;;){
int datasize = myrand_range(0,5)==0?myrand_range(100,10000):myrand_range(0,100);
infostream<<"datasize="<<datasize<<std::endl;
SharedBuffer<u8> data1(datasize);
for(u16 i=0; i<datasize; i++)
data1[i] = i/4;
int sendtimes = myrand_range(1,10);
for(int i=0; i<sendtimes; i++){
server.Send(peer_id_client, 0, data1, true);
sendcount++;
}
infostream<<"sendcount="<<sendcount<<std::endl;
//int receivetimes = myrand_range(1,20);
int receivetimes = 20;
for(int i=0; i<receivetimes; i++){
SharedBuffer<u8> recvdata;
u16 peer_id = 132;
u16 size = 0;
bool received = false;
try{
size = client.Receive(peer_id, recvdata);
received = true;
}catch(con::NoIncomingDataException &e){
}
}
}
}
#endif
/* /*
Send a large packet Send a large packet
*/ */
{ {
const int datasize = 30000; const int datasize = 30000;
SharedBuffer<u8> data1(datasize); NetworkPacket* pkt = new NetworkPacket(0, datasize);
for(u16 i=0; i<datasize; i++){ for(u16 i=0; i<datasize; i++){
data1[i] = i/4; *pkt << (u8) i/4;
} }
infostream<<"Sending data (size="<<datasize<<"):"; infostream<<"Sending data (size="<<datasize<<"):";
for(int i=0; i<datasize && i<20; i++){ for(int i=0; i<datasize && i<20; i++){
if(i%2==0) infostream<<" "; if(i%2==0) infostream<<" ";
char buf[10]; char buf[10];
snprintf(buf, 10, "%.2X", ((int)((const char*)*data1)[i])&0xff); snprintf(buf, 10, "%.2X", ((int)((const char*)pkt->getU8Ptr(0))[i])&0xff);
infostream<<buf; infostream<<buf;
} }
if(datasize>20) if(datasize>20)
infostream<<"..."; infostream<<"...";
infostream<<std::endl; infostream<<std::endl;
server.Send(peer_id_client, 0, data1, true); SharedBuffer<u8> sentdata = pkt->oldForgePacket();
server.Send(peer_id_client, 0, pkt, true);
//sleep_ms(3000); //sleep_ms(3000);
@ -2183,7 +2072,7 @@ struct TestConnection: public TestBase
infostream<<"..."; infostream<<"...";
infostream<<std::endl; infostream<<std::endl;
UASSERT(memcmp(*data1, *recvdata, data1.getSize()) == 0); UASSERT(memcmp(*sentdata, *recvdata, recvdata.getSize()) == 0);
UASSERT(peer_id == PEER_ID_SERVER); UASSERT(peer_id == PEER_ID_SERVER);
} }