aboutsummaryrefslogtreecommitdiff
path: root/src/network
diff options
context:
space:
mode:
Diffstat (limited to 'src/network')
-rw-r--r--src/network/address.cpp2
-rw-r--r--src/network/clientopcodes.cpp414
-rw-r--r--src/network/clientopcodes.h11
-rw-r--r--src/network/clientpackethandler.cpp616
-rw-r--r--src/network/connection.cpp525
-rw-r--r--src/network/connection.h392
-rw-r--r--src/network/connectionthreads.cpp779
-rw-r--r--src/network/networkpacket.cpp132
-rw-r--r--src/network/networkprotocol.h151
-rw-r--r--src/network/serveropcodes.cpp396
-rw-r--r--src/network/serveropcodes.h11
-rw-r--r--src/network/serverpackethandler.cpp745
12 files changed, 2018 insertions, 2156 deletions
diff --git a/src/network/address.cpp b/src/network/address.cpp
index d24a56027..05678aa62 100644
--- a/src/network/address.cpp
+++ b/src/network/address.cpp
@@ -283,7 +283,7 @@ bool Address::isLocalhost() const
auto addr = m_address.ipv6.sin6_addr.s6_addr;
return memcmp(addr, localhost_bytes, 16) == 0 ||
- memcmp(addr, mapped_ipv4_localhost, 13) == 0;
+ memcmp(addr, mapped_ipv4_localhost, 13) == 0;
}
return (m_address.ipv4.sin_addr.s_addr & 0xFF) == 0x7f;
diff --git a/src/network/clientopcodes.cpp b/src/network/clientopcodes.cpp
index b7dd78f65..f812a08a1 100644
--- a/src/network/clientopcodes.cpp
+++ b/src/network/clientopcodes.cpp
@@ -20,152 +20,111 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "clientopcodes.h"
-const static ToClientCommandHandler null_command_handler = {
- "TOCLIENT_NULL", TOCLIENT_STATE_ALL, &Client::handleCommand_Null};
+const static ToClientCommandHandler null_command_handler = {"TOCLIENT_NULL", TOCLIENT_STATE_ALL, &Client::handleCommand_Null};
-const ToClientCommandHandler toClientCommandTable[TOCLIENT_NUM_MSG_TYPES] = {
- null_command_handler, // 0x00 (never use this)
- null_command_handler, // 0x01
- {"TOCLIENT_HELLO", TOCLIENT_STATE_NOT_CONNECTED,
- &Client::handleCommand_Hello}, // 0x02
- {"TOCLIENT_AUTH_ACCEPT", TOCLIENT_STATE_NOT_CONNECTED,
- &Client::handleCommand_AuthAccept}, // 0x03
- {"TOCLIENT_ACCEPT_SUDO_MODE", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_AcceptSudoMode}, // 0x04
- {"TOCLIENT_DENY_SUDO_MODE", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_DenySudoMode}, // 0x05
- null_command_handler, // 0x06
- null_command_handler, // 0x07
- null_command_handler, // 0x08
- null_command_handler, // 0x09
- {"TOCLIENT_ACCESS_DENIED", TOCLIENT_STATE_NOT_CONNECTED,
- &Client::handleCommand_AccessDenied}, // 0x0A
- null_command_handler, // 0x0B
- null_command_handler, // 0x0C
- null_command_handler, // 0x0D
- null_command_handler, // 0x0E
- null_command_handler, // 0x0F
- null_command_handler, // 0x10
- null_command_handler, null_command_handler, null_command_handler,
- null_command_handler, null_command_handler, null_command_handler,
- null_command_handler, null_command_handler, null_command_handler,
- null_command_handler, null_command_handler, null_command_handler,
- null_command_handler, null_command_handler, null_command_handler,
- {"TOCLIENT_BLOCKDATA", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_BlockData}, // 0x20
- {"TOCLIENT_ADDNODE", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_AddNode}, // 0x21
- {"TOCLIENT_REMOVENODE", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_RemoveNode}, // 0x22
- null_command_handler, null_command_handler, null_command_handler,
- null_command_handler,
- {"TOCLIENT_INVENTORY", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_Inventory}, // 0x27
- null_command_handler,
- {"TOCLIENT_TIME_OF_DAY", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_TimeOfDay}, // 0x29
- {"TOCLIENT_CSM_RESTRICTION_FLAGS", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_CSMRestrictionFlags}, // 0x2A
- {"TOCLIENT_PLAYER_SPEED", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_PlayerSpeed}, // 0x2B
- {"TOCLIENT_MEDIA_PUSH", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_MediaPush}, // 0x2C
- null_command_handler, null_command_handler,
- {"TOCLIENT_CHAT_MESSAGE", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_ChatMessage}, // 0x2F
- null_command_handler, // 0x30
- {"TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_ActiveObjectRemoveAdd}, // 0x31
- {"TOCLIENT_ACTIVE_OBJECT_MESSAGES", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_ActiveObjectMessages}, // 0x32
- {"TOCLIENT_HP", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_HP}, // 0x33
- {"TOCLIENT_MOVE_PLAYER", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_MovePlayer}, // 0x34
- {"TOCLIENT_ACCESS_DENIED_LEGACY", TOCLIENT_STATE_NOT_CONNECTED,
- &Client::handleCommand_AccessDenied}, // 0x35
- {"TOCLIENT_FOV", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_Fov}, // 0x36
- {"TOCLIENT_DEATHSCREEN", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_DeathScreen}, // 0x37
- {"TOCLIENT_MEDIA", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_Media}, // 0x38
- null_command_handler,
- {"TOCLIENT_NODEDEF", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_NodeDef}, // 0x3a
- null_command_handler,
- {"TOCLIENT_ANNOUNCE_MEDIA", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_AnnounceMedia}, // 0x3c
- {"TOCLIENT_ITEMDEF", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_ItemDef}, // 0x3d
- null_command_handler,
- {"TOCLIENT_PLAY_SOUND", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_PlaySound}, // 0x3f
- {"TOCLIENT_STOP_SOUND", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_StopSound}, // 0x40
- {"TOCLIENT_PRIVILEGES", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_Privileges}, // 0x41
- {"TOCLIENT_INVENTORY_FORMSPEC", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_InventoryFormSpec}, // 0x42
- {"TOCLIENT_DETACHED_INVENTORY", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_DetachedInventory}, // 0x43
- {"TOCLIENT_SHOW_FORMSPEC", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_ShowFormSpec}, // 0x44
- {"TOCLIENT_MOVEMENT", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_Movement}, // 0x45
- {"TOCLIENT_SPAWN_PARTICLE", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_SpawnParticle}, // 0x46
- {"TOCLIENT_ADD_PARTICLESPAWNER", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_AddParticleSpawner}, // 0x47
- null_command_handler,
- {"TOCLIENT_HUDADD", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_HudAdd}, // 0x49
- {"TOCLIENT_HUDRM", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_HudRemove}, // 0x4a
- {"TOCLIENT_HUDCHANGE", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_HudChange}, // 0x4b
- {"TOCLIENT_HUD_SET_FLAGS", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_HudSetFlags}, // 0x4c
- {"TOCLIENT_HUD_SET_PARAM", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_HudSetParam}, // 0x4d
- {"TOCLIENT_BREATH", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_Breath}, // 0x4e
- {"TOCLIENT_SET_SKY", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_HudSetSky}, // 0x4f
- {"TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_OverrideDayNightRatio}, // 0x50
- {"TOCLIENT_LOCAL_PLAYER_ANIMATIONS", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_LocalPlayerAnimations}, // 0x51
- {"TOCLIENT_EYE_OFFSET", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_EyeOffset}, // 0x52
- {"TOCLIENT_DELETE_PARTICLESPAWNER", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_DeleteParticleSpawner}, // 0x53
- {"TOCLIENT_CLOUD_PARAMS", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_CloudParams}, // 0x54
- {"TOCLIENT_FADE_SOUND", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_FadeSound}, // 0x55
- {"TOCLIENT_UPDATE_PLAYER_LIST", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_UpdatePlayerList}, // 0x56
- {"TOCLIENT_MODCHANNEL_MSG", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_ModChannelMsg}, // 0x57
- {"TOCLIENT_MODCHANNEL_SIGNAL", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_ModChannelSignal}, // 0x58
- {"TOCLIENT_NODEMETA_CHANGED", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_NodemetaChanged}, // 0x59
- {"TOCLIENT_SET_SUN", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_HudSetSun}, // 0x5a
- {"TOCLIENT_SET_MOON", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_HudSetMoon}, // 0x5b
- {"TOCLIENT_SET_STARS", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_HudSetStars}, // 0x5c
- null_command_handler, null_command_handler, null_command_handler,
- {"TOCLIENT_SRP_BYTES_S_B", TOCLIENT_STATE_NOT_CONNECTED,
- &Client::handleCommand_SrpBytesSandB}, // 0x60
- {"TOCLIENT_FORMSPEC_PREPEND", TOCLIENT_STATE_CONNECTED,
- &Client::handleCommand_FormspecPrepend}, // 0x61,
+const ToClientCommandHandler toClientCommandTable[TOCLIENT_NUM_MSG_TYPES] =
+{
+ null_command_handler, // 0x00 (never use this)
+ null_command_handler, // 0x01
+ { "TOCLIENT_HELLO", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_Hello }, // 0x02
+ { "TOCLIENT_AUTH_ACCEPT", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_AuthAccept }, // 0x03
+ { "TOCLIENT_ACCEPT_SUDO_MODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AcceptSudoMode}, // 0x04
+ { "TOCLIENT_DENY_SUDO_MODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DenySudoMode}, // 0x05
+ null_command_handler, // 0x06
+ null_command_handler, // 0x07
+ null_command_handler, // 0x08
+ null_command_handler, // 0x09
+ { "TOCLIENT_ACCESS_DENIED", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_AccessDenied }, // 0x0A
+ null_command_handler, // 0x0B
+ null_command_handler, // 0x0C
+ null_command_handler, // 0x0D
+ null_command_handler, // 0x0E
+ null_command_handler, // 0x0F
+ null_command_handler, // 0x10
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ { "TOCLIENT_BLOCKDATA", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_BlockData }, // 0x20
+ { "TOCLIENT_ADDNODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AddNode }, // 0x21
+ { "TOCLIENT_REMOVENODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_RemoveNode }, // 0x22
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ { "TOCLIENT_INVENTORY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Inventory }, // 0x27
+ null_command_handler,
+ { "TOCLIENT_TIME_OF_DAY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_TimeOfDay }, // 0x29
+ { "TOCLIENT_CSM_RESTRICTION_FLAGS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_CSMRestrictionFlags }, // 0x2A
+ { "TOCLIENT_PLAYER_SPEED", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_PlayerSpeed }, // 0x2B
+ { "TOCLIENT_MEDIA_PUSH", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_MediaPush }, // 0x2C
+ null_command_handler,
+ null_command_handler,
+ { "TOCLIENT_CHAT_MESSAGE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ChatMessage }, // 0x2F
+ null_command_handler, // 0x30
+ { "TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ActiveObjectRemoveAdd }, // 0x31
+ { "TOCLIENT_ACTIVE_OBJECT_MESSAGES", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ActiveObjectMessages }, // 0x32
+ { "TOCLIENT_HP", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HP }, // 0x33
+ { "TOCLIENT_MOVE_PLAYER", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_MovePlayer }, // 0x34
+ { "TOCLIENT_ACCESS_DENIED_LEGACY", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_AccessDenied }, // 0x35
+ { "TOCLIENT_FOV", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Fov }, // 0x36
+ { "TOCLIENT_DEATHSCREEN", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DeathScreen }, // 0x37
+ { "TOCLIENT_MEDIA", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Media }, // 0x38
+ null_command_handler,
+ { "TOCLIENT_NODEDEF", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_NodeDef }, // 0x3a
+ null_command_handler,
+ { "TOCLIENT_ANNOUNCE_MEDIA", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AnnounceMedia }, // 0x3c
+ { "TOCLIENT_ITEMDEF", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ItemDef }, // 0x3d
+ null_command_handler,
+ { "TOCLIENT_PLAY_SOUND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_PlaySound }, // 0x3f
+ { "TOCLIENT_STOP_SOUND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_StopSound }, // 0x40
+ { "TOCLIENT_PRIVILEGES", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Privileges }, // 0x41
+ { "TOCLIENT_INVENTORY_FORMSPEC", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_InventoryFormSpec }, // 0x42
+ { "TOCLIENT_DETACHED_INVENTORY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DetachedInventory }, // 0x43
+ { "TOCLIENT_SHOW_FORMSPEC", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ShowFormSpec }, // 0x44
+ { "TOCLIENT_MOVEMENT", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Movement }, // 0x45
+ { "TOCLIENT_SPAWN_PARTICLE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_SpawnParticle }, // 0x46
+ { "TOCLIENT_ADD_PARTICLESPAWNER", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AddParticleSpawner }, // 0x47
+ null_command_handler,
+ { "TOCLIENT_HUDADD", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudAdd }, // 0x49
+ { "TOCLIENT_HUDRM", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudRemove }, // 0x4a
+ { "TOCLIENT_HUDCHANGE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudChange }, // 0x4b
+ { "TOCLIENT_HUD_SET_FLAGS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetFlags }, // 0x4c
+ { "TOCLIENT_HUD_SET_PARAM", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetParam }, // 0x4d
+ { "TOCLIENT_BREATH", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Breath }, // 0x4e
+ { "TOCLIENT_SET_SKY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetSky }, // 0x4f
+ { "TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_OverrideDayNightRatio }, // 0x50
+ { "TOCLIENT_LOCAL_PLAYER_ANIMATIONS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_LocalPlayerAnimations }, // 0x51
+ { "TOCLIENT_EYE_OFFSET", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_EyeOffset }, // 0x52
+ { "TOCLIENT_DELETE_PARTICLESPAWNER", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DeleteParticleSpawner }, // 0x53
+ { "TOCLIENT_CLOUD_PARAMS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_CloudParams }, // 0x54
+ { "TOCLIENT_FADE_SOUND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_FadeSound }, // 0x55
+ { "TOCLIENT_UPDATE_PLAYER_LIST", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_UpdatePlayerList }, // 0x56
+ { "TOCLIENT_MODCHANNEL_MSG", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ModChannelMsg }, // 0x57
+ { "TOCLIENT_MODCHANNEL_SIGNAL", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ModChannelSignal }, // 0x58
+ { "TOCLIENT_NODEMETA_CHANGED", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_NodemetaChanged }, // 0x59
+ { "TOCLIENT_SET_SUN", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetSun }, // 0x5a
+ { "TOCLIENT_SET_MOON", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetMoon }, // 0x5b
+ { "TOCLIENT_SET_STARS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetStars }, // 0x5c
+ null_command_handler,
+ null_command_handler,
+ null_command_handler,
+ { "TOCLIENT_SRP_BYTES_S_B", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_SrpBytesSandB }, // 0x60
+ { "TOCLIENT_FORMSPEC_PREPEND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_FormspecPrepend }, // 0x61,
};
-const static ServerCommandFactory null_command_factory = {"TOSERVER_NULL", 0, false};
+const static ServerCommandFactory null_command_factory = { "TOSERVER_NULL", 0, false };
/*
Channels used for Client -> Server communication
@@ -177,88 +136,89 @@ const static ServerCommandFactory null_command_factory = {"TOSERVER_NULL", 0, fa
the same objects are *required* to be in the same channel.
*/
-const ServerCommandFactory serverCommandFactoryTable[TOSERVER_NUM_MSG_TYPES] = {
- null_command_factory, // 0x00
- null_command_factory, // 0x01
- {"TOSERVER_INIT", 1, false}, // 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
- null_command_factory, // 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
- {"TOSERVER_MODCHANNEL_JOIN", 0, true}, // 0x17
- {"TOSERVER_MODCHANNEL_LEAVE", 0, true}, // 0x18
- {"TOSERVER_MODCHANNEL_MSG", 0, true}, // 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
- null_command_factory, // 0x27
- null_command_factory, // 0x28
- null_command_factory, // 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
- null_command_factory, // 0x30
- {"TOSERVER_INVENTORY_ACTION", 0, true}, // 0x31
- {"TOSERVER_CHAT_MESSAGE", 0, true}, // 0x32
- null_command_factory, // 0x33
- null_command_factory, // 0x34
- {"TOSERVER_DAMAGE", 0, true}, // 0x35
- null_command_factory, // 0x36
- {"TOSERVER_PLAYERITEM", 0, true}, // 0x37
- {"TOSERVER_RESPAWN", 0, true}, // 0x38
- {"TOSERVER_INTERACT", 0, true}, // 0x39
- {"TOSERVER_REMOVED_SOUNDS", 2, 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
- null_command_factory, // 0x41
- null_command_factory, // 0x42
- {"TOSERVER_CLIENT_READY", 1, true}, // 0x43
- null_command_factory, // 0x44
- null_command_factory, // 0x45
- null_command_factory, // 0x46
- null_command_factory, // 0x47
- null_command_factory, // 0x48
- null_command_factory, // 0x49
- null_command_factory, // 0x4a
- null_command_factory, // 0x4b
- null_command_factory, // 0x4c
- null_command_factory, // 0x4d
- null_command_factory, // 0x4e
- null_command_factory, // 0x4f
- {"TOSERVER_FIRST_SRP", 1, true}, // 0x50
- {"TOSERVER_SRP_BYTES_A", 1, true}, // 0x51
- {"TOSERVER_SRP_BYTES_M", 1, true}, // 0x52
+const ServerCommandFactory serverCommandFactoryTable[TOSERVER_NUM_MSG_TYPES] =
+{
+ null_command_factory, // 0x00
+ null_command_factory, // 0x01
+ { "TOSERVER_INIT", 1, false }, // 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
+ null_command_factory, // 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
+ { "TOSERVER_MODCHANNEL_JOIN", 0, true }, // 0x17
+ { "TOSERVER_MODCHANNEL_LEAVE", 0, true }, // 0x18
+ { "TOSERVER_MODCHANNEL_MSG", 0, true }, // 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
+ null_command_factory, // 0x27
+ null_command_factory, // 0x28
+ null_command_factory, // 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
+ null_command_factory, // 0x30
+ { "TOSERVER_INVENTORY_ACTION", 0, true }, // 0x31
+ { "TOSERVER_CHAT_MESSAGE", 0, true }, // 0x32
+ null_command_factory, // 0x33
+ null_command_factory, // 0x34
+ { "TOSERVER_DAMAGE", 0, true }, // 0x35
+ null_command_factory, // 0x36
+ { "TOSERVER_PLAYERITEM", 0, true }, // 0x37
+ { "TOSERVER_RESPAWN", 0, true }, // 0x38
+ { "TOSERVER_INTERACT", 0, true }, // 0x39
+ { "TOSERVER_REMOVED_SOUNDS", 2, 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
+ null_command_factory, // 0x41
+ null_command_factory, // 0x42
+ { "TOSERVER_CLIENT_READY", 1, true }, // 0x43
+ null_command_factory, // 0x44
+ null_command_factory, // 0x45
+ null_command_factory, // 0x46
+ null_command_factory, // 0x47
+ null_command_factory, // 0x48
+ null_command_factory, // 0x49
+ null_command_factory, // 0x4a
+ null_command_factory, // 0x4b
+ null_command_factory, // 0x4c
+ null_command_factory, // 0x4d
+ null_command_factory, // 0x4e
+ null_command_factory, // 0x4f
+ { "TOSERVER_FIRST_SRP", 1, true }, // 0x50
+ { "TOSERVER_SRP_BYTES_A", 1, true }, // 0x51
+ { "TOSERVER_SRP_BYTES_M", 1, true }, // 0x52
};
diff --git a/src/network/clientopcodes.h b/src/network/clientopcodes.h
index d984d0cb7..d03dc457d 100644
--- a/src/network/clientopcodes.h
+++ b/src/network/clientopcodes.h
@@ -25,8 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
class NetworkPacket;
-enum ToClientConnectionState
-{
+enum ToClientConnectionState {
TOCLIENT_STATE_NOT_CONNECTED,
TOCLIENT_STATE_CONNECTED,
TOCLIENT_STATE_ALL,
@@ -34,14 +33,14 @@ enum ToClientConnectionState
struct ToClientCommandHandler
{
- const char *name;
- ToClientConnectionState state;
- void (Client::*handler)(NetworkPacket *pkt);
+ const char* name;
+ ToClientConnectionState state;
+ void (Client::*handler)(NetworkPacket* pkt);
};
struct ServerCommandFactory
{
- const char *name;
+ const char* name;
u8 channel;
bool reliable;
};
diff --git a/src/network/clientpackethandler.cpp b/src/network/clientpackethandler.cpp
index 7e72bc549..f0fb09fad 100644
--- a/src/network/clientpackethandler.cpp
+++ b/src/network/clientpackethandler.cpp
@@ -46,14 +46,14 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "gettext.h"
#include "skyparams.h"
-void Client::handleCommand_Deprecated(NetworkPacket *pkt)
+void Client::handleCommand_Deprecated(NetworkPacket* pkt)
{
infostream << "Got deprecated command "
- << toClientCommandTable[pkt->getCommand()].name << " from peer "
- << pkt->getPeerId() << "!" << std::endl;
+ << toClientCommandTable[pkt->getCommand()].name << " from peer "
+ << pkt->getPeerId() << "!" << std::endl;
}
-void Client::handleCommand_Hello(NetworkPacket *pkt)
+void Client::handleCommand_Hello(NetworkPacket* pkt)
{
if (pkt->getSize() < 1)
return;
@@ -63,38 +63,39 @@ void Client::handleCommand_Hello(NetworkPacket *pkt)
u16 compression_mode;
u32 auth_mechs;
std::string username_legacy; // for case insensitivity
- *pkt >> serialization_ver >> compression_mode >> proto_ver >> auth_mechs >>
- username_legacy;
+ *pkt >> serialization_ver >> compression_mode >> proto_ver
+ >> auth_mechs >> username_legacy;
// Chose an auth method we support
AuthMechanism chosen_auth_mechanism = choseAuthMech(auth_mechs);
infostream << "Client: TOCLIENT_HELLO received with "
- << "serialization_ver=" << (u32)serialization_ver
- << ", auth_mechs=" << auth_mechs << ", proto_ver=" << proto_ver
- << ", compression_mode=" << compression_mode
- << ". Doing auth with mech " << chosen_auth_mechanism << std::endl;
+ << "serialization_ver=" << (u32)serialization_ver
+ << ", auth_mechs=" << auth_mechs
+ << ", proto_ver=" << proto_ver
+ << ", compression_mode=" << compression_mode
+ << ". Doing auth with mech " << chosen_auth_mechanism << std::endl;
if (!ser_ver_supported(serialization_ver)) {
infostream << "Client: TOCLIENT_HELLO: Server sent "
- << "unsupported ser_fmt_ver" << std::endl;
+ << "unsupported ser_fmt_ver"<< std::endl;
return;
}
m_server_ser_ver = serialization_ver;
m_proto_ver = proto_ver;
- // TODO verify that username_legacy matches sent username, only
+ //TODO verify that username_legacy matches sent username, only
// differs in casing (make both uppercase and compare)
// This is only neccessary though when we actually want to add casing support
if (m_chosen_auth_mech != AUTH_MECHANISM_NONE) {
// we recieved a TOCLIENT_HELLO while auth was already going on
errorstream << "Client: TOCLIENT_HELLO while auth was already going on"
- << "(chosen_mech=" << m_chosen_auth_mech << ")." << std::endl;
+ << "(chosen_mech=" << m_chosen_auth_mech << ")." << std::endl;
if (m_chosen_auth_mech == AUTH_MECHANISM_SRP ||
m_chosen_auth_mech == AUTH_MECHANISM_LEGACY_PASSWORD) {
- srp_user_delete((SRPUser *)m_auth_data);
+ srp_user_delete((SRPUser *) m_auth_data);
m_auth_data = 0;
}
}
@@ -115,15 +116,16 @@ void Client::handleCommand_Hello(NetworkPacket *pkt)
m_access_denied_reason = "Unknown";
m_con->Disconnect();
}
+
}
-void Client::handleCommand_AuthAccept(NetworkPacket *pkt)
+void Client::handleCommand_AuthAccept(NetworkPacket* pkt)
{
deleteAuthData();
v3f playerpos;
- *pkt >> playerpos >> m_map_seed >> m_recommended_send_interval >>
- m_sudo_auth_methods;
+ *pkt >> playerpos >> m_map_seed >> m_recommended_send_interval
+ >> m_sudo_auth_methods;
playerpos -= v3f(0, BS / 2, 0);
@@ -134,7 +136,7 @@ void Client::handleCommand_AuthAccept(NetworkPacket *pkt)
infostream << "Client: received map seed: " << m_map_seed << std::endl;
infostream << "Client: received recommended send interval "
- << m_recommended_send_interval << std::endl;
+ << m_recommended_send_interval<<std::endl;
// Reply to server
/*~ DO NOT TRANSLATE THIS LITERALLY!
@@ -150,7 +152,7 @@ void Client::handleCommand_AuthAccept(NetworkPacket *pkt)
m_state = LC_Init;
}
-void Client::handleCommand_AcceptSudoMode(NetworkPacket *pkt)
+void Client::handleCommand_AcceptSudoMode(NetworkPacket* pkt)
{
deleteAuthData();
@@ -164,7 +166,7 @@ void Client::handleCommand_AcceptSudoMode(NetworkPacket *pkt)
// reset again
m_chosen_auth_mech = AUTH_MECHANISM_NONE;
}
-void Client::handleCommand_DenySudoMode(NetworkPacket *pkt)
+void Client::handleCommand_DenySudoMode(NetworkPacket* pkt)
{
ChatMessage *chatMessage = new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
L"Password change denied. Password NOT changed.");
@@ -173,7 +175,7 @@ void Client::handleCommand_DenySudoMode(NetworkPacket *pkt)
deleteAuthData();
}
-void Client::handleCommand_AccessDenied(NetworkPacket *pkt)
+void Client::handleCommand_AccessDenied(NetworkPacket* pkt)
{
// The server didn't like our password. Note, this needs
// to be processed even if the serialisation format has
@@ -225,7 +227,7 @@ void Client::handleCommand_AccessDenied(NetworkPacket *pkt)
}
}
-void Client::handleCommand_RemoveNode(NetworkPacket *pkt)
+void Client::handleCommand_RemoveNode(NetworkPacket* pkt)
{
if (pkt->getSize() < 6)
return;
@@ -235,7 +237,7 @@ void Client::handleCommand_RemoveNode(NetworkPacket *pkt)
removeNode(p);
}
-void Client::handleCommand_AddNode(NetworkPacket *pkt)
+void Client::handleCommand_AddNode(NetworkPacket* pkt)
{
if (pkt->getSize() < 6 + MapNode::serializedLength(m_server_ser_ver))
return;
@@ -272,7 +274,8 @@ void Client::handleCommand_NodemetaChanged(NetworkPacket *pkt)
i != meta_updates_list.end(); ++i) {
v3s16 pos = i->first;
- if (map.isValidPosition(pos) && map.setNodeMetadata(pos, i->second))
+ if (map.isValidPosition(pos) &&
+ map.setNodeMetadata(pos, i->second))
continue; // Prevent from deleting metadata
// Meta couldn't be set, unused metadata
@@ -280,7 +283,7 @@ void Client::handleCommand_NodemetaChanged(NetworkPacket *pkt)
}
}
-void Client::handleCommand_BlockData(NetworkPacket *pkt)
+void Client::handleCommand_BlockData(NetworkPacket* pkt)
{
// Ignore too small packet
if (pkt->getSize() < 6)
@@ -307,7 +310,8 @@ void Client::handleCommand_BlockData(NetworkPacket *pkt)
*/
block->deSerialize(istr, m_server_ser_ver, false);
block->deSerializeNetworkSpecific(istr);
- } else {
+ }
+ else {
/*
Create a new block
*/
@@ -327,7 +331,7 @@ void Client::handleCommand_BlockData(NetworkPacket *pkt)
addUpdateMeshTaskWithEdge(p, true);
}
-void Client::handleCommand_Inventory(NetworkPacket *pkt)
+void Client::handleCommand_Inventory(NetworkPacket* pkt)
{
if (pkt->getSize() < 1)
return;
@@ -347,7 +351,7 @@ void Client::handleCommand_Inventory(NetworkPacket *pkt)
m_inventory_from_server_age = 0.0;
}
-void Client::handleCommand_TimeOfDay(NetworkPacket *pkt)
+void Client::handleCommand_TimeOfDay(NetworkPacket* pkt)
{
if (pkt->getSize() < 2)
return;
@@ -356,12 +360,13 @@ void Client::handleCommand_TimeOfDay(NetworkPacket *pkt)
*pkt >> time_of_day;
- time_of_day = time_of_day % 24000;
+ time_of_day = time_of_day % 24000;
float time_speed = 0;
if (pkt->getSize() >= 2 + 4) {
*pkt >> time_speed;
- } else {
+ }
+ else {
// Old message; try to approximate speed of time by ourselves
float time_of_day_f = (float)time_of_day / 24000.0f;
float tod_diff_f = 0;
@@ -371,15 +376,15 @@ void Client::handleCommand_TimeOfDay(NetworkPacket *pkt)
else
tod_diff_f = time_of_day_f - m_last_time_of_day_f;
- m_last_time_of_day_f = time_of_day_f;
- float time_diff = m_time_of_day_update_timer;
+ m_last_time_of_day_f = time_of_day_f;
+ float time_diff = m_time_of_day_update_timer;
m_time_of_day_update_timer = 0;
if (m_time_of_day_set) {
time_speed = (3600.0f * 24.0f) * tod_diff_f / time_diff;
infostream << "Client: Measured time_of_day speed (old format): "
- << time_speed << " tod_diff_f=" << tod_diff_f
- << " time_diff=" << time_diff << std::endl;
+ << time_speed << " tod_diff_f=" << tod_diff_f
+ << " time_diff=" << time_diff << std::endl;
}
}
@@ -388,8 +393,8 @@ void Client::handleCommand_TimeOfDay(NetworkPacket *pkt)
m_env.setTimeOfDaySpeed(time_speed);
m_time_of_day_set = true;
- // u32 dr = m_env.getDayNightRatio();
- // infostream << "Client: time_of_day=" << time_of_day
+ //u32 dr = m_env.getDayNightRatio();
+ //infostream << "Client: time_of_day=" << time_of_day
// << " time_speed=" << time_speed
// << " dr=" << dr << std::endl;
}
@@ -418,11 +423,11 @@ void Client::handleCommand_ChatMessage(NetworkPacket *pkt)
*pkt >> chatMessage->sender >> chatMessage->message >> timestamp;
chatMessage->timestamp = static_cast<std::time_t>(timestamp);
- chatMessage->type = (ChatMessageType)message_type;
+ chatMessage->type = (ChatMessageType) message_type;
// @TODO send this to CSM using ChatMessage object
if (modsLoaded() && m_script->on_receiving_message(
- wide_to_utf8(chatMessage->message))) {
+ wide_to_utf8(chatMessage->message))) {
// Message was consumed by CSM and should not be handled by client
delete chatMessage;
} else {
@@ -430,7 +435,7 @@ void Client::handleCommand_ChatMessage(NetworkPacket *pkt)
}
}
-void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket *pkt)
+void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt)
{
/*
u16 count of removed objects
@@ -445,10 +450,10 @@ void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket *pkt)
string initialization data
}
*/
-
+
LocalPlayer *player = m_env.getLocalPlayer();
- bool try_reattach = player && player->isWaitingForReattach();
-
+ bool try_reattach = player && player->isWaitingForReattach();
+
try {
u8 type;
u16 removed_count, added_count, id;
@@ -472,7 +477,7 @@ void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket *pkt)
}
} catch (PacketError &e) {
infostream << "handleCommand_ActiveObjectRemoveAdd: " << e.what()
- << ". The packet is unreliable, ignoring" << std::endl;
+ << ". The packet is unreliable, ignoring" << std::endl;
}
// m_activeobjects_received is false before the first
@@ -480,7 +485,7 @@ void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket *pkt)
m_activeobjects_received = true;
}
-void Client::handleCommand_ActiveObjectMessages(NetworkPacket *pkt)
+void Client::handleCommand_ActiveObjectMessages(NetworkPacket* pkt)
{
/*
for all objects
@@ -506,32 +511,32 @@ void Client::handleCommand_ActiveObjectMessages(NetworkPacket *pkt)
}
} catch (SerializationError &e) {
errorstream << "Client::handleCommand_ActiveObjectMessages: "
- << "caught SerializationError: " << e.what() << std::endl;
+ << "caught SerializationError: " << e.what() << std::endl;
}
}
-void Client::handleCommand_Movement(NetworkPacket *pkt)
+void Client::handleCommand_Movement(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
float mad, maa, maf, msw, mscr, msf, mscl, msj, lf, lfs, ls, g;
- *pkt >> mad >> maa >> maf >> msw >> mscr >> msf >> mscl >> msj >> lf >> lfs >>
- ls >> g;
-
- player->movement_acceleration_default = mad * BS;
- player->movement_acceleration_air = maa * BS;
- player->movement_acceleration_fast = maf * BS;
- player->movement_speed_walk = msw * BS;
- player->movement_speed_crouch = mscr * BS;
- player->movement_speed_fast = msf * BS;
- player->movement_speed_climb = mscl * BS;
- player->movement_speed_jump = msj * BS;
- player->movement_liquid_fluidity = lf * BS;
+ *pkt >> mad >> maa >> maf >> msw >> mscr >> msf >> mscl >> msj
+ >> lf >> lfs >> ls >> g;
+
+ player->movement_acceleration_default = mad * BS;
+ player->movement_acceleration_air = maa * BS;
+ player->movement_acceleration_fast = maf * BS;
+ player->movement_speed_walk = msw * BS;
+ player->movement_speed_crouch = mscr * BS;
+ player->movement_speed_fast = msf * BS;
+ player->movement_speed_climb = mscl * BS;
+ player->movement_speed_jump = msj * BS;
+ player->movement_liquid_fluidity = lf * BS;
player->movement_liquid_fluidity_smooth = lfs * BS;
- player->movement_liquid_sink = ls * BS;
- player->movement_gravity = g * BS;
+ player->movement_liquid_sink = ls * BS;
+ player->movement_gravity = g * BS;
}
void Client::handleCommand_Fov(NetworkPacket *pkt)
@@ -546,12 +551,11 @@ void Client::handleCommand_Fov(NetworkPacket *pkt)
// try-catch to preserve backwards compat
try {
*pkt >> transition_time;
- } catch (PacketError &e) {
- };
+ } catch (PacketError &e) {};
LocalPlayer *player = m_env.getLocalPlayer();
assert(player);
- player->setFov({fov, is_multiplier, transition_time});
+ player->setFov({ fov, is_multiplier, transition_time });
m_camera->notifyFovChange();
}
@@ -579,7 +583,7 @@ void Client::handleCommand_HP(NetworkPacket *pkt)
}
}
-void Client::handleCommand_Breath(NetworkPacket *pkt)
+void Client::handleCommand_Breath(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
@@ -591,15 +595,14 @@ void Client::handleCommand_Breath(NetworkPacket *pkt)
player->setBreath(breath);
}
-void Client::handleCommand_MovePlayer(NetworkPacket *pkt)
-{
+void Client::handleCommand_MovePlayer(NetworkPacket* pkt)
+{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
- if ((player->getCAO() && player->getCAO()->getParentId()) ||
- player->isWaitingForReattach())
+ if ((player->getCAO() && player->getCAO()->getParentId()) || player->isWaitingForReattach())
return;
-
+
v3f pos;
f32 pitch, yaw;
@@ -608,8 +611,10 @@ void Client::handleCommand_MovePlayer(NetworkPacket *pkt)
player->setLegitPosition(pos);
infostream << "Client got TOCLIENT_MOVE_PLAYER"
- << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")"
- << " pitch=" << pitch << " yaw=" << yaw << std::endl;
+ << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")"
+ << " pitch=" << pitch
+ << " yaw=" << yaw
+ << std::endl;
/*
Add to ClientEvent queue.
@@ -617,10 +622,10 @@ void Client::handleCommand_MovePlayer(NetworkPacket *pkt)
it would just force the pitch and yaw values to whatever
the camera points to.
*/
-
+
if (g_settings->getBool("no_force_rotate"))
return;
-
+
ClientEvent *event = new ClientEvent();
event->type = CE_PLAYER_FORCE_MOVE;
event->player_force_move.pitch = pitch;
@@ -628,7 +633,7 @@ void Client::handleCommand_MovePlayer(NetworkPacket *pkt)
m_client_event_queue.push(event);
}
-void Client::handleCommand_DeathScreen(NetworkPacket *pkt)
+void Client::handleCommand_DeathScreen(NetworkPacket* pkt)
{
bool set_camera_point_target;
v3f camera_point_target;
@@ -637,32 +642,32 @@ void Client::handleCommand_DeathScreen(NetworkPacket *pkt)
*pkt >> camera_point_target;
ClientEvent *event = new ClientEvent();
- event->type = CE_DEATHSCREEN;
+ event->type = CE_DEATHSCREEN;
event->deathscreen.set_camera_point_target = set_camera_point_target;
- event->deathscreen.camera_point_target_x = camera_point_target.X;
- event->deathscreen.camera_point_target_y = camera_point_target.Y;
- event->deathscreen.camera_point_target_z = camera_point_target.Z;
+ event->deathscreen.camera_point_target_x = camera_point_target.X;
+ event->deathscreen.camera_point_target_y = camera_point_target.Y;
+ event->deathscreen.camera_point_target_z = camera_point_target.Z;
m_client_event_queue.push(event);
}
-void Client::handleCommand_AnnounceMedia(NetworkPacket *pkt)
+void Client::handleCommand_AnnounceMedia(NetworkPacket* pkt)
{
u16 num_files;
*pkt >> num_files;
infostream << "Client: Received media announcement: packet size: "
- << pkt->getSize() << std::endl;
-
- if (m_media_downloader == NULL || m_media_downloader->isStarted()) {
- const char *problem =
- m_media_downloader
- ? "we already saw another announcement"
- : "all media has been received already";
- errorstream << "Client: Received media announcement but " << problem
- << "! "
- << " files=" << num_files << " size=" << pkt->getSize()
- << std::endl;
+ << pkt->getSize() << std::endl;
+
+ if (m_media_downloader == NULL ||
+ m_media_downloader->isStarted()) {
+ const char *problem = m_media_downloader ?
+ "we already saw another announcement" :
+ "all media has been received already";
+ errorstream << "Client: Received media announcement but "
+ << problem << "! "
+ << " files=" << num_files
+ << " size=" << pkt->getSize() << std::endl;
return;
}
@@ -685,19 +690,20 @@ void Client::handleCommand_AnnounceMedia(NetworkPacket *pkt)
*pkt >> str;
Strfnd sf(str);
- while (!sf.at_end()) {
+ while(!sf.at_end()) {
std::string baseurl = trim(sf.next(","));
if (!baseurl.empty())
m_media_downloader->addRemoteServer(baseurl);
}
- } catch (SerializationError &e) {
+ }
+ catch(SerializationError& e) {
// not supported by server or turned off
}
m_media_downloader->step(this);
}
-void Client::handleCommand_Media(NetworkPacket *pkt)
+void Client::handleCommand_Media(NetworkPacket* pkt)
{
/*
u16 command
@@ -717,21 +723,22 @@ void Client::handleCommand_Media(NetworkPacket *pkt)
*pkt >> num_bunches >> bunch_i >> num_files;
- infostream << "Client: Received files: bunch " << bunch_i << "/" << num_bunches
- << " files=" << num_files << " size=" << pkt->getSize() << std::endl;
+ infostream << "Client: Received files: bunch " << bunch_i << "/"
+ << num_bunches << " files=" << num_files
+ << " size=" << pkt->getSize() << std::endl;
if (num_files == 0)
return;
if (!m_media_downloader || !m_media_downloader->isStarted()) {
- const char *problem =
- m_media_downloader
- ? "media has not been requested"
- : "all media has been received already";
- errorstream << "Client: Received media but " << problem << "! "
- << " bunch " << bunch_i << "/" << num_bunches
- << " files=" << num_files << " size=" << pkt->getSize()
- << std::endl;
+ const char *problem = m_media_downloader ?
+ "media has not been requested" :
+ "all media has been received already";
+ errorstream << "Client: Received media but "
+ << problem << "! "
+ << " bunch " << bunch_i << "/" << num_bunches
+ << " files=" << num_files
+ << " size=" << pkt->getSize() << std::endl;
return;
}
@@ -739,21 +746,22 @@ void Client::handleCommand_Media(NetworkPacket *pkt)
// updating content definitions
sanity_check(!m_mesh_update_thread.isRunning());
- for (u32 i = 0; i < num_files; i++) {
+ for (u32 i=0; i < num_files; i++) {
std::string name;
*pkt >> name;
std::string data = pkt->readLongString();
- m_media_downloader->conventionalTransferDone(name, data, this);
+ m_media_downloader->conventionalTransferDone(
+ name, data, this);
}
}
-void Client::handleCommand_NodeDef(NetworkPacket *pkt)
+void Client::handleCommand_NodeDef(NetworkPacket* pkt)
{
- infostream << "Client: Received node definitions: packet size: " << pkt->getSize()
- << std::endl;
+ infostream << "Client: Received node definitions: packet size: "
+ << pkt->getSize() << std::endl;
// Mesh update thread must be stopped while
// updating content definitions
@@ -770,10 +778,10 @@ void Client::handleCommand_NodeDef(NetworkPacket *pkt)
m_nodedef_received = true;
}
-void Client::handleCommand_ItemDef(NetworkPacket *pkt)
+void Client::handleCommand_ItemDef(NetworkPacket* pkt)
{
- infostream << "Client: Received item definitions: packet size: " << pkt->getSize()
- << std::endl;
+ infostream << "Client: Received item definitions: packet size: "
+ << pkt->getSize() << std::endl;
// Mesh update thread must be stopped while
// updating content definitions
@@ -790,7 +798,7 @@ void Client::handleCommand_ItemDef(NetworkPacket *pkt)
m_itemdef_received = true;
}
-void Client::handleCommand_PlaySound(NetworkPacket *pkt)
+void Client::handleCommand_PlaySound(NetworkPacket* pkt)
{
/*
[0] u32 server_id
@@ -824,27 +832,27 @@ void Client::handleCommand_PlaySound(NetworkPacket *pkt)
*pkt >> fade;
*pkt >> pitch;
*pkt >> ephemeral;
- } catch (PacketError &e) {
- };
+ } catch (PacketError &e) {};
// Start playing
int client_id = -1;
- switch (type) {
- case 0: // local
- client_id = m_sound->playSound(name, loop, gain, fade, pitch);
- break;
- case 1: // positional
- client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch);
- break;
- case 2: { // object
- ClientActiveObject *cao = m_env.getActiveObject(object_id);
- if (cao)
- pos = cao->getPosition();
- client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch);
- break;
- }
- default:
- break;
+ switch(type) {
+ case 0: // local
+ client_id = m_sound->playSound(name, loop, gain, fade, pitch);
+ break;
+ case 1: // positional
+ client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch);
+ break;
+ case 2:
+ { // object
+ ClientActiveObject *cao = m_env.getActiveObject(object_id);
+ if (cao)
+ pos = cao->getPosition();
+ client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch);
+ break;
+ }
+ default:
+ break;
}
if (client_id != -1) {
@@ -858,14 +866,13 @@ void Client::handleCommand_PlaySound(NetworkPacket *pkt)
}
}
-void Client::handleCommand_StopSound(NetworkPacket *pkt)
+void Client::handleCommand_StopSound(NetworkPacket* pkt)
{
s32 server_id;
*pkt >> server_id;
- std::unordered_map<s32, int>::iterator i =
- m_sounds_server_to_client.find(server_id);
+ std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.find(server_id);
if (i != m_sounds_server_to_client.end()) {
int client_id = i->second;
m_sound->stopSound(client_id);
@@ -887,7 +894,7 @@ void Client::handleCommand_FadeSound(NetworkPacket *pkt)
m_sound->fadeSound(i->second, step, gain);
}
-void Client::handleCommand_Privileges(NetworkPacket *pkt)
+void Client::handleCommand_Privileges(NetworkPacket* pkt)
{
m_privileges.clear();
infostream << "Client: Privileges updated: ";
@@ -906,7 +913,7 @@ void Client::handleCommand_Privileges(NetworkPacket *pkt)
infostream << std::endl;
}
-void Client::handleCommand_InventoryFormSpec(NetworkPacket *pkt)
+void Client::handleCommand_InventoryFormSpec(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
@@ -915,14 +922,14 @@ void Client::handleCommand_InventoryFormSpec(NetworkPacket *pkt)
player->inventory_formspec = pkt->readLongString();
}
-void Client::handleCommand_DetachedInventory(NetworkPacket *pkt)
+void Client::handleCommand_DetachedInventory(NetworkPacket* pkt)
{
std::string name;
bool keep_inv = true;
*pkt >> name >> keep_inv;
infostream << "Client: Detached inventory update: \"" << name
- << "\", mode=" << (keep_inv ? "update" : "remove") << std::endl;
+ << "\", mode=" << (keep_inv ? "update" : "remove") << std::endl;
const auto &inv_it = m_detached_inventories.find(name);
if (!keep_inv) {
@@ -948,7 +955,7 @@ void Client::handleCommand_DetachedInventory(NetworkPacket *pkt)
inv->deSerialize(is);
}
-void Client::handleCommand_ShowFormSpec(NetworkPacket *pkt)
+void Client::handleCommand_ShowFormSpec(NetworkPacket* pkt)
{
std::string formspec = pkt->readLongString();
std::string formname;
@@ -964,7 +971,7 @@ void Client::handleCommand_ShowFormSpec(NetworkPacket *pkt)
m_client_event_queue.push(event);
}
-void Client::handleCommand_SpawnParticle(NetworkPacket *pkt)
+void Client::handleCommand_SpawnParticle(NetworkPacket* pkt)
{
std::string datastring(pkt->getString(0), pkt->getSize());
std::istringstream is(datastring, std::ios_base::binary);
@@ -973,17 +980,17 @@ void Client::handleCommand_SpawnParticle(NetworkPacket *pkt)
p.deSerialize(is, m_proto_ver);
ClientEvent *event = new ClientEvent();
- event->type = CE_SPAWN_PARTICLE;
+ event->type = CE_SPAWN_PARTICLE;
event->spawn_particle = new ParticleParameters(p);
-
+
if (g_settings->getBool("log_particles")) {
std::cout << p.pos.X << " " << p.pos.Y << " " << p.pos.Z << std::endl;
}
-
+
m_client_event_queue.push(event);
}
-void Client::handleCommand_AddParticleSpawner(NetworkPacket *pkt)
+void Client::handleCommand_AddParticleSpawner(NetworkPacket* pkt)
{
std::string datastring(pkt->getString(0), pkt->getSize());
std::istringstream is(datastring, std::ios_base::binary);
@@ -992,20 +999,20 @@ void Client::handleCommand_AddParticleSpawner(NetworkPacket *pkt)
u32 server_id;
u16 attached_id = 0;
- p.amount = readU16(is);
- p.time = readF32(is);
- p.minpos = readV3F32(is);
- p.maxpos = readV3F32(is);
- p.minvel = readV3F32(is);
- p.maxvel = readV3F32(is);
- p.minacc = readV3F32(is);
- p.maxacc = readV3F32(is);
- p.minexptime = readF32(is);
- p.maxexptime = readF32(is);
- p.minsize = readF32(is);
- p.maxsize = readF32(is);
+ p.amount = readU16(is);
+ p.time = readF32(is);
+ p.minpos = readV3F32(is);
+ p.maxpos = readV3F32(is);
+ p.minvel = readV3F32(is);
+ p.maxvel = readV3F32(is);
+ p.minacc = readV3F32(is);
+ p.maxacc = readV3F32(is);
+ p.minexptime = readF32(is);
+ p.maxexptime = readF32(is);
+ p.minsize = readF32(is);
+ p.maxsize = readF32(is);
p.collisiondetection = readU8(is);
- p.texture = deSerializeLongString(is);
+ p.texture = deSerializeLongString(is);
server_id = readU32(is);
@@ -1025,19 +1032,20 @@ void Client::handleCommand_AddParticleSpawner(NetworkPacket *pkt)
break;
p.node.param0 = tmp_param0;
p.node.param2 = readU8(is);
- p.node_tile = readU8(is);
+ p.node_tile = readU8(is);
} while (0);
auto event = new ClientEvent();
- event->type = CE_ADD_PARTICLESPAWNER;
- event->add_particlespawner.p = new ParticleSpawnerParameters(p);
+ event->type = CE_ADD_PARTICLESPAWNER;
+ event->add_particlespawner.p = new ParticleSpawnerParameters(p);
event->add_particlespawner.attached_id = attached_id;
- event->add_particlespawner.id = server_id;
+ event->add_particlespawner.id = server_id;
m_client_event_queue.push(event);
}
-void Client::handleCommand_DeleteParticleSpawner(NetworkPacket *pkt)
+
+void Client::handleCommand_DeleteParticleSpawner(NetworkPacket* pkt)
{
u32 server_id;
*pkt >> server_id;
@@ -1049,7 +1057,7 @@ void Client::handleCommand_DeleteParticleSpawner(NetworkPacket *pkt)
m_client_event_queue.push(event);
}
-void Client::handleCommand_HudAdd(NetworkPacket *pkt)
+void Client::handleCommand_HudAdd(NetworkPacket* pkt)
{
std::string datastring(pkt->getString(0), pkt->getSize());
std::istringstream is(datastring, std::ios_base::binary);
@@ -1070,37 +1078,36 @@ void Client::handleCommand_HudAdd(NetworkPacket *pkt)
s16 z_index = 0;
std::string text2;
- *pkt >> server_id >> type >> pos >> name >> scale >> text >> number >> item >>
- dir >> align >> offset;
+ *pkt >> server_id >> type >> pos >> name >> scale >> text >> number >> item
+ >> dir >> align >> offset;
try {
*pkt >> world_pos;
*pkt >> size;
*pkt >> z_index;
*pkt >> text2;
- } catch (PacketError &e) {
- };
+ } catch(PacketError &e) {};
ClientEvent *event = new ClientEvent();
- event->type = CE_HUDADD;
+ event->type = CE_HUDADD;
event->hudadd.server_id = server_id;
- event->hudadd.type = type;
- event->hudadd.pos = new v2f(pos);
- event->hudadd.name = new std::string(name);
- event->hudadd.scale = new v2f(scale);
- event->hudadd.text = new std::string(text);
- event->hudadd.number = number;
- event->hudadd.item = item;
- event->hudadd.dir = dir;
- event->hudadd.align = new v2f(align);
- event->hudadd.offset = new v2f(offset);
+ event->hudadd.type = type;
+ event->hudadd.pos = new v2f(pos);
+ event->hudadd.name = new std::string(name);
+ event->hudadd.scale = new v2f(scale);
+ event->hudadd.text = new std::string(text);
+ event->hudadd.number = number;
+ event->hudadd.item = item;
+ event->hudadd.dir = dir;
+ event->hudadd.align = new v2f(align);
+ event->hudadd.offset = new v2f(offset);
event->hudadd.world_pos = new v3f(world_pos);
- event->hudadd.size = new v2s32(size);
- event->hudadd.z_index = z_index;
- event->hudadd.text2 = new std::string(text2);
+ event->hudadd.size = new v2s32(size);
+ event->hudadd.z_index = z_index;
+ event->hudadd.text2 = new std::string(text2);
m_client_event_queue.push(event);
}
-void Client::handleCommand_HudRemove(NetworkPacket *pkt)
+void Client::handleCommand_HudRemove(NetworkPacket* pkt)
{
u32 server_id;
@@ -1112,13 +1119,13 @@ void Client::handleCommand_HudRemove(NetworkPacket *pkt)
m_hud_server_to_client.erase(i);
ClientEvent *event = new ClientEvent();
- event->type = CE_HUDRM;
+ event->type = CE_HUDRM;
event->hudrm.id = client_id;
m_client_event_queue.push(event);
}
}
-void Client::handleCommand_HudChange(NetworkPacket *pkt)
+void Client::handleCommand_HudChange(NetworkPacket* pkt)
{
std::string sdata;
v2f v2fdata;
@@ -1130,35 +1137,34 @@ void Client::handleCommand_HudChange(NetworkPacket *pkt)
*pkt >> server_id >> stat;
- if (stat == HUD_STAT_POS || stat == HUD_STAT_SCALE || stat == HUD_STAT_ALIGN ||
- stat == HUD_STAT_OFFSET)
+ if (stat == HUD_STAT_POS || stat == HUD_STAT_SCALE ||
+ stat == HUD_STAT_ALIGN || stat == HUD_STAT_OFFSET)
*pkt >> v2fdata;
else if (stat == HUD_STAT_NAME || stat == HUD_STAT_TEXT || stat == HUD_STAT_TEXT2)
*pkt >> sdata;
else if (stat == HUD_STAT_WORLD_POS)
*pkt >> v3fdata;
- else if (stat == HUD_STAT_SIZE)
+ else if (stat == HUD_STAT_SIZE )
*pkt >> v2s32data;
else
*pkt >> intdata;
- std::unordered_map<u32, u32>::const_iterator i =
- m_hud_server_to_client.find(server_id);
+ std::unordered_map<u32, u32>::const_iterator i = m_hud_server_to_client.find(server_id);
if (i != m_hud_server_to_client.end()) {
ClientEvent *event = new ClientEvent();
- event->type = CE_HUDCHANGE;
- event->hudchange.id = i->second;
- event->hudchange.stat = (HudElementStat)stat;
+ event->type = CE_HUDCHANGE;
+ event->hudchange.id = i->second;
+ event->hudchange.stat = (HudElementStat)stat;
event->hudchange.v2fdata = new v2f(v2fdata);
event->hudchange.v3fdata = new v3f(v3fdata);
- event->hudchange.sdata = new std::string(sdata);
- event->hudchange.data = intdata;
+ event->hudchange.sdata = new std::string(sdata);
+ event->hudchange.data = intdata;
event->hudchange.v2s32data = new v2s32(v2s32data);
m_client_event_queue.push(event);
}
}
-void Client::handleCommand_HudSetFlags(NetworkPacket *pkt)
+void Client::handleCommand_HudSetFlags(NetworkPacket* pkt)
{
u32 flags, mask;
@@ -1168,22 +1174,20 @@ void Client::handleCommand_HudSetFlags(NetworkPacket *pkt)
assert(player != NULL);
bool was_minimap_visible = player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE;
- bool was_minimap_radar_visible =
- player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE;
+ bool was_minimap_radar_visible = player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE;
player->hud_flags &= ~mask;
player->hud_flags |= flags;
if (g_settings->getBool("hud_flags_bypass"))
- player->hud_flags =
- HUD_FLAG_HOTBAR_VISIBLE | HUD_FLAG_HEALTHBAR_VISIBLE |
- HUD_FLAG_CROSSHAIR_VISIBLE | HUD_FLAG_WIELDITEM_VISIBLE |
- HUD_FLAG_BREATHBAR_VISIBLE | HUD_FLAG_MINIMAP_VISIBLE |
- HUD_FLAG_MINIMAP_RADAR_VISIBLE;
+ player->hud_flags = HUD_FLAG_HOTBAR_VISIBLE | HUD_FLAG_HEALTHBAR_VISIBLE |
+ HUD_FLAG_CROSSHAIR_VISIBLE | HUD_FLAG_WIELDITEM_VISIBLE |
+ HUD_FLAG_BREATHBAR_VISIBLE | HUD_FLAG_MINIMAP_VISIBLE |
+ HUD_FLAG_MINIMAP_RADAR_VISIBLE;
+
m_minimap_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE);
- bool m_minimap_radar_disabled_by_server =
- !(player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE);
+ bool m_minimap_radar_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE);
// Hide minimap if it has been disabled by the server
if (m_minimap && m_minimap_disabled_by_server && was_minimap_visible)
@@ -1194,12 +1198,13 @@ void Client::handleCommand_HudSetFlags(NetworkPacket *pkt)
// Switch to surface mode if radar disabled by server
if (m_minimap && m_minimap_radar_disabled_by_server && was_minimap_radar_visible)
m_minimap->setMinimapMode(MINIMAP_MODE_SURFACEx1);
+
+
}
-void Client::handleCommand_HudSetParam(NetworkPacket *pkt)
+void Client::handleCommand_HudSetParam(NetworkPacket* pkt)
{
- u16 param;
- std::string value;
+ u16 param; std::string value;
*pkt >> param >> value;
@@ -1207,17 +1212,19 @@ void Client::handleCommand_HudSetParam(NetworkPacket *pkt)
assert(player != NULL);
if (param == HUD_PARAM_HOTBAR_ITEMCOUNT && value.size() == 4) {
- s32 hotbar_itemcount = readS32((u8 *)value.c_str());
+ s32 hotbar_itemcount = readS32((u8*) value.c_str());
if (hotbar_itemcount > 0 && hotbar_itemcount <= HUD_HOTBAR_ITEMCOUNT_MAX)
player->hud_hotbar_itemcount = hotbar_itemcount;
- } else if (param == HUD_PARAM_HOTBAR_IMAGE) {
+ }
+ else if (param == HUD_PARAM_HOTBAR_IMAGE) {
player->hotbar_image = value;
- } else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) {
+ }
+ else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) {
player->hotbar_selected_image = value;
}
}
-void Client::handleCommand_HudSetSky(NetworkPacket *pkt)
+void Client::handleCommand_HudSetSky(NetworkPacket* pkt)
{
if (m_proto_ver < 39) {
// Handle Protocol 38 and below servers with old set_sky,
@@ -1236,8 +1243,7 @@ void Client::handleCommand_HudSetSky(NetworkPacket *pkt)
skybox.clouds = true;
try {
skybox.clouds = readU8(is);
- } catch (...) {
- }
+ } catch (...) {}
// Use default skybox settings:
SkyboxDefaults sky_defaults;
@@ -1251,7 +1257,8 @@ void Client::handleCommand_HudSetSky(NetworkPacket *pkt)
skybox.fog_tint_type = "default";
skybox.fog_moon_tint = video::SColor(255, 255, 255, 255);
skybox.fog_sun_tint = video::SColor(255, 255, 255, 255);
- } else {
+ }
+ else {
sun.visible = false;
sun.sunrise_visible = false;
moon.visible = false;
@@ -1284,8 +1291,7 @@ void Client::handleCommand_HudSetSky(NetworkPacket *pkt)
std::string texture;
*pkt >> skybox.bgcolor >> skybox.type >> skybox.clouds >>
- skybox.fog_sun_tint >> skybox.fog_moon_tint >>
- skybox.fog_tint_type;
+ skybox.fog_sun_tint >> skybox.fog_moon_tint >> skybox.fog_tint_type;
if (skybox.type == "skybox") {
*pkt >> texture_count;
@@ -1293,14 +1299,12 @@ void Client::handleCommand_HudSetSky(NetworkPacket *pkt)
*pkt >> texture;
skybox.textures.emplace_back(texture);
}
- } else if (skybox.type == "regular") {
- *pkt >> skybox.sky_color.day_sky >>
- skybox.sky_color.day_horizon >>
- skybox.sky_color.dawn_sky >>
- skybox.sky_color.dawn_horizon >>
- skybox.sky_color.night_sky >>
- skybox.sky_color.night_horizon >>
- skybox.sky_color.indoors;
+ }
+ else if (skybox.type == "regular") {
+ *pkt >> skybox.sky_color.day_sky >> skybox.sky_color.day_horizon
+ >> skybox.sky_color.dawn_sky >> skybox.sky_color.dawn_horizon
+ >> skybox.sky_color.night_sky >> skybox.sky_color.night_horizon
+ >> skybox.sky_color.indoors;
}
ClientEvent *event = new ClientEvent();
@@ -1314,12 +1318,12 @@ void Client::handleCommand_HudSetSun(NetworkPacket *pkt)
{
SunParams sun;
- *pkt >> sun.visible >> sun.texture >> sun.tonemap >> sun.sunrise >>
- sun.sunrise_visible >> sun.scale;
+ *pkt >> sun.visible >> sun.texture>> sun.tonemap
+ >> sun.sunrise >> sun.sunrise_visible >> sun.scale;
ClientEvent *event = new ClientEvent();
- event->type = CE_SET_SUN;
- event->sun_params = new SunParams(sun);
+ event->type = CE_SET_SUN;
+ event->sun_params = new SunParams(sun);
m_client_event_queue.push(event);
}
@@ -1327,10 +1331,11 @@ void Client::handleCommand_HudSetMoon(NetworkPacket *pkt)
{
MoonParams moon;
- *pkt >> moon.visible >> moon.texture >> moon.tonemap >> moon.scale;
+ *pkt >> moon.visible >> moon.texture
+ >> moon.tonemap >> moon.scale;
ClientEvent *event = new ClientEvent();
- event->type = CE_SET_MOON;
+ event->type = CE_SET_MOON;
event->moon_params = new MoonParams(moon);
m_client_event_queue.push(event);
}
@@ -1339,16 +1344,17 @@ void Client::handleCommand_HudSetStars(NetworkPacket *pkt)
{
StarParams stars;
- *pkt >> stars.visible >> stars.count >> stars.starcolor >> stars.scale;
+ *pkt >> stars.visible >> stars.count
+ >> stars.starcolor >> stars.scale;
ClientEvent *event = new ClientEvent();
- event->type = CE_SET_STARS;
+ event->type = CE_SET_STARS;
event->star_params = new StarParams(stars);
m_client_event_queue.push(event);
}
-void Client::handleCommand_CloudParams(NetworkPacket *pkt)
+void Client::handleCommand_CloudParams(NetworkPacket* pkt)
{
f32 density;
video::SColor color_bright;
@@ -1357,25 +1363,26 @@ void Client::handleCommand_CloudParams(NetworkPacket *pkt)
f32 thickness;
v2f speed;
- *pkt >> density >> color_bright >> color_ambient >> height >> thickness >> speed;
+ *pkt >> density >> color_bright >> color_ambient
+ >> height >> thickness >> speed;
ClientEvent *event = new ClientEvent();
- event->type = CE_CLOUD_PARAMS;
- event->cloud_params.density = density;
+ event->type = CE_CLOUD_PARAMS;
+ event->cloud_params.density = density;
// use the underlying u32 representation, because we can't
// use struct members with constructors here, and this way
// we avoid using new() and delete() for no good reason
- event->cloud_params.color_bright = color_bright.color;
+ event->cloud_params.color_bright = color_bright.color;
event->cloud_params.color_ambient = color_ambient.color;
- event->cloud_params.height = height;
- event->cloud_params.thickness = thickness;
+ event->cloud_params.height = height;
+ event->cloud_params.thickness = thickness;
// same here: deconstruct to skip constructor
- event->cloud_params.speed_x = speed.X;
- event->cloud_params.speed_y = speed.Y;
+ event->cloud_params.speed_x = speed.X;
+ event->cloud_params.speed_y = speed.Y;
m_client_event_queue.push(event);
}
-void Client::handleCommand_OverrideDayNightRatio(NetworkPacket *pkt)
+void Client::handleCommand_OverrideDayNightRatio(NetworkPacket* pkt)
{
bool do_override;
u16 day_night_ratio_u;
@@ -1385,13 +1392,13 @@ void Client::handleCommand_OverrideDayNightRatio(NetworkPacket *pkt)
float day_night_ratio_f = (float)day_night_ratio_u / 65536;
ClientEvent *event = new ClientEvent();
- event->type = CE_OVERRIDE_DAY_NIGHT_RATIO;
+ event->type = CE_OVERRIDE_DAY_NIGHT_RATIO;
event->override_day_night_ratio.do_override = do_override;
- event->override_day_night_ratio.ratio_f = day_night_ratio_f;
+ event->override_day_night_ratio.ratio_f = day_night_ratio_f;
m_client_event_queue.push(event);
}
-void Client::handleCommand_LocalPlayerAnimations(NetworkPacket *pkt)
+void Client::handleCommand_LocalPlayerAnimations(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
@@ -1403,7 +1410,7 @@ void Client::handleCommand_LocalPlayerAnimations(NetworkPacket *pkt)
*pkt >> player->local_animation_speed;
}
-void Client::handleCommand_EyeOffset(NetworkPacket *pkt)
+void Client::handleCommand_EyeOffset(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
@@ -1411,12 +1418,12 @@ void Client::handleCommand_EyeOffset(NetworkPacket *pkt)
*pkt >> player->eye_offset_first >> player->eye_offset_third;
}
-void Client::handleCommand_UpdatePlayerList(NetworkPacket *pkt)
+void Client::handleCommand_UpdatePlayerList(NetworkPacket* pkt)
{
u8 type;
u16 num_players;
*pkt >> type >> num_players;
- PlayerListModifer notice_type = (PlayerListModifer)type;
+ PlayerListModifer notice_type = (PlayerListModifer) type;
for (u16 i = 0; i < num_players; i++) {
std::string name;
@@ -1433,30 +1440,30 @@ void Client::handleCommand_UpdatePlayerList(NetworkPacket *pkt)
}
}
-void Client::handleCommand_SrpBytesSandB(NetworkPacket *pkt)
+void Client::handleCommand_SrpBytesSandB(NetworkPacket* pkt)
{
if (m_chosen_auth_mech != AUTH_MECHANISM_SRP &&
m_chosen_auth_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
errorstream << "Client: Received SRP S_B login message,"
- << " but wasn't supposed to (chosen_mech="
- << m_chosen_auth_mech << ")." << std::endl;
+ << " but wasn't supposed to (chosen_mech="
+ << m_chosen_auth_mech << ")." << std::endl;
return;
}
char *bytes_M = 0;
size_t len_M = 0;
- SRPUser *usr = (SRPUser *)m_auth_data;
+ SRPUser *usr = (SRPUser *) m_auth_data;
std::string s;
std::string B;
*pkt >> s >> B;
infostream << "Client: Received TOCLIENT_SRP_BYTES_S_B." << std::endl;
- srp_user_process_challenge(usr, (const unsigned char *)s.c_str(), s.size(),
- (const unsigned char *)B.c_str(), B.size(),
- (unsigned char **)&bytes_M, &len_M);
+ srp_user_process_challenge(usr, (const unsigned char *) s.c_str(), s.size(),
+ (const unsigned char *) B.c_str(), B.size(),
+ (unsigned char **) &bytes_M, &len_M);
- if (!bytes_M) {
+ if ( !bytes_M ) {
errorstream << "Client: SRP-6a S_B safety check violation!" << std::endl;
return;
}
@@ -1511,8 +1518,8 @@ void Client::handleCommand_MediaPush(NetworkPacket *pkt)
}
verbosestream << "Server pushes media file \"" << filename << "\" with "
- << filedata.size() << " bytes of data (cached=" << cached << ")"
- << std::endl;
+ << filedata.size() << " bytes of data (cached=" << cached
+ << ")" << std::endl;
if (m_media_pushed_files.count(filename) != 0) {
// Silently ignore for synchronization purposes
@@ -1525,7 +1532,7 @@ void Client::handleCommand_MediaPush(NetworkPacket *pkt)
SHA1 ctx;
ctx.addBytes(filedata.c_str(), filedata.size());
unsigned char *buf = ctx.getDigest();
- computed_hash.assign((char *)buf, 20);
+ computed_hash.assign((char*) buf, 20);
free(buf);
}
if (raw_hash != computed_hash) {
@@ -1552,12 +1559,12 @@ void Client::handleCommand_ModChannelMsg(NetworkPacket *pkt)
*pkt >> channel_name >> sender >> channel_msg;
verbosestream << "Mod channel message received from server " << pkt->getPeerId()
- << " on channel " << channel_name << ". sender: `" << sender
- << "`, message: " << channel_msg << std::endl;
+ << " on channel " << channel_name << ". sender: `" << sender << "`, message: "
+ << channel_msg << std::endl;
if (!m_modchannel_mgr->channelRegistered(channel_name)) {
verbosestream << "Server sent us messages on unregistered channel "
- << channel_name << ", ignoring." << std::endl;
+ << channel_name << ", ignoring." << std::endl;
return;
}
@@ -1577,57 +1584,56 @@ void Client::handleCommand_ModChannelSignal(NetworkPacket *pkt)
bool valid_signal = true;
// @TODO: send Signal to Lua API
switch (signal) {
- case MODCHANNEL_SIGNAL_JOIN_OK:
- m_modchannel_mgr->setChannelState(channel, MODCHANNEL_STATE_READ_WRITE);
- infostream << "Server ack our mod channel join on channel `" << channel
- << "`, joining." << std::endl;
- break;
- case MODCHANNEL_SIGNAL_JOIN_FAILURE:
- // Unable to join, remove channel
- m_modchannel_mgr->leaveChannel(channel, 0);
- infostream << "Server refused our mod channel join on channel `"
- << channel << "`" << std::endl;
- break;
- case MODCHANNEL_SIGNAL_LEAVE_OK:
+ case MODCHANNEL_SIGNAL_JOIN_OK:
+ m_modchannel_mgr->setChannelState(channel, MODCHANNEL_STATE_READ_WRITE);
+ infostream << "Server ack our mod channel join on channel `" << channel
+ << "`, joining." << std::endl;
+ break;
+ case MODCHANNEL_SIGNAL_JOIN_FAILURE:
+ // Unable to join, remove channel
+ m_modchannel_mgr->leaveChannel(channel, 0);
+ infostream << "Server refused our mod channel join on channel `" << channel
+ << "`" << std::endl;
+ break;
+ case MODCHANNEL_SIGNAL_LEAVE_OK:
#ifndef NDEBUG
- infostream << "Server ack our mod channel leave on channel " << channel
- << "`, leaving." << std::endl;
+ infostream << "Server ack our mod channel leave on channel " << channel
+ << "`, leaving." << std::endl;
#endif
- break;
- case MODCHANNEL_SIGNAL_LEAVE_FAILURE:
- infostream << "Server refused our mod channel leave on channel `"
- << channel << "`" << std::endl;
- break;
- case MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED:
+ break;
+ case MODCHANNEL_SIGNAL_LEAVE_FAILURE:
+ infostream << "Server refused our mod channel leave on channel `" << channel
+ << "`" << std::endl;
+ break;
+ case MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED:
#ifndef NDEBUG
- // Generally unused, but ensure we don't do an implementation error
- infostream << "Server tells us we sent a message on channel `" << channel
- << "` but we are not registered. Message was dropped."
- << std::endl;
+ // Generally unused, but ensure we don't do an implementation error
+ infostream << "Server tells us we sent a message on channel `" << channel
+ << "` but we are not registered. Message was dropped." << std::endl;
#endif
- break;
- case MODCHANNEL_SIGNAL_SET_STATE: {
- u8 state;
- *pkt >> state;
-
- if (state == MODCHANNEL_STATE_INIT || state >= MODCHANNEL_STATE_MAX) {
- infostream << "Received wrong channel state " << state
- << ", ignoring." << std::endl;
- return;
- }
+ break;
+ case MODCHANNEL_SIGNAL_SET_STATE: {
+ u8 state;
+ *pkt >> state;
+
+ if (state == MODCHANNEL_STATE_INIT || state >= MODCHANNEL_STATE_MAX) {
+ infostream << "Received wrong channel state " << state
+ << ", ignoring." << std::endl;
+ return;
+ }
- m_modchannel_mgr->setChannelState(channel, (ModChannelState)state);
- infostream << "Server sets mod channel `" << channel
- << "` in read-only mode." << std::endl;
- break;
- }
- default:
+ m_modchannel_mgr->setChannelState(channel, (ModChannelState) state);
+ infostream << "Server sets mod channel `" << channel
+ << "` in read-only mode." << std::endl;
+ break;
+ }
+ default:
#ifndef NDEBUG
- warningstream << "Received unhandled mod channel signal ID " << signal
- << ", ignoring." << std::endl;
+ warningstream << "Received unhandled mod channel signal ID "
+ << signal << ", ignoring." << std::endl;
#endif
- valid_signal = false;
- break;
+ valid_signal = false;
+ break;
}
// If signal is valid, forward it to client side mods
diff --git a/src/network/connection.cpp b/src/network/connection.cpp
index dbcece99d..3692e45a9 100644
--- a/src/network/connection.cpp
+++ b/src/network/connection.cpp
@@ -41,29 +41,29 @@ namespace con
/* defines used for debugging and profiling */
/******************************************************************************/
#ifdef NDEBUG
-#define LOG(a) a
-#define PROFILE(a)
+ #define LOG(a) a
+ #define PROFILE(a)
#else
-#if 0
+ #if 0
/* this mutex is used to achieve log message consistency */
std::mutex log_message_mutex;
-#define LOG(a) \
- { \
- MutexAutoLock loglock(log_message_mutex); \
- a; \
- }
-#else
-// Prevent deadlocks until a solution is found after 5.2.0 (TODO)
-#define LOG(a) a
-#endif
+ #define LOG(a) \
+ { \
+ MutexAutoLock loglock(log_message_mutex); \
+ a; \
+ }
+ #else
+ // Prevent deadlocks until a solution is found after 5.2.0 (TODO)
+ #define LOG(a) a
+ #endif
-#define PROFILE(a) a
+ #define PROFILE(a) a
#endif
#define PING_TIMEOUT 5.0
-BufferedPacket makePacket(Address &address, const SharedBuffer<u8> &data, u32 protocol_id,
- session_t sender_peer_id, u8 channel)
+BufferedPacket makePacket(Address &address, const SharedBuffer<u8> &data,
+ u32 protocol_id, session_t sender_peer_id, u8 channel)
{
u32 packet_size = data.getSize() + BASE_HEADER_SIZE;
BufferedPacket p(packet_size);
@@ -123,7 +123,8 @@ void makeSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max, u16 seqnum
start = end + 1;
chunk_num++;
- } while (end != data.getSize() - 1);
+ }
+ while (end != data.getSize() - 1);
for (SharedBuffer<u8> &chunk : *chunks) {
// Write chunk_count
@@ -166,11 +167,11 @@ SharedBuffer<u8> makeReliablePacket(const SharedBuffer<u8> &data, u16 seqnum)
void ReliablePacketBuffer::print()
{
MutexAutoLock listlock(m_list_mutex);
- LOG(dout_con << "Dump of ReliablePacketBuffer:" << std::endl);
+ LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
unsigned int index = 0;
for (BufferedPacket &bufferedPacket : m_list) {
- u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE + 1]));
- LOG(dout_con << index << ":" << s << std::endl);
+ u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
+ LOG(dout_con<<index<< ":" << s << std::endl);
index++;
}
}
@@ -190,8 +191,9 @@ u32 ReliablePacketBuffer::size()
RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
{
std::list<BufferedPacket>::iterator i = m_list.begin();
- for (; i != m_list.end(); ++i) {
- u16 s = readU16(&(i->data[BASE_HEADER_SIZE + 1]));
+ for(; i != m_list.end(); ++i)
+ {
+ u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
if (s == seqnum)
break;
}
@@ -203,7 +205,7 @@ RPBSearchResult ReliablePacketBuffer::notFound()
return m_list.end();
}
-bool ReliablePacketBuffer::getFirstSeqnum(u16 &result)
+bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
{
MutexAutoLock listlock(m_list_mutex);
if (m_list.empty())
@@ -235,16 +237,17 @@ BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
MutexAutoLock listlock(m_list_mutex);
RPBSearchResult r = findPacket(seqnum);
if (r == notFound()) {
- LOG(dout_con << "Sequence number: " << seqnum
- << " not found in reliable buffer" << std::endl);
+ LOG(dout_con<<"Sequence number: " << seqnum
+ << " not found in reliable buffer"<<std::endl);
throw NotFoundException("seqnum not found in buffer");
}
BufferedPacket p = *r;
+
RPBSearchResult next = r;
++next;
if (next != notFound()) {
- u16 s = readU16(&(next->data[BASE_HEADER_SIZE + 1]));
+ u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
m_oldest_non_answered_ack = s;
}
@@ -264,27 +267,25 @@ void ReliablePacketBuffer::insert(BufferedPacket &p, u16 next_expected)
MutexAutoLock listlock(m_list_mutex);
if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
- "reliable packet"
- << std::endl;
+ "reliable packet" << std::endl;
return;
}
u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
if (type != PACKET_TYPE_RELIABLE) {
errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
- << std::endl;
+ << std::endl;
return;
}
u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
- "expected window "
- << std::endl;
+ "expected window " << std::endl;
return;
}
if (seqnum == next_expected) {
errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
- << std::endl;
+ << std::endl;
return;
}
@@ -292,7 +293,8 @@ void ReliablePacketBuffer::insert(BufferedPacket &p, u16 next_expected)
// Find the right place for the packet and insert it there
// If list is empty, just add it
- if (m_list.empty()) {
+ if (m_list.empty())
+ {
m_list.push_back(p);
m_oldest_non_answered_ack = seqnum;
// Done.
@@ -302,47 +304,47 @@ void ReliablePacketBuffer::insert(BufferedPacket &p, u16 next_expected)
// Otherwise find the right place
std::list<BufferedPacket>::iterator i = m_list.begin();
// Find the first packet in the list which has a higher seqnum
- u16 s = readU16(&(i->data[BASE_HEADER_SIZE + 1]));
+ u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
/* case seqnum is smaller then next_expected seqnum */
/* this is true e.g. on wrap around */
if (seqnum < next_expected) {
- while (((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
+ while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
++i;
if (i != m_list.end())
- s = readU16(&(i->data[BASE_HEADER_SIZE + 1]));
+ s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
}
}
/* non wrap around case (at least for incoming and next_expected */
- else {
- while (((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
+ else
+ {
+ while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
++i;
if (i != m_list.end())
- s = readU16(&(i->data[BASE_HEADER_SIZE + 1]));
+ s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
}
}
if (s == seqnum) {
/* nothing to do this seems to be a resent packet */
/* for paranoia reason data should be compared */
- if ((readU16(&(i->data[BASE_HEADER_SIZE + 1])) != seqnum) ||
- (i->data.getSize() != p.data.getSize()) ||
- (i->address != p.address)) {
+ if (
+ (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
+ (i->data.getSize() != p.data.getSize()) ||
+ (i->address != p.address)
+ )
+ {
/* if this happens your maximum transfer window may be to big */
fprintf(stderr,
- "Duplicated seqnum %d non matching packet "
- "detected:\n",
+ "Duplicated seqnum %d non matching packet detected:\n",
seqnum);
fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
- readU16(&(i->data[BASE_HEADER_SIZE + 1])),
- i->data.getSize(),
+ readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
i->address.serializeString().c_str());
fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
- readU16(&(p.data[BASE_HEADER_SIZE + 1])),
- p.data.getSize(),
+ readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
p.address.serializeString().c_str());
- throw IncomingDataCorruption(
- "duplicated packet isn't same as original one");
+ throw IncomingDataCorruption("duplicated packet isn't same as original one");
}
}
/* insert or push back */
@@ -353,8 +355,7 @@ void ReliablePacketBuffer::insert(BufferedPacket &p, u16 next_expected)
}
/* update last packet number */
- m_oldest_non_answered_ack =
- readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE + 1]);
+ m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
}
void ReliablePacketBuffer::incrementTimeouts(float dtime)
@@ -366,8 +367,8 @@ void ReliablePacketBuffer::incrementTimeouts(float dtime)
}
}
-std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(
- float timeout, unsigned int max_packets)
+std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
+ unsigned int max_packets)
{
MutexAutoLock listlock(m_list_mutex);
std::list<BufferedPacket> timed_outs;
@@ -375,7 +376,7 @@ std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(
if (bufferedPacket.time >= timeout) {
timed_outs.push_back(bufferedPacket);
- // this packet will be sent right afterwards reset timeout here
+ //this packet will be sent right afterwards reset timeout here
bufferedPacket.time = 0.0f;
if (timed_outs.size() >= max_packets)
break;
@@ -446,19 +447,19 @@ SharedBuffer<u8> IncomingSplitBuffer::insert(const BufferedPacket &p, bool relia
errorstream << "Invalid data size for split packet" << std::endl;
return SharedBuffer<u8>();
}
- u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
- u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
- u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE + 3]);
- u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE + 5]);
+ u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
+ u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
+ u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
+ u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
if (type != PACKET_TYPE_SPLIT) {
errorstream << "IncomingSplitBuffer::insert(): type is not split"
- << std::endl;
+ << std::endl;
return SharedBuffer<u8>();
}
if (chunk_num >= chunk_count) {
errorstream << "IncomingSplitBuffer::insert(): chunk_num=" << chunk_num
- << " >= chunk_count=" << chunk_count << std::endl;
+ << " >= chunk_count=" << chunk_count << std::endl;
return SharedBuffer<u8>();
}
@@ -473,13 +474,14 @@ SharedBuffer<u8> IncomingSplitBuffer::insert(const BufferedPacket &p, bool relia
if (chunk_count != sp->chunk_count) {
errorstream << "IncomingSplitBuffer::insert(): chunk_count="
- << chunk_count << " != sp->chunk_count=" << sp->chunk_count
- << std::endl;
+ << chunk_count << " != sp->chunk_count=" << sp->chunk_count
+ << std::endl;
return SharedBuffer<u8>();
}
if (reliable != sp->reliable)
- LOG(derr_con << "Connection: WARNING: reliable=" << reliable
- << " != sp->reliable=" << sp->reliable << std::endl);
+ LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
+ <<" != sp->reliable="<<sp->reliable
+ <<std::endl);
// Cut chunk data out of packet
u32 chunkdatasize = p.data.getSize() - headersize;
@@ -519,8 +521,7 @@ void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
}
for (u16 j : remove_queue) {
MutexAutoLock listlock(m_map_mutex);
- LOG(dout_con << "NOTE: Removing timed out unreliable split packet"
- << std::endl);
+ LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
delete m_buf[j];
m_buf.erase(j);
}
@@ -530,8 +531,8 @@ void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
ConnectionCommand
*/
-void ConnectionCommand::send(
- session_t peer_id_, u8 channelnum_, NetworkPacket *pkt, bool reliable_)
+void ConnectionCommand::send(session_t peer_id_, u8 channelnum_, NetworkPacket *pkt,
+ bool reliable_)
{
type = CONNCMD_SEND;
peer_id = peer_id_;
@@ -569,36 +570,36 @@ void Channel::setNextSplitSeqNum(u16 seqnum)
next_outgoing_split_seqnum = seqnum;
}
-u16 Channel::getOutgoingSequenceNumber(bool &successful)
+u16 Channel::getOutgoingSequenceNumber(bool& successful)
{
MutexAutoLock internal(m_internal_mutex);
u16 retval = next_outgoing_seqnum;
u16 lowest_unacked_seqnumber;
/* shortcut if there ain't any packet in outgoing list */
- if (outgoing_reliables_sent.empty()) {
+ if (outgoing_reliables_sent.empty())
+ {
next_outgoing_seqnum++;
return retval;
}
- if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber)) {
+ if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
+ {
if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
// ugly cast but this one is required in order to tell compiler we
- // know about difference of two unsigned may be negative in
- // general but we already made sure it won't happen in this case
- if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) >
- window_size) {
+ // know about difference of two unsigned may be negative in general
+ // but we already made sure it won't happen in this case
+ if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
successful = false;
return 0;
}
- } else {
+ }
+ else {
// ugly cast but this one is required in order to tell compiler we
- // know about difference of two unsigned may be negative in
- // general but we already made sure it won't happen in this case
- if ((next_outgoing_seqnum +
- (u16)(SEQNUM_MAX -
- lowest_unacked_seqnumber)) >
- window_size) {
+ // know about difference of two unsigned may be negative in general
+ // but we already made sure it won't happen in this case
+ if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
+ window_size) {
successful = false;
return 0;
}
@@ -617,7 +618,7 @@ u16 Channel::readOutgoingSequenceNumber()
bool Channel::putBackSequenceNumber(u16 seqnum)
{
- if (((seqnum + 1) % (SEQNUM_MAX + 1)) == next_outgoing_seqnum) {
+ if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
next_outgoing_seqnum = seqnum;
return true;
@@ -632,8 +633,7 @@ void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
current_packet_successful += packets;
}
-void Channel::UpdateBytesReceived(unsigned int bytes)
-{
+void Channel::UpdateBytesReceived(unsigned int bytes) {
MutexAutoLock internal(m_internal_mutex);
current_bytes_received += bytes;
}
@@ -644,6 +644,7 @@ void Channel::UpdateBytesLost(unsigned int bytes)
current_bytes_lost += bytes;
}
+
void Channel::UpdatePacketLossCounter(unsigned int count)
{
MutexAutoLock internal(m_internal_mutex);
@@ -664,21 +665,19 @@ void Channel::UpdateTimers(float dtime)
if (packet_loss_counter > 1.0f) {
packet_loss_counter -= 1.0f;
- unsigned int packet_loss =
- 11; /* use a neutral value for initialization */
+ unsigned int packet_loss = 11; /* use a neutral value for initialization */
unsigned int packets_successful = 0;
- // unsigned int packet_too_late = 0;
+ //unsigned int packet_too_late = 0;
bool reasonable_amount_of_data_transmitted = false;
{
MutexAutoLock internal(m_internal_mutex);
packet_loss = current_packet_loss;
- // packet_too_late = current_packet_too_late;
+ //packet_too_late = current_packet_too_late;
packets_successful = current_packet_successful;
- if (current_bytes_transfered >
- (unsigned int)(window_size * 512 / 2)) {
+ if (current_bytes_transfered > (unsigned int) (window_size*512/2)) {
reasonable_amount_of_data_transmitted = true;
}
current_packet_loss = 0;
@@ -691,33 +690,38 @@ void Channel::UpdateTimers(float dtime)
bool done = false;
if (packets_successful > 0) {
- successful_to_lost_ratio = packet_loss / packets_successful;
+ successful_to_lost_ratio = packet_loss/packets_successful;
} else if (packet_loss > 0) {
window_size = std::max(
- (window_size - 10), MIN_RELIABLE_WINDOW_SIZE);
+ (window_size - 10),
+ MIN_RELIABLE_WINDOW_SIZE);
done = true;
}
if (!done) {
if ((successful_to_lost_ratio < 0.01f) &&
- (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
+ (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
/* don't even think about increasing if we didn't even
* use major parts of our window */
if (reasonable_amount_of_data_transmitted)
- window_size = std::min((window_size + 100),
+ window_size = std::min(
+ (window_size + 100),
MAX_RELIABLE_WINDOW_SIZE);
} else if ((successful_to_lost_ratio < 0.05f) &&
(window_size < MAX_RELIABLE_WINDOW_SIZE)) {
/* don't even think about increasing if we didn't even
* use major parts of our window */
if (reasonable_amount_of_data_transmitted)
- window_size = std::min((window_size + 50),
+ window_size = std::min(
+ (window_size + 50),
MAX_RELIABLE_WINDOW_SIZE);
} else if (successful_to_lost_ratio > 0.15f) {
- window_size = std::max((window_size - 100),
+ window_size = std::max(
+ (window_size - 100),
MIN_RELIABLE_WINDOW_SIZE);
} else if (successful_to_lost_ratio > 0.1f) {
- window_size = std::max((window_size - 50),
+ window_size = std::max(
+ (window_size - 50),
MIN_RELIABLE_WINDOW_SIZE);
}
}
@@ -726,17 +730,16 @@ void Channel::UpdateTimers(float dtime)
if (bpm_counter > 10.0f) {
{
MutexAutoLock internal(m_internal_mutex);
- cur_kbps = (((float)current_bytes_transfered) / bpm_counter) /
- 1024.0f;
+ cur_kbps =
+ (((float) current_bytes_transfered)/bpm_counter)/1024.0f;
current_bytes_transfered = 0;
- cur_kbps_lost = (((float)current_bytes_lost) / bpm_counter) /
- 1024.0f;
- current_bytes_lost = 0;
- cur_incoming_kbps =
- (((float)current_bytes_received) / bpm_counter) /
- 1024.0f;
- current_bytes_received = 0;
- bpm_counter = 0.0f;
+ cur_kbps_lost =
+ (((float) current_bytes_lost)/bpm_counter)/1024.0f;
+ current_bytes_lost = 0;
+ cur_incoming_kbps =
+ (((float) current_bytes_received)/bpm_counter)/1024.0f;
+ current_bytes_received = 0;
+ bpm_counter = 0.0f;
}
if (cur_kbps > max_kbps) {
@@ -751,21 +754,24 @@ void Channel::UpdateTimers(float dtime)
max_incoming_kbps = cur_incoming_kbps;
}
- rate_samples = MYMIN(rate_samples + 1, 10);
- float old_fraction = ((float)(rate_samples - 1)) / ((float)rate_samples);
- avg_kbps = avg_kbps * old_fraction + cur_kbps * (1.0 - old_fraction);
- avg_kbps_lost = avg_kbps_lost * old_fraction +
+ rate_samples = MYMIN(rate_samples+1,10);
+ float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
+ avg_kbps = avg_kbps * old_fraction +
+ cur_kbps * (1.0 - old_fraction);
+ avg_kbps_lost = avg_kbps_lost * old_fraction +
cur_kbps_lost * (1.0 - old_fraction);
- avg_incoming_kbps = avg_incoming_kbps * old_fraction +
- cur_incoming_kbps * (1.0 - old_fraction);
+ avg_incoming_kbps = avg_incoming_kbps * old_fraction +
+ cur_incoming_kbps * (1.0 - old_fraction);
}
}
+
/*
Peer
*/
-PeerHelper::PeerHelper(Peer *peer) : m_peer(peer)
+PeerHelper::PeerHelper(Peer* peer) :
+ m_peer(peer)
{
if (peer && !peer->IncUseCount())
m_peer = nullptr;
@@ -779,7 +785,7 @@ PeerHelper::~PeerHelper()
m_peer = nullptr;
}
-PeerHelper &PeerHelper::operator=(Peer *peer)
+PeerHelper& PeerHelper::operator=(Peer* peer)
{
m_peer = peer;
if (peer && !peer->IncUseCount())
@@ -787,24 +793,24 @@ PeerHelper &PeerHelper::operator=(Peer *peer)
return *this;
}
-Peer *PeerHelper::operator->() const
+Peer* PeerHelper::operator->() const
{
return m_peer;
}
-Peer *PeerHelper::operator&() const
+Peer* PeerHelper::operator&() const
{
return m_peer;
}
bool PeerHelper::operator!()
{
- return !m_peer;
+ return ! m_peer;
}
-bool PeerHelper::operator!=(void *ptr)
+bool PeerHelper::operator!=(void* ptr)
{
- return ((void *)m_peer != ptr);
+ return ((void*) m_peer != ptr);
}
bool Peer::IncUseCount()
@@ -832,9 +838,8 @@ void Peer::DecUseCount()
delete this;
}
-void Peer::RTTStatistics(
- float rtt, const std::string &profiler_id, unsigned int num_samples)
-{
+void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
+ unsigned int num_samples) {
if (m_last_rtt > 0) {
/* set min max values */
@@ -845,18 +850,18 @@ void Peer::RTTStatistics(
/* do average calculation */
if (m_rtt.avg_rtt < 0.0)
- m_rtt.avg_rtt = rtt;
+ m_rtt.avg_rtt = rtt;
else
- m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples / (num_samples - 1)) +
- rtt * (1 / num_samples);
+ m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
+ rtt * (1/num_samples);
/* do jitter calculation */
- // just use some neutral value at beginning
+ //just use some neutral value at beginning
float jitter = m_rtt.jitter_min;
if (rtt > m_last_rtt)
- jitter = rtt - m_last_rtt;
+ jitter = rtt-m_last_rtt;
if (rtt <= m_last_rtt)
jitter = m_last_rtt - rtt;
@@ -867,17 +872,14 @@ void Peer::RTTStatistics(
m_rtt.jitter_max = jitter;
if (m_rtt.jitter_avg < 0.0)
- m_rtt.jitter_avg = jitter;
+ m_rtt.jitter_avg = jitter;
else
- m_rtt.jitter_avg =
- m_rtt.jitter_avg *
- (num_samples / (num_samples - 1)) +
- jitter * (1 / num_samples);
+ m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
+ jitter * (1/num_samples);
if (!profiler_id.empty()) {
g_profiler->graphAdd(profiler_id + " RTT [ms]", rtt * 1000.f);
- g_profiler->graphAdd(
- profiler_id + " jitter [ms]", jitter * 1000.f);
+ g_profiler->graphAdd(profiler_id + " jitter [ms]", jitter * 1000.f);
}
}
/* save values required for next loop */
@@ -889,7 +891,7 @@ bool Peer::isTimedOut(float timeout)
MutexAutoLock lock(m_exclusive_access_mutex);
u64 current_time = porting::getTimeMs();
- float dtime = CALC_DTIME(m_last_timeout_check, current_time);
+ float dtime = CALC_DTIME(m_last_timeout_check,current_time);
m_last_timeout_check = current_time;
m_timeout_counter += dtime;
@@ -907,28 +909,28 @@ void Peer::Drop()
}
PROFILE(std::stringstream peerIdentifier1);
- PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc() << ";" << id
- << ";RELIABLE]");
+ PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
+ << ";" << id << ";RELIABLE]");
PROFILE(g_profiler->remove(peerIdentifier1.str()));
PROFILE(std::stringstream peerIdentifier2);
- PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc() << ";" << id
- << ";RELIABLE]");
+ PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
+ << ";" << id << ";RELIABLE]");
PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
delete this;
}
-UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection *connection) :
- Peer(a_address, a_id, connection)
+UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
+ Peer(a_address,a_id,connection)
{
for (Channel &channel : channels)
channel.setWindowSize(START_RELIABLE_WINDOW_SIZE);
}
-bool UDPPeer::getAddress(MTProtocols type, Address &toset)
+bool UDPPeer::getAddress(MTProtocols type,Address& toset)
{
- if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) ||
- (type == MTP_PRIMARY)) {
+ if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
+ {
toset = address;
return true;
}
@@ -941,7 +943,7 @@ void UDPPeer::reportRTT(float rtt)
if (rtt < 0.0) {
return;
}
- RTTStatistics(rtt, "rudp", MAX_RELIABLE_WINDOW_SIZE * 10);
+ RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
if (timeout < RESEND_TIMEOUT_MIN)
@@ -953,10 +955,11 @@ void UDPPeer::reportRTT(float rtt)
resend_timeout = timeout;
}
-bool UDPPeer::Ping(float dtime, SharedBuffer<u8> &data)
+bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
{
m_ping_timer += dtime;
- if (m_ping_timer >= PING_TIMEOUT) {
+ if (m_ping_timer >= PING_TIMEOUT)
+ {
// Create and send PING packet
writeU8(&data[0], PACKET_TYPE_CONTROL);
writeU8(&data[1], CONTROLTYPE_PING);
@@ -966,7 +969,8 @@ bool UDPPeer::Ping(float dtime, SharedBuffer<u8> &data)
return false;
}
-void UDPPeer::PutReliableSendCommand(ConnectionCommand &c, unsigned int max_packet_size)
+void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
+ unsigned int max_packet_size)
{
if (m_pending_disconnect)
return;
@@ -976,37 +980,41 @@ void UDPPeer::PutReliableSendCommand(ConnectionCommand &c, unsigned int max_pack
if (chan.queued_commands.empty() &&
/* don't queue more packets then window size */
(chan.queued_reliables.size() < chan.getWindowSize() / 2)) {
- LOG(dout_con << m_connection->getDesc()
- << " processing reliable command for peer id: " << c.peer_id
- << " data size: " << c.data.getSize() << std::endl);
- if (!processReliableSendCommand(c, max_packet_size)) {
+ LOG(dout_con<<m_connection->getDesc()
+ <<" processing reliable command for peer id: " << c.peer_id
+ <<" data size: " << c.data.getSize() << std::endl);
+ if (!processReliableSendCommand(c,max_packet_size)) {
chan.queued_commands.push_back(c);
}
- } else {
- LOG(dout_con << m_connection->getDesc()
- << " Queueing reliable command for peer id: " << c.peer_id
- << " data size: " << c.data.getSize() << std::endl);
+ }
+ else {
+ LOG(dout_con<<m_connection->getDesc()
+ <<" Queueing reliable command for peer id: " << c.peer_id
+ <<" data size: " << c.data.getSize() <<std::endl);
chan.queued_commands.push_back(c);
if (chan.queued_commands.size() >= chan.getWindowSize() / 2) {
LOG(derr_con << m_connection->getDesc()
- << "Possible packet stall to peer id: " << c.peer_id
- << " queued_commands=" << chan.queued_commands.size()
- << std::endl);
+ << "Possible packet stall to peer id: " << c.peer_id
+ << " queued_commands=" << chan.queued_commands.size()
+ << std::endl);
}
}
}
bool UDPPeer::processReliableSendCommand(
- ConnectionCommand &c, unsigned int max_packet_size)
+ ConnectionCommand &c,
+ unsigned int max_packet_size)
{
if (m_pending_disconnect)
return true;
Channel &chan = channels[c.channelnum];
- u32 chunksize_max = max_packet_size - BASE_HEADER_SIZE - RELIABLE_HEADER_SIZE;
+ u32 chunksize_max = max_packet_size
+ - BASE_HEADER_SIZE
+ - RELIABLE_HEADER_SIZE;
- sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE * 512);
+ sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
std::list<SharedBuffer<u8>> originals;
u16 split_sequence_number = chan.readNextSplitSeqNum();
@@ -1014,8 +1022,7 @@ bool UDPPeer::processReliableSendCommand(
if (c.raw) {
originals.emplace_back(c.data);
} else {
- makeAutoSplitPacket(
- c.data, chunksize_max, split_sequence_number, &originals);
+ makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals);
chan.setNextSplitSeqNum(split_sequence_number);
}
@@ -1031,7 +1038,8 @@ bool UDPPeer::processReliableSendCommand(
if (!have_sequence_number)
break;
- if (!have_initial_sequence_number) {
+ if (!have_initial_sequence_number)
+ {
initial_sequence_number = seqnum;
have_initial_sequence_number = true;
}
@@ -1051,14 +1059,11 @@ bool UDPPeer::processReliableSendCommand(
while (!toadd.empty()) {
BufferedPacket p = toadd.front();
toadd.pop();
- // LOG(dout_con<<connection->getDesc()
- // << " queuing reliable packet for
- //peer_id: " << c.peer_id
- // << " channel: " <<
- //(c.channelnum&0xFF)
- // << " seqnum: " <<
- //readU16(&p.data[BASE_HEADER_SIZE+1])
- // << std::endl)
+// LOG(dout_con<<connection->getDesc()
+// << " queuing reliable packet for peer_id: " << c.peer_id
+// << " channel: " << (c.channelnum&0xFF)
+// << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
+// << std::endl)
chan.queued_reliables.push(p);
pcount++;
}
@@ -1076,9 +1081,9 @@ bool UDPPeer::processReliableSendCommand(
/* remove packet */
toadd.pop();
- bool successfully_put_back_sequence_number = chan.putBackSequenceNumber(
- (initial_sequence_number +
- toadd.size() % (SEQNUM_MAX + 1)));
+ bool successfully_put_back_sequence_number
+ = chan.putBackSequenceNumber(
+ (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
}
@@ -1087,20 +1092,24 @@ bool UDPPeer::processReliableSendCommand(
// 'log_message_mutex' and 'm_list_mutex'.
u32 n_queued = chan.outgoing_reliables_sent.size();
- LOG(dout_con << m_connection->getDesc()
- << " Windowsize exceeded on reliable sending " << c.data.getSize()
- << " bytes" << std::endl
- << "\t\tinitial_sequence_number: " << initial_sequence_number
- << std::endl
- << "\t\tgot at most : " << packets_available << " packets"
- << std::endl
- << "\t\tpackets queued : " << n_queued << std::endl);
+ LOG(dout_con<<m_connection->getDesc()
+ << " Windowsize exceeded on reliable sending "
+ << c.data.getSize() << " bytes"
+ << std::endl << "\t\tinitial_sequence_number: "
+ << initial_sequence_number
+ << std::endl << "\t\tgot at most : "
+ << packets_available << " packets"
+ << std::endl << "\t\tpackets queued : "
+ << n_queued
+ << std::endl);
return false;
}
-void UDPPeer::RunCommandQueues(unsigned int max_packet_size, unsigned int maxcommands,
- unsigned int maxtransfer)
+void UDPPeer::RunCommandQueues(
+ unsigned int max_packet_size,
+ unsigned int maxcommands,
+ unsigned int maxtransfer)
{
for (Channel &channel : channels) {
@@ -1113,22 +1122,19 @@ void UDPPeer::RunCommandQueues(unsigned int max_packet_size, unsigned int maxcom
ConnectionCommand c = channel.queued_commands.front();
LOG(dout_con << m_connection->getDesc()
- << " processing queued reliable command "
- << std::endl);
+ << " processing queued reliable command " << std::endl);
// Packet is processed, remove it from queue
- if (processReliableSendCommand(c, max_packet_size)) {
+ if (processReliableSendCommand(c,max_packet_size)) {
channel.queued_commands.pop_front();
} else {
LOG(dout_con << m_connection->getDesc()
- << " Failed to queue packets for "
- "peer_id: "
- << c.peer_id
- << ", delaying sending of "
- << c.data.getSize() << " bytes"
- << std::endl);
+ << " Failed to queue packets for peer_id: " << c.peer_id
+ << ", delaying sending of " << c.data.getSize()
+ << " bytes" << std::endl);
}
- } catch (ItemNotFoundException &e) {
+ }
+ catch (ItemNotFoundException &e) {
// intentionally empty
}
}
@@ -1147,8 +1153,8 @@ void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
channels[channel].setNextSplitSeqNum(seqnum);
}
-SharedBuffer<u8> UDPPeer::addSplitPacket(
- u8 channel, const BufferedPacket &toadd, bool reliable)
+SharedBuffer<u8> UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd,
+ bool reliable)
{
assert(channel < CHANNEL_COUNT); // Pre-condition
return channels[channel].incoming_splits.insert(toadd, reliable);
@@ -1158,13 +1164,13 @@ SharedBuffer<u8> UDPPeer::addSplitPacket(
Connection
*/
-Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool ipv6,
- PeerHandler *peerhandler) :
- m_udpSocket(ipv6),
- m_protocol_id(protocol_id),
- m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
- m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
- m_bc_peerhandler(peerhandler)
+Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
+ bool ipv6, PeerHandler *peerhandler) :
+ m_udpSocket(ipv6),
+ m_protocol_id(protocol_id),
+ m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
+ m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
+ m_bc_peerhandler(peerhandler)
{
/* Amount of time Receive() will wait for data, this is entirely different
@@ -1178,6 +1184,7 @@ Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool
m_receiveThread->start();
}
+
Connection::~Connection()
{
m_shutting_down = true;
@@ -1185,7 +1192,7 @@ Connection::~Connection()
m_sendThread->stop();
m_receiveThread->stop();
- // TODO for some unkonwn reason send/receive threads do not exit as they're
+ //TODO for some unkonwn reason send/receive threads do not exit as they're
// supposed to be but wait on peer timeout. To speed up shutdown we reduce
// timeout to half a second.
m_sendThread->setPeerTimeout(0.5);
@@ -1228,20 +1235,20 @@ PeerHelper Connection::getPeerNoEx(session_t peer_id)
}
/* find peer_id for address */
-u16 Connection::lookupPeer(Address &sender)
+u16 Connection::lookupPeer(Address& sender)
{
MutexAutoLock peerlock(m_peers_mutex);
- std::map<u16, Peer *>::iterator j;
+ std::map<u16, Peer*>::iterator j;
j = m_peers.begin();
- for (; j != m_peers.end(); ++j) {
+ for(; j != m_peers.end(); ++j)
+ {
Peer *peer = j->second;
if (peer->isPendingDeletion())
continue;
Address tocheck;
- if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) &&
- (tocheck == sender))
+ if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
return peer->id;
if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
@@ -1266,13 +1273,14 @@ bool Connection::deletePeer(session_t peer_id, bool timeout)
}
Address peer_address;
- // any peer has a primary address this never fails!
+ //any peer has a primary address this never fails!
peer->getAddress(MTP_PRIMARY, peer_address);
// Create event
ConnectionEvent e;
e.peerRemoved(peer_id, timeout, peer_address);
putEvent(e);
+
peer->Drop();
return true;
}
@@ -1283,7 +1291,7 @@ ConnectionEvent Connection::waitEvent(u32 timeout_ms)
{
try {
return m_event_queue.pop_front(timeout_ms);
- } catch (ItemNotFoundException &ex) {
+ } catch(ItemNotFoundException &ex) {
ConnectionEvent e;
e.type = CONNEVENT_NONE;
return e;
@@ -1343,12 +1351,12 @@ bool Connection::Receive(NetworkPacket *pkt, u32 timeout)
events keep happening before the timeout expires.
This is not considered to be a problem (is it?)
*/
- for (;;) {
+ for(;;) {
ConnectionEvent e = waitEvent(timeout);
if (e.type != CONNEVENT_NONE)
LOG(dout_con << getDesc() << ": Receive: got event: "
- << e.describe() << std::endl);
- switch (e.type) {
+ << e.describe() << std::endl);
+ switch(e.type) {
case CONNEVENT_NONE:
return false;
case CONNEVENT_DATA_RECEIVED:
@@ -1373,7 +1381,7 @@ bool Connection::Receive(NetworkPacket *pkt, u32 timeout)
}
case CONNEVENT_BIND_FAILED:
throw ConnectionBindFailed("Failed to bind socket "
- "(port already in use?)");
+ "(port already in use?)");
}
}
return false;
@@ -1391,7 +1399,8 @@ bool Connection::TryReceive(NetworkPacket *pkt)
return Receive(pkt, 0);
}
-void Connection::Send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable)
+void Connection::Send(session_t peer_id, u8 channelnum,
+ NetworkPacket *pkt, bool reliable)
{
assert(channelnum < CHANNEL_COUNT); // Pre-condition
@@ -1415,8 +1424,7 @@ Address Connection::GetPeerAddress(session_t peer_id)
float Connection::getPeerStat(session_t peer_id, rtt_stat_type type)
{
PeerHelper peer = getPeerNoEx(peer_id);
- if (!peer)
- return -1;
+ if (!peer) return -1;
return peer->getStat(type);
}
@@ -1424,31 +1432,30 @@ float Connection::getLocalStat(rate_stat_type type)
{
PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
- FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? "
- "are you serious???");
+ FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
float retval = 0.0;
for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
- switch (type) {
- case CUR_DL_RATE:
- retval += channel.getCurrentDownloadRateKB();
- break;
- case AVG_DL_RATE:
- retval += channel.getAvgDownloadRateKB();
- break;
- case CUR_INC_RATE:
- retval += channel.getCurrentIncomingRateKB();
- break;
- case AVG_INC_RATE:
- retval += channel.getAvgIncomingRateKB();
- break;
- case AVG_LOSS_RATE:
- retval += channel.getAvgLossRateKB();
- break;
- case CUR_LOSS_RATE:
- retval += channel.getCurrentLossRateKB();
- break;
+ switch(type) {
+ case CUR_DL_RATE:
+ retval += channel.getCurrentDownloadRateKB();
+ break;
+ case AVG_DL_RATE:
+ retval += channel.getAvgDownloadRateKB();
+ break;
+ case CUR_INC_RATE:
+ retval += channel.getCurrentIncomingRateKB();
+ break;
+ case AVG_INC_RATE:
+ retval += channel.getAvgIncomingRateKB();
+ break;
+ case AVG_LOSS_RATE:
+ retval += channel.getAvgLossRateKB();
+ break;
+ case CUR_LOSS_RATE:
+ retval += channel.getCurrentLossRateKB();
+ break;
default:
FATAL_ERROR("Connection::getLocalStat Invalid stat type");
}
@@ -1456,20 +1463,20 @@ float Connection::getLocalStat(rate_stat_type type)
return retval;
}
-u16 Connection::createPeer(Address &sender, MTProtocols protocol, int fd)
+u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
{
// Somebody wants to make a new connection
// Get a unique peer id (2 or higher)
session_t peer_id_new = m_next_remote_peer_id;
- u16 overflow = MAX_UDP_PEERS;
+ u16 overflow = MAX_UDP_PEERS;
/*
Find an unused peer id
*/
MutexAutoLock lock(m_peers_mutex);
bool out_of_ids = false;
- for (;;) {
+ for(;;) {
// Check if exists
if (m_peers.find(peer_id_new) == m_peers.end())
@@ -1494,17 +1501,17 @@ u16 Connection::createPeer(Address &sender, MTProtocols protocol, int fd)
m_peers[peer->id] = peer;
m_peer_ids.push_back(peer->id);
- m_next_remote_peer_id = (peer_id_new + 1) % MAX_UDP_PEERS;
+ 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);
+ LOG(dout_con << getDesc()
+ << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
ConnectionCommand cmd;
SharedBuffer<u8> reply(4);
writeU8(&reply[0], PACKET_TYPE_CONTROL);
writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
writeU16(&reply[2], peer_id_new);
- cmd.createPeer(peer_id_new, reply);
+ cmd.createPeer(peer_id_new,reply);
putCommand(cmd);
// Create peer addition event
@@ -1519,14 +1526,14 @@ u16 Connection::createPeer(Address &sender, MTProtocols protocol, int fd)
void Connection::PrintInfo(std::ostream &out)
{
m_info_mutex.lock();
- out << getDesc() << ": ";
+ out<<getDesc()<<": ";
m_info_mutex.unlock();
}
const std::string Connection::getDesc()
{
- return std::string("con(") + itos(m_udpSocket.GetHandle()) + "/" +
- itos(m_peer_id) + ")";
+ return std::string("con(")+
+ itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
}
void Connection::DisconnectPeer(session_t peer_id)
@@ -1540,9 +1547,10 @@ void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum)
{
assert(channelnum < CHANNEL_COUNT); // Pre-condition
- LOG(dout_con << getDesc() << " Queuing ACK command to peer_id: " << peer_id
- << " channel: " << (channelnum & 0xFF) << " seqnum: " << seqnum
- << std::endl);
+ LOG(dout_con<<getDesc()
+ <<" Queuing ACK command to peer_id: " << peer_id <<
+ " channel: " << (channelnum & 0xFF) <<
+ " seqnum: " << seqnum << std::endl);
ConnectionCommand c;
SharedBuffer<u8> ack(4);
@@ -1555,9 +1563,10 @@ void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum)
m_sendThread->Trigger();
}
-UDPPeer *Connection::createServerPeer(Address &address)
+UDPPeer* Connection::createServerPeer(Address& address)
{
- if (getPeerNoEx(PEER_ID_SERVER) != 0) {
+ if (getPeerNoEx(PEER_ID_SERVER) != 0)
+ {
throw ConnectionException("Already connected to a server");
}
diff --git a/src/network/connection.h b/src/network/connection.h
index 9febfb2b7..47b0805ce 100644
--- a/src/network/connection.h
+++ b/src/network/connection.h
@@ -41,8 +41,7 @@ namespace con
class ConnectionReceiveThread;
class ConnectionSendThread;
-typedef enum MTProtocols
-{
+typedef enum MTProtocols {
MTP_PRIMARY,
MTP_UDP,
MTP_MINETEST_RELIABLE_UDP
@@ -54,43 +53,49 @@ typedef enum MTProtocols
inline bool seqnum_higher(u16 totest, u16 base)
{
- if (totest > base) {
- if ((totest - base) > (SEQNUM_MAX / 2))
+ if (totest > base)
+ {
+ if ((totest - base) > (SEQNUM_MAX/2))
return false;
return true;
}
- if ((base - totest) > (SEQNUM_MAX / 2))
+ if ((base - totest) > (SEQNUM_MAX/2))
return true;
return false;
}
-inline bool seqnum_in_window(u16 seqnum, u16 next, u16 window_size)
+inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size)
{
u16 window_start = next;
- u16 window_end = (next + window_size) % (SEQNUM_MAX + 1);
+ u16 window_end = ( next + window_size ) % (SEQNUM_MAX+1);
if (window_start < window_end) {
return ((seqnum >= window_start) && (seqnum < window_end));
}
+
return ((seqnum < window_end) || (seqnum >= window_start));
}
static inline float CALC_DTIME(u64 lasttime, u64 curtime)
{
- float value = (curtime - lasttime) / 1000.0;
- return MYMAX(MYMIN(value, 0.1), 0.0);
+ float value = ( curtime - lasttime) / 1000.0;
+ return MYMAX(MYMIN(value,0.1),0.0);
}
struct BufferedPacket
{
- BufferedPacket(u8 *a_data, u32 a_size) : data(a_data, a_size) {}
- BufferedPacket(u32 a_size) : data(a_size) {}
- Buffer<u8> data; // Data of the packet, including headers
- float time = 0.0f; // Seconds from buffering the packet or re-sending
+ BufferedPacket(u8 *a_data, u32 a_size):
+ data(a_data, a_size)
+ {}
+ BufferedPacket(u32 a_size):
+ data(a_size)
+ {}
+ Buffer<u8> data; // Data of the packet, including headers
+ float time = 0.0f; // Seconds from buffering the packet or re-sending
float totaltime = 0.0f; // Seconds from buffering the packet
u64 absolute_send_time = -1;
Address address; // Sender or destination
@@ -98,8 +103,8 @@ struct BufferedPacket
};
// This adds the base headers to the data and makes a packet out of it
-BufferedPacket makePacket(Address &address, const SharedBuffer<u8> &data, u32 protocol_id,
- session_t sender_peer_id, u8 channel);
+BufferedPacket makePacket(Address &address, const SharedBuffer<u8> &data,
+ u32 protocol_id, session_t sender_peer_id, u8 channel);
// Depending on size, make a TYPE_ORIGINAL or TYPE_SPLIT packet
// Increments split_seqnum if a split packet is made
@@ -111,7 +116,8 @@ SharedBuffer<u8> makeReliablePacket(const SharedBuffer<u8> &data, u16 seqnum);
struct IncomingSplitPacket
{
- IncomingSplitPacket(u32 cc, bool r) : chunk_count(cc), reliable(r) {}
+ IncomingSplitPacket(u32 cc, bool r):
+ chunk_count(cc), reliable(r) {}
IncomingSplitPacket() = delete;
@@ -119,7 +125,10 @@ struct IncomingSplitPacket
u32 chunk_count;
bool reliable; // If true, isn't deleted on timeout
- bool allReceived() const { return (chunks.size() == chunk_count); }
+ bool allReceived() const
+ {
+ return (chunks.size() == chunk_count);
+ }
bool insert(u32 chunk_num, SharedBuffer<u8> &chunkdata);
SharedBuffer<u8> reassemble();
@@ -210,8 +219,7 @@ with a buffer in the receiving and transmitting end.
#define RELIABLE_HEADER_SIZE 3
#define SEQNUM_INITIAL 65500
-enum PacketType : u8
-{
+enum PacketType: u8 {
PACKET_TYPE_CONTROL = 0,
PACKET_TYPE_ORIGINAL = 1,
PACKET_TYPE_SPLIT = 2,
@@ -230,20 +238,22 @@ class ReliablePacketBuffer
public:
ReliablePacketBuffer() = default;
- bool getFirstSeqnum(u16 &result);
+ bool getFirstSeqnum(u16& result);
BufferedPacket popFirst();
BufferedPacket popSeqnum(u16 seqnum);
void insert(BufferedPacket &p, u16 next_expected);
void incrementTimeouts(float dtime);
- std::list<BufferedPacket> getTimedOuts(float timeout, unsigned int max_packets);
+ std::list<BufferedPacket> getTimedOuts(float timeout,
+ unsigned int max_packets);
void print();
bool empty();
RPBSearchResult notFound();
u32 size();
+
private:
RPBSearchResult findPacket(u16 seqnum); // does not perform locking
@@ -272,7 +282,7 @@ public:
private:
// Key is seqnum
- std::map<u16, IncomingSplitPacket *> m_buf;
+ std::map<u16, IncomingSplitPacket*> m_buf;
std::mutex m_map_mutex;
};
@@ -286,16 +296,17 @@ struct OutgoingPacket
bool ack;
OutgoingPacket(session_t peer_id_, u8 channelnum_, const SharedBuffer<u8> &data_,
- bool reliable_, bool ack_ = false) :
- peer_id(peer_id_),
- channelnum(channelnum_), data(data_), reliable(reliable_),
- ack(ack_)
+ bool reliable_,bool ack_=false):
+ peer_id(peer_id_),
+ channelnum(channelnum_),
+ data(data_),
+ reliable(reliable_),
+ ack(ack_)
{
}
};
-enum ConnectionCommandType
-{
+enum ConnectionCommandType{
CONNCMD_NONE,
CONNCMD_SERVE,
CONNCMD_CONNECT,
@@ -341,7 +352,10 @@ struct ConnectionCommand
type = CONNCMD_CONNECT;
address = address_;
}
- void disconnect() { type = CONNCMD_DISCONNECT; }
+ void disconnect()
+ {
+ type = CONNCMD_DISCONNECT;
+ }
void disconnect_peer(session_t peer_id_)
{
type = CONNCMD_DISCONNECT_PEER;
@@ -387,7 +401,7 @@ public:
u16 readNextIncomingSeqNum();
u16 incNextIncomingSeqNum();
- u16 getOutgoingSequenceNumber(bool &successfull);
+ u16 getOutgoingSequenceNumber(bool& successfull);
u16 readOutgoingSequenceNumber();
bool putBackSequenceNumber(u16);
@@ -401,10 +415,10 @@ public:
// re-send them if no ACK is received
ReliablePacketBuffer outgoing_reliables_sent;
- // queued reliable packets
+ //queued reliable packets
std::queue<BufferedPacket> queued_reliables;
- // queue commands prior splitting to packets
+ //queue commands prior splitting to packets
std::deque<ConnectionCommand> queued_commands;
IncomingSplitBuffer incoming_splits;
@@ -414,65 +428,37 @@ public:
void UpdatePacketLossCounter(unsigned int count);
void UpdatePacketTooLateCounter();
- void UpdateBytesSent(unsigned int bytes, unsigned int packages = 1);
+ void UpdateBytesSent(unsigned int bytes,unsigned int packages=1);
void UpdateBytesLost(unsigned int bytes);
void UpdateBytesReceived(unsigned int bytes);
void UpdateTimers(float dtime);
const float getCurrentDownloadRateKB()
- {
- MutexAutoLock lock(m_internal_mutex);
- return cur_kbps;
- };
+ { MutexAutoLock lock(m_internal_mutex); return cur_kbps; };
const float getMaxDownloadRateKB()
- {
- MutexAutoLock lock(m_internal_mutex);
- return max_kbps;
- };
+ { MutexAutoLock lock(m_internal_mutex); return max_kbps; };
const float getCurrentLossRateKB()
- {
- MutexAutoLock lock(m_internal_mutex);
- return cur_kbps_lost;
- };
+ { MutexAutoLock lock(m_internal_mutex); return cur_kbps_lost; };
const float getMaxLossRateKB()
- {
- MutexAutoLock lock(m_internal_mutex);
- return max_kbps_lost;
- };
+ { MutexAutoLock lock(m_internal_mutex); return max_kbps_lost; };
const float getCurrentIncomingRateKB()
- {
- MutexAutoLock lock(m_internal_mutex);
- return cur_incoming_kbps;
- };
+ { MutexAutoLock lock(m_internal_mutex); return cur_incoming_kbps; };
const float getMaxIncomingRateKB()
- {
- MutexAutoLock lock(m_internal_mutex);
- return max_incoming_kbps;
- };
+ { MutexAutoLock lock(m_internal_mutex); return max_incoming_kbps; };
const float getAvgDownloadRateKB()
- {
- MutexAutoLock lock(m_internal_mutex);
- return avg_kbps;
- };
+ { MutexAutoLock lock(m_internal_mutex); return avg_kbps; };
const float getAvgLossRateKB()
- {
- MutexAutoLock lock(m_internal_mutex);
- return avg_kbps_lost;
- };
+ { MutexAutoLock lock(m_internal_mutex); return avg_kbps_lost; };
const float getAvgIncomingRateKB()
- {
- MutexAutoLock lock(m_internal_mutex);
- return avg_incoming_kbps;
- };
+ { MutexAutoLock lock(m_internal_mutex); return avg_incoming_kbps; };
const unsigned int getWindowSize() const { return window_size; };
void setWindowSize(unsigned int size) { window_size = size; };
-
private:
std::mutex m_internal_mutex;
int window_size = MIN_RELIABLE_WINDOW_SIZE;
@@ -510,14 +496,14 @@ class PeerHelper
{
public:
PeerHelper() = default;
- PeerHelper(Peer *peer);
+ PeerHelper(Peer* peer);
~PeerHelper();
- PeerHelper &operator=(Peer *peer);
- Peer *operator->() const;
- bool operator!();
- Peer *operator&() const;
- bool operator!=(void *ptr);
+ PeerHelper& operator=(Peer* peer);
+ Peer* operator->() const;
+ bool operator!();
+ Peer* operator&() const;
+ bool operator!=(void* ptr);
private:
Peer *m_peer = nullptr;
@@ -525,8 +511,7 @@ private:
class Connection;
-typedef enum
-{
+typedef enum {
CUR_DL_RATE,
AVG_DL_RATE,
CUR_INC_RATE,
@@ -535,144 +520,140 @@ typedef enum
AVG_LOSS_RATE,
} rate_stat_type;
-class Peer
-{
-public:
- friend class PeerHelper;
-
- Peer(Address address_, u16 id_, Connection *connection) :
- id(id_), m_connection(connection), address(address_),
- m_last_timeout_check(porting::getTimeMs()){};
-
- virtual ~Peer()
- {
- MutexAutoLock usage_lock(m_exclusive_access_mutex);
- FATAL_ERROR_IF(m_usage != 0, "Reference counting failure");
- };
-
- // Unique id of the peer
- u16 id;
-
- void Drop();
-
- virtual void PutReliableSendCommand(
- ConnectionCommand &c, unsigned int max_packet_size){};
-
- virtual bool getAddress(MTProtocols type, Address &toset) = 0;
-
- bool isPendingDeletion()
- {
- MutexAutoLock lock(m_exclusive_access_mutex);
- return m_pending_deletion;
- };
-
- void ResetTimeout()
- {
- MutexAutoLock lock(m_exclusive_access_mutex);
- m_timeout_counter = 0.0;
- };
-
- bool isTimedOut(float timeout);
-
- unsigned int m_increment_packets_remaining = 0;
-
- virtual u16 getNextSplitSequenceNumber(u8 channel) { return 0; };
- virtual void setNextSplitSequenceNumber(u8 channel, u16 seqnum){};
- virtual SharedBuffer<u8> addSplitPacket(
- u8 channel, const BufferedPacket &toadd, bool reliable)
- {
- errorstream << "Peer::addSplitPacket called,"
- << " this is supposed to be never called!" << std::endl;
- return SharedBuffer<u8>(0);
- };
-
- virtual bool Ping(float dtime, SharedBuffer<u8> &data) { return false; };
-
- virtual float getStat(rtt_stat_type type) const
- {
- switch (type) {
- case MIN_RTT:
- return m_rtt.min_rtt;
- case MAX_RTT:
- return m_rtt.max_rtt;
- case AVG_RTT:
- return m_rtt.avg_rtt;
- case MIN_JITTER:
- return m_rtt.jitter_min;
- case MAX_JITTER:
- return m_rtt.jitter_max;
- case AVG_JITTER:
- return m_rtt.jitter_avg;
+class Peer {
+ public:
+ friend class PeerHelper;
+
+ Peer(Address address_,u16 id_,Connection* connection) :
+ id(id_),
+ m_connection(connection),
+ address(address_),
+ m_last_timeout_check(porting::getTimeMs())
+ {
+ };
+
+ virtual ~Peer() {
+ MutexAutoLock usage_lock(m_exclusive_access_mutex);
+ FATAL_ERROR_IF(m_usage != 0, "Reference counting failure");
+ };
+
+ // Unique id of the peer
+ u16 id;
+
+ void Drop();
+
+ virtual void PutReliableSendCommand(ConnectionCommand &c,
+ unsigned int max_packet_size) {};
+
+ virtual bool getAddress(MTProtocols type, Address& toset) = 0;
+
+ bool isPendingDeletion()
+ { MutexAutoLock lock(m_exclusive_access_mutex); return m_pending_deletion; };
+
+ void ResetTimeout()
+ {MutexAutoLock lock(m_exclusive_access_mutex); m_timeout_counter = 0.0; };
+
+ bool isTimedOut(float timeout);
+
+ unsigned int m_increment_packets_remaining = 0;
+
+ virtual u16 getNextSplitSequenceNumber(u8 channel) { return 0; };
+ virtual void setNextSplitSequenceNumber(u8 channel, u16 seqnum) {};
+ virtual SharedBuffer<u8> addSplitPacket(u8 channel, const BufferedPacket &toadd,
+ bool reliable)
+ {
+ errorstream << "Peer::addSplitPacket called,"
+ << " this is supposed to be never called!" << std::endl;
+ return SharedBuffer<u8>(0);
+ };
+
+ virtual bool Ping(float dtime, SharedBuffer<u8>& data) { return false; };
+
+ virtual float getStat(rtt_stat_type type) const {
+ switch (type) {
+ case MIN_RTT:
+ return m_rtt.min_rtt;
+ case MAX_RTT:
+ return m_rtt.max_rtt;
+ case AVG_RTT:
+ return m_rtt.avg_rtt;
+ case MIN_JITTER:
+ return m_rtt.jitter_min;
+ case MAX_JITTER:
+ return m_rtt.jitter_max;
+ case AVG_JITTER:
+ return m_rtt.jitter_avg;
+ }
+ return -1;
}
- return -1;
- }
+ protected:
+ virtual void reportRTT(float rtt) {};
-protected:
- virtual void reportRTT(float rtt){};
+ void RTTStatistics(float rtt,
+ const std::string &profiler_id = "",
+ unsigned int num_samples = 1000);
- void RTTStatistics(float rtt, const std::string &profiler_id = "",
- unsigned int num_samples = 1000);
+ bool IncUseCount();
+ void DecUseCount();
- bool IncUseCount();
- void DecUseCount();
+ std::mutex m_exclusive_access_mutex;
- std::mutex m_exclusive_access_mutex;
+ bool m_pending_deletion = false;
- bool m_pending_deletion = false;
+ Connection* m_connection;
- Connection *m_connection;
+ // Address of the peer
+ Address address;
- // Address of the peer
- Address address;
-
- // Ping timer
- float m_ping_timer = 0.0f;
+ // Ping timer
+ float m_ping_timer = 0.0f;
+ private:
-private:
- struct rttstats
- {
- float jitter_min = FLT_MAX;
- float jitter_max = 0.0f;
- float jitter_avg = -1.0f;
- float min_rtt = FLT_MAX;
- float max_rtt = 0.0f;
- float avg_rtt = -1.0f;
+ struct rttstats {
+ float jitter_min = FLT_MAX;
+ float jitter_max = 0.0f;
+ float jitter_avg = -1.0f;
+ float min_rtt = FLT_MAX;
+ float max_rtt = 0.0f;
+ float avg_rtt = -1.0f;
- rttstats() = default;
- };
+ rttstats() = default;
+ };
- rttstats m_rtt;
- float m_last_rtt = -1.0f;
+ rttstats m_rtt;
+ float m_last_rtt = -1.0f;
- // current usage count
- unsigned int m_usage = 0;
+ // current usage count
+ unsigned int m_usage = 0;
- // Seconds from last receive
- float m_timeout_counter = 0.0f;
+ // Seconds from last receive
+ float m_timeout_counter = 0.0f;
- u64 m_last_timeout_check;
+ u64 m_last_timeout_check;
};
class UDPPeer : public Peer
{
public:
+
friend class PeerHelper;
friend class ConnectionReceiveThread;
friend class ConnectionSendThread;
friend class Connection;
- UDPPeer(u16 a_id, Address a_address, Connection *connection);
+ UDPPeer(u16 a_id, Address a_address, Connection* connection);
virtual ~UDPPeer() = default;
- void PutReliableSendCommand(ConnectionCommand &c, unsigned int max_packet_size);
+ void PutReliableSendCommand(ConnectionCommand &c,
+ unsigned int max_packet_size);
- bool getAddress(MTProtocols type, Address &toset);
+ bool getAddress(MTProtocols type, Address& toset);
u16 getNextSplitSequenceNumber(u8 channel);
void setNextSplitSequenceNumber(u8 channel, u16 seqnum);
- SharedBuffer<u8> addSplitPacket(
- u8 channel, const BufferedPacket &toadd, bool reliable);
+ SharedBuffer<u8> addSplitPacket(u8 channel, const BufferedPacket &toadd,
+ bool reliable);
protected:
/*
@@ -681,39 +662,34 @@ protected:
*/
void reportRTT(float rtt);
- void RunCommandQueues(unsigned int max_packet_size, unsigned int maxcommands,
- unsigned int maxtransfer);
+ void RunCommandQueues(
+ unsigned int max_packet_size,
+ unsigned int maxcommands,
+ unsigned int maxtransfer);
float getResendTimeout()
- {
- MutexAutoLock lock(m_exclusive_access_mutex);
- return resend_timeout;
- }
+ { MutexAutoLock lock(m_exclusive_access_mutex); return resend_timeout; }
void setResendTimeout(float timeout)
- {
- MutexAutoLock lock(m_exclusive_access_mutex);
- resend_timeout = timeout;
- }
- bool Ping(float dtime, SharedBuffer<u8> &data);
+ { MutexAutoLock lock(m_exclusive_access_mutex); resend_timeout = timeout; }
+ bool Ping(float dtime,SharedBuffer<u8>& data);
Channel channels[CHANNEL_COUNT];
bool m_pending_disconnect = false;
-
private:
// This is changed dynamically
float resend_timeout = 0.5;
bool processReliableSendCommand(
- ConnectionCommand &c, unsigned int max_packet_size);
+ ConnectionCommand &c,
+ unsigned int max_packet_size);
};
/*
Connection
*/
-enum ConnectionEventType
-{
+enum ConnectionEventType{
CONNEVENT_NONE,
CONNEVENT_DATA_RECEIVED,
CONNEVENT_PEER_ADDED,
@@ -733,7 +709,7 @@ struct ConnectionEvent
std::string describe()
{
- switch (type) {
+ switch(type) {
case CONNEVENT_NONE:
return "CONNEVENT_NONE";
case CONNEVENT_DATA_RECEIVED:
@@ -767,7 +743,10 @@ struct ConnectionEvent
timeout = timeout_;
address = address_;
}
- void bindFailed() { type = CONNEVENT_BIND_FAILED; }
+ void bindFailed()
+ {
+ type = CONNEVENT_BIND_FAILED;
+ }
};
class PeerHandler;
@@ -791,7 +770,7 @@ public:
void Connect(Address address);
bool Connected();
void Disconnect();
- void Receive(NetworkPacket *pkt);
+ void Receive(NetworkPacket* pkt);
bool TryReceive(NetworkPacket *pkt);
void Send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable);
session_t GetPeerID() const { return m_peer_id; }
@@ -804,10 +783,10 @@ public:
protected:
PeerHelper getPeerNoEx(session_t peer_id);
- u16 lookupPeer(Address &sender);
+ u16 lookupPeer(Address& sender);
- u16 createPeer(Address &sender, MTProtocols protocol, int fd);
- UDPPeer *createServerPeer(Address &sender);
+ u16 createPeer(Address& sender, MTProtocols protocol, int fd);
+ UDPPeer* createServerPeer(Address& sender);
bool deletePeer(session_t peer_id, bool timeout);
void SetPeerID(session_t id) { m_peer_id = id; }
@@ -830,7 +809,6 @@ protected:
void putEvent(ConnectionEvent &e);
void TriggerSend();
-
private:
MutexedQueue<ConnectionEvent> m_event_queue;
diff --git a/src/network/connectionthreads.cpp b/src/network/connectionthreads.cpp
index 4d47b776c..9a6617a1c 100644
--- a/src/network/connectionthreads.cpp
+++ b/src/network/connectionthreads.cpp
@@ -38,10 +38,10 @@ namespace con
#else
/* this mutex is used to achieve log message consistency */
std::mutex log_conthread_mutex;
-#define LOG(a) \
- { \
- MutexAutoLock loglock(log_conthread_mutex); \
- a; \
+#define LOG(a) \
+ { \
+ MutexAutoLock loglock(log_conthread_mutex); \
+ a; \
}
#define PROFILE(a) a
//#define DEBUG_CONNECTION_KBPS
@@ -66,10 +66,12 @@ static u8 readChannel(u8 *packetdata)
/* Connection Threads */
/******************************************************************************/
-ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size, float timeout) :
- Thread("ConnectionSend"), m_max_packet_size(max_packet_size),
- m_timeout(timeout), m_max_data_packets_per_iteration(g_settings->getU16(
- "max_packets_per_iteration"))
+ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size,
+ float timeout) :
+ Thread("ConnectionSend"),
+ m_max_packet_size(max_packet_size),
+ m_timeout(timeout),
+ m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration"))
{
SANITY_CHECK(m_max_data_packets_per_iteration > 1);
}
@@ -78,15 +80,14 @@ void *ConnectionSendThread::run()
{
assert(m_connection);
- LOG(dout_con << m_connection->getDesc() << "ConnectionSend thread started"
- << std::endl);
+ LOG(dout_con << m_connection->getDesc()
+ << "ConnectionSend thread started" << std::endl);
u64 curtime = porting::getTimeMs();
u64 lasttime = curtime;
PROFILE(std::stringstream ThreadIdentifier);
- PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc()
- << "]");
+ PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
/* if stop is requested don't stop immediately but try to send all */
/* packets first */
@@ -111,10 +112,8 @@ void *ConnectionSendThread::run()
runTimeouts(dtime);
if (m_iteration_packets_avaialble == 0) {
LOG(warningstream << m_connection->getDesc()
- << " Packet quota used up after re-sending "
- "packets, "
- << "max=" << m_max_data_packets_per_iteration
- << std::endl);
+ << " Packet quota used up after re-sending packets, "
+ << "max=" << m_max_data_packets_per_iteration << std::endl);
}
/* translate commands to packets */
@@ -166,6 +165,7 @@ bool ConnectionSendThread::packetsQueued()
}
}
+
return false;
}
@@ -185,20 +185,21 @@ void ConnectionSendThread::runTimeouts(float dtime)
continue;
PROFILE(std::stringstream peerIdentifier);
- PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc() << ";"
- << peerId << ";RELIABLE]");
- PROFILE(ScopeProfiler peerprofiler(
- g_profiler, peerIdentifier.str(), SPT_AVG));
+ PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
+ << ";" << peerId << ";RELIABLE]");
+ PROFILE(ScopeProfiler
+ peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
- SharedBuffer<u8> data(2); // data for sending ping, required here because
- // of goto
+ SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
/*
Check peer timeout
*/
if (peer->isTimedOut(m_timeout)) {
- infostream << m_connection->getDesc() << "RunTimeouts(): Peer "
- << peer->id << " has timed out." << std::endl;
+ infostream << m_connection->getDesc()
+ << "RunTimeouts(): Peer " << peer->id
+ << " has timed out."
+ << std::endl;
// Add peer to the list
timeouted_peers.push_back(peer->id);
// Don't bother going through the buffers of this one
@@ -211,8 +212,7 @@ void ConnectionSendThread::runTimeouts(float dtime)
std::list<BufferedPacket> timed_outs;
// Remove timed out incomplete unreliable split packets
- channel.incoming_splits.removeUnreliableTimedOuts(
- dtime, m_timeout);
+ channel.incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
// Increment reliable packet times
channel.outgoing_reliables_sent.incrementTimeouts(dtime);
@@ -223,9 +223,8 @@ void ConnectionSendThread::runTimeouts(float dtime)
return;
// Re-send timed out outgoing reliables
- timed_outs = channel.outgoing_reliables_sent.getTimedOuts(
- resend_timeout,
- (m_max_data_packets_per_iteration / numpeers));
+ timed_outs = channel.outgoing_reliables_sent.getTimedOuts(resend_timeout,
+ (m_max_data_packets_per_iteration / numpeers));
channel.UpdatePacketLossCounter(timed_outs.size());
g_profiler->graphAdd("packets_lost", timed_outs.size());
@@ -233,7 +232,7 @@ void ConnectionSendThread::runTimeouts(float dtime)
m_iteration_packets_avaialble -= timed_outs.size();
for (std::list<BufferedPacket>::iterator k = timed_outs.begin();
- k != timed_outs.end(); ++k) {
+ k != timed_outs.end(); ++k) {
session_t peer_id = readPeerId(*(k->data));
u8 channelnum = readChannel(*(k->data));
u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE + 1]));
@@ -244,28 +243,27 @@ void ConnectionSendThread::runTimeouts(float dtime)
if (k->resend_count > MAX_RELIABLE_RETRY) {
retry_count_exceeded = true;
timeouted_peers.push_back(peer->id);
- /* no need to check additional packets if a single
- * one did timeout*/
+ /* no need to check additional packets if a single one did timeout*/
break;
}
LOG(derr_con << m_connection->getDesc()
- << "RE-SENDING timed-out RELIABLE to "
- << k->address.serializeString()
- << "(t/o=" << resend_timeout << "): "
- << "from_peer_id=" << peer_id
- << ", channel=" << ((int)channelnum & 0xff)
- << ", seqnum=" << seqnum << std::endl);
+ << "RE-SENDING timed-out RELIABLE to "
+ << k->address.serializeString()
+ << "(t/o=" << resend_timeout << "): "
+ << "from_peer_id=" << peer_id
+ << ", channel=" << ((int) channelnum & 0xff)
+ << ", seqnum=" << seqnum
+ << std::endl);
rawSend(*k);
- // do not handle rtt here as we can't decide if this
- // packet was lost or really takes more time to transmit
+ // do not handle rtt here as we can't decide if this packet was
+ // lost or really takes more time to transmit
}
if (retry_count_exceeded) {
- break; /* no need to check other channels if we already
- did timeout */
+ break; /* no need to check other channels if we already did timeout */
}
channel.UpdateTimers(dtime);
@@ -278,23 +276,23 @@ void ConnectionSendThread::runTimeouts(float dtime)
/* send ping if necessary */
if (udpPeer->Ping(dtime, data)) {
LOG(dout_con << m_connection->getDesc()
- << "Sending ping for peer_id: " << udpPeer->id
- << std::endl);
+ << "Sending ping for peer_id: " << udpPeer->id << std::endl);
/* this may fail if there ain't a sequence number left */
if (!rawSendAsPacket(udpPeer->id, 0, data, true)) {
- // retrigger with reduced ping interval
+ //retrigger with reduced ping interval
udpPeer->Ping(4.0, data);
}
}
- udpPeer->RunCommandQueues(m_max_packet_size, m_max_commands_per_iteration,
- m_max_packets_requeued);
+ udpPeer->RunCommandQueues(m_max_packet_size,
+ m_max_commands_per_iteration,
+ m_max_packets_requeued);
}
// Remove timed out peers
for (u16 timeouted_peer : timeouted_peers) {
- LOG(dout_con << m_connection->getDesc() << "RunTimeouts(): Removing peer "
- << timeouted_peer << std::endl);
+ LOG(dout_con << m_connection->getDesc()
+ << "RunTimeouts(): Removing peer " << timeouted_peer << std::endl);
m_connection->deletePeer(timeouted_peer, true);
}
}
@@ -302,14 +300,15 @@ void ConnectionSendThread::runTimeouts(float dtime)
void ConnectionSendThread::rawSend(const BufferedPacket &packet)
{
try {
- m_connection->m_udpSocket.Send(
- packet.address, *packet.data, packet.data.getSize());
- LOG(dout_con << m_connection->getDesc() << " rawSend: "
- << packet.data.getSize() << " bytes sent" << std::endl);
+ m_connection->m_udpSocket.Send(packet.address, *packet.data,
+ packet.data.getSize());
+ LOG(dout_con << m_connection->getDesc()
+ << " rawSend: " << packet.data.getSize()
+ << " bytes sent" << std::endl);
} catch (SendFailedException &e) {
LOG(derr_con << m_connection->getDesc()
- << "Connection::rawSend(): SendFailedException: "
- << packet.address.serializeString() << std::endl);
+ << "Connection::rawSend(): SendFailedException: "
+ << packet.address.serializeString() << std::endl);
}
}
@@ -318,14 +317,14 @@ void ConnectionSendThread::sendAsPacketReliable(BufferedPacket &p, Channel *chan
try {
p.absolute_send_time = porting::getTimeMs();
// Buffer the packet
- channel->outgoing_reliables_sent.insert(
- p, (channel->readOutgoingSequenceNumber() -
- MAX_RELIABLE_WINDOW_SIZE) %
- (MAX_RELIABLE_WINDOW_SIZE + 1));
- } catch (AlreadyExistsException &e) {
+ channel->outgoing_reliables_sent.insert(p,
+ (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
+ % (MAX_RELIABLE_WINDOW_SIZE + 1));
+ }
+ catch (AlreadyExistsException &e) {
LOG(derr_con << m_connection->getDesc()
- << "WARNING: Going to send a reliable packet"
- << " in outgoing buffer" << std::endl);
+ << "WARNING: Going to send a reliable packet"
+ << " in outgoing buffer" << std::endl);
}
// Send the packet
@@ -333,22 +332,21 @@ void ConnectionSendThread::sendAsPacketReliable(BufferedPacket &p, Channel *chan
}
bool ConnectionSendThread::rawSendAsPacket(session_t peer_id, u8 channelnum,
- const SharedBuffer<u8> &data, bool reliable)
+ const SharedBuffer<u8> &data, bool reliable)
{
PeerHelper peer = m_connection->getPeerNoEx(peer_id);
if (!peer) {
- LOG(errorstream << m_connection->getDesc() << " dropped "
- << (reliable ? "reliable " : "")
- << "packet for non existent peer_id: " << peer_id
- << std::endl);
+ LOG(errorstream << m_connection->getDesc()
+ << " dropped " << (reliable ? "reliable " : "")
+ << "packet for non existent peer_id: " << peer_id << std::endl);
return false;
}
Channel *channel = &(dynamic_cast<UDPPeer *>(&peer)->channels[channelnum]);
if (reliable) {
bool have_sequence_number_for_raw_packet = true;
- u16 seqnum = channel->getOutgoingSequenceNumber(
- have_sequence_number_for_raw_packet);
+ u16 seqnum =
+ channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
if (!have_sequence_number_for_raw_packet)
return false;
@@ -359,23 +357,24 @@ bool ConnectionSendThread::rawSendAsPacket(session_t peer_id, u8 channelnum,
// Add base headers and make a packet
BufferedPacket p = con::makePacket(peer_address, reliable,
- m_connection->GetProtocolID(), m_connection->GetPeerID(),
- channelnum);
+ m_connection->GetProtocolID(), m_connection->GetPeerID(),
+ channelnum);
// first check if our send window is already maxed out
- if (channel->outgoing_reliables_sent.size() < channel->getWindowSize()) {
+ if (channel->outgoing_reliables_sent.size()
+ < channel->getWindowSize()) {
LOG(dout_con << m_connection->getDesc()
- << " INFO: sending a reliable packet to peer_id "
- << peer_id << " channel: " << (u32)channelnum
- << " seqnum: " << seqnum << std::endl);
+ << " INFO: sending a reliable packet to peer_id " << peer_id
+ << " channel: " << (u32)channelnum
+ << " seqnum: " << seqnum << std::endl);
sendAsPacketReliable(p, channel);
return true;
}
LOG(dout_con << m_connection->getDesc()
- << " INFO: queueing reliable packet for peer_id: " << peer_id
- << " channel: " << (u32)channelnum << " seqnum: " << seqnum
- << std::endl);
+ << " INFO: queueing reliable packet for peer_id: " << peer_id
+ << " channel: " << (u32)channelnum
+ << " seqnum: " << seqnum << std::endl);
channel->queued_reliables.push(p);
return false;
}
@@ -384,8 +383,8 @@ bool ConnectionSendThread::rawSendAsPacket(session_t peer_id, u8 channelnum,
if (peer->getAddress(MTP_UDP, peer_address)) {
// Add base headers and make a packet
BufferedPacket p = con::makePacket(peer_address, data,
- m_connection->GetProtocolID(), m_connection->GetPeerID(),
- channelnum);
+ m_connection->GetProtocolID(), m_connection->GetPeerID(),
+ channelnum);
// Send the packet
rawSend(p);
@@ -393,116 +392,116 @@ bool ConnectionSendThread::rawSendAsPacket(session_t peer_id, u8 channelnum,
}
LOG(dout_con << m_connection->getDesc()
- << " INFO: dropped unreliable packet for peer_id: " << peer_id
- << " because of (yet) missing udp address" << std::endl);
+ << " INFO: dropped unreliable packet for peer_id: " << peer_id
+ << " because of (yet) missing udp address" << std::endl);
return false;
}
void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
{
- assert(c.reliable); // Pre-condition
+ assert(c.reliable); // Pre-condition
switch (c.type) {
- case CONNCMD_NONE:
- LOG(dout_con << m_connection->getDesc()
- << "UDP processing reliable CONNCMD_NONE" << std::endl);
- return;
+ case CONNCMD_NONE:
+ LOG(dout_con << m_connection->getDesc()
+ << "UDP processing reliable CONNCMD_NONE" << std::endl);
+ return;
- case CONNCMD_SEND:
- LOG(dout_con << m_connection->getDesc()
- << "UDP processing reliable CONNCMD_SEND" << std::endl);
- sendReliable(c);
- return;
+ case CONNCMD_SEND:
+ LOG(dout_con << m_connection->getDesc()
+ << "UDP processing reliable CONNCMD_SEND" << std::endl);
+ sendReliable(c);
+ return;
- case CONNCMD_SEND_TO_ALL:
- LOG(dout_con << m_connection->getDesc()
- << "UDP processing CONNCMD_SEND_TO_ALL" << std::endl);
- sendToAllReliable(c);
- return;
+ case CONNCMD_SEND_TO_ALL:
+ LOG(dout_con << m_connection->getDesc()
+ << "UDP processing CONNCMD_SEND_TO_ALL" << std::endl);
+ sendToAllReliable(c);
+ return;
- case CONCMD_CREATE_PEER:
- LOG(dout_con << m_connection->getDesc()
- << "UDP processing reliable CONCMD_CREATE_PEER"
- << std::endl);
- if (!rawSendAsPacket(c.peer_id, c.channelnum, c.data, c.reliable)) {
- /* put to queue if we couldn't send it immediately */
- sendReliable(c);
- }
- return;
+ case CONCMD_CREATE_PEER:
+ LOG(dout_con << m_connection->getDesc()
+ << "UDP processing reliable CONCMD_CREATE_PEER" << std::endl);
+ if (!rawSendAsPacket(c.peer_id, c.channelnum, c.data, c.reliable)) {
+ /* put to queue if we couldn't send it immediately */
+ sendReliable(c);
+ }
+ return;
- case CONNCMD_SERVE:
- case CONNCMD_CONNECT:
- case CONNCMD_DISCONNECT:
- case CONCMD_ACK:
- FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
- default:
- LOG(dout_con << m_connection->getDesc()
- << " Invalid reliable command type: " << c.type
- << std::endl);
+ case CONNCMD_SERVE:
+ case CONNCMD_CONNECT:
+ case CONNCMD_DISCONNECT:
+ case CONCMD_ACK:
+ FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
+ default:
+ LOG(dout_con << m_connection->getDesc()
+ << " Invalid reliable command type: " << c.type << std::endl);
}
}
+
void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
{
assert(!c.reliable); // Pre-condition
switch (c.type) {
- case CONNCMD_NONE:
- LOG(dout_con << m_connection->getDesc() << " UDP processing CONNCMD_NONE"
- << std::endl);
- return;
- case CONNCMD_SERVE:
- LOG(dout_con << m_connection->getDesc()
- << " UDP processing CONNCMD_SERVE port="
- << c.address.serializeString() << std::endl);
- serve(c.address);
- return;
- case CONNCMD_CONNECT:
- LOG(dout_con << m_connection->getDesc()
- << " UDP processing CONNCMD_CONNECT" << std::endl);
- connect(c.address);
- return;
- case CONNCMD_DISCONNECT:
- LOG(dout_con << m_connection->getDesc()
- << " UDP processing CONNCMD_DISCONNECT" << std::endl);
- disconnect();
- return;
- case CONNCMD_DISCONNECT_PEER:
- LOG(dout_con << m_connection->getDesc()
- << " UDP processing CONNCMD_DISCONNECT_PEER" << std::endl);
- disconnect_peer(c.peer_id);
- return;
- case CONNCMD_SEND:
- LOG(dout_con << m_connection->getDesc() << " UDP processing CONNCMD_SEND"
- << std::endl);
- send(c.peer_id, c.channelnum, c.data);
- return;
- case CONNCMD_SEND_TO_ALL:
- LOG(dout_con << m_connection->getDesc()
- << " UDP processing CONNCMD_SEND_TO_ALL" << std::endl);
- sendToAll(c.channelnum, c.data);
- return;
- case CONCMD_ACK:
- LOG(dout_con << m_connection->getDesc() << " UDP processing CONCMD_ACK"
- << std::endl);
- sendAsPacket(c.peer_id, c.channelnum, c.data, true);
- return;
- case CONCMD_CREATE_PEER:
- FATAL_ERROR("Got command that should be reliable as unreliable command");
- default:
- LOG(dout_con << m_connection->getDesc()
- << " Invalid command type: " << c.type << std::endl);
+ case CONNCMD_NONE:
+ LOG(dout_con << m_connection->getDesc()
+ << " UDP processing CONNCMD_NONE" << std::endl);
+ return;
+ case CONNCMD_SERVE:
+ LOG(dout_con << m_connection->getDesc()
+ << " UDP processing CONNCMD_SERVE port="
+ << c.address.serializeString() << std::endl);
+ serve(c.address);
+ return;
+ case CONNCMD_CONNECT:
+ LOG(dout_con << m_connection->getDesc()
+ << " UDP processing CONNCMD_CONNECT" << std::endl);
+ connect(c.address);
+ return;
+ case CONNCMD_DISCONNECT:
+ LOG(dout_con << m_connection->getDesc()
+ << " UDP processing CONNCMD_DISCONNECT" << std::endl);
+ disconnect();
+ return;
+ case CONNCMD_DISCONNECT_PEER:
+ LOG(dout_con << m_connection->getDesc()
+ << " UDP processing CONNCMD_DISCONNECT_PEER" << std::endl);
+ disconnect_peer(c.peer_id);
+ return;
+ case CONNCMD_SEND:
+ LOG(dout_con << m_connection->getDesc()
+ << " UDP processing CONNCMD_SEND" << std::endl);
+ send(c.peer_id, c.channelnum, c.data);
+ return;
+ case CONNCMD_SEND_TO_ALL:
+ LOG(dout_con << m_connection->getDesc()
+ << " UDP processing CONNCMD_SEND_TO_ALL" << std::endl);
+ sendToAll(c.channelnum, c.data);
+ return;
+ case CONCMD_ACK:
+ LOG(dout_con << m_connection->getDesc()
+ << " UDP processing CONCMD_ACK" << std::endl);
+ sendAsPacket(c.peer_id, c.channelnum, c.data, true);
+ return;
+ case CONCMD_CREATE_PEER:
+ FATAL_ERROR("Got command that should be reliable as unreliable command");
+ default:
+ LOG(dout_con << m_connection->getDesc()
+ << " Invalid command type: " << c.type << std::endl);
}
}
void ConnectionSendThread::serve(Address bind_address)
{
- LOG(dout_con << m_connection->getDesc() << "UDP serving at port "
- << bind_address.serializeString() << std::endl);
+ LOG(dout_con << m_connection->getDesc()
+ << "UDP serving at port " << bind_address.serializeString() << std::endl);
try {
m_connection->m_udpSocket.Bind(bind_address);
m_connection->SetPeerID(PEER_ID_SERVER);
- } catch (SocketException &e) {
+ }
+ catch (SocketException &e) {
// Create event
ConnectionEvent ce;
ce.bindFailed();
@@ -513,8 +512,8 @@ void ConnectionSendThread::serve(Address bind_address)
void ConnectionSendThread::connect(Address address)
{
LOG(dout_con << m_connection->getDesc() << " connecting to "
- << address.serializeString() << ":" << address.getPort()
- << std::endl);
+ << address.serializeString()
+ << ":" << address.getPort() << std::endl);
UDPPeer *peer = m_connection->createServerPeer(address);
@@ -526,7 +525,7 @@ void ConnectionSendThread::connect(Address address)
Address bind_addr;
if (address.isIPv6())
- bind_addr.setAddress((IPv6AddressBytes *)NULL);
+ bind_addr.setAddress((IPv6AddressBytes *) NULL);
else
bind_addr.setAddress(0, 0, 0, 0);
@@ -547,6 +546,7 @@ void ConnectionSendThread::disconnect()
writeU8(&data[0], PACKET_TYPE_CONTROL);
writeU8(&data[1], CONTROLTYPE_DISCO);
+
// Send to all
std::list<session_t> peerids = m_connection->getPeerIDs();
@@ -577,23 +577,23 @@ void ConnectionSendThread::disconnect_peer(session_t peer_id)
dynamic_cast<UDPPeer *>(&peer)->m_pending_disconnect = true;
}
-void ConnectionSendThread::send(
- session_t peer_id, u8 channelnum, const SharedBuffer<u8> &data)
+void ConnectionSendThread::send(session_t peer_id, u8 channelnum,
+ const SharedBuffer<u8> &data)
{
assert(channelnum < CHANNEL_COUNT); // Pre-condition
PeerHelper peer = m_connection->getPeerNoEx(peer_id);
if (!peer) {
LOG(dout_con << m_connection->getDesc() << " peer: peer_id=" << peer_id
- << ">>>NOT<<< found on sending packet"
- << ", channel " << (channelnum % 0xFF)
- << ", size: " << data.getSize() << std::endl);
+ << ">>>NOT<<< found on sending packet"
+ << ", channel " << (channelnum % 0xFF)
+ << ", size: " << data.getSize() << std::endl);
return;
}
LOG(dout_con << m_connection->getDesc() << " sending to peer_id=" << peer_id
- << ", channel " << (channelnum % 0xFF)
- << ", size: " << data.getSize() << std::endl);
+ << ", channel " << (channelnum % 0xFF)
+ << ", size: " << data.getSize() << std::endl);
u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
@@ -647,16 +647,16 @@ void ConnectionSendThread::sendPackets(float dtime)
std::list<session_t> pendingDisconnect;
std::map<session_t, bool> pending_unreliable;
- const unsigned int peer_packet_quota =
- m_iteration_packets_avaialble / MYMAX(peerIds.size(), 1);
+ const unsigned int peer_packet_quota = m_iteration_packets_avaialble
+ / MYMAX(peerIds.size(), 1);
for (session_t peerId : peerIds) {
PeerHelper peer = m_connection->getPeerNoEx(peerId);
- // peer may have been removed
+ //peer may have been removed
if (!peer) {
- LOG(dout_con << m_connection->getDesc()
- << " Peer not found: peer_id=" << peerId
- << std::endl);
+ LOG(dout_con << m_connection->getDesc() << " Peer not found: peer_id="
+ << peerId
+ << std::endl);
continue;
}
peer->m_increment_packets_remaining = peer_packet_quota;
@@ -671,16 +671,17 @@ void ConnectionSendThread::sendPackets(float dtime)
pendingDisconnect.push_back(peerId);
}
- PROFILE(std::stringstream peerIdentifier);
- PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";"
- << peerId << ";RELIABLE]");
- PROFILE(ScopeProfiler peerprofiler(
- g_profiler, peerIdentifier.str(), SPT_AVG));
+ PROFILE(std::stringstream
+ peerIdentifier);
+ PROFILE(
+ peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << peerId
+ << ";RELIABLE]");
+ PROFILE(ScopeProfiler
+ peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
LOG(dout_con << m_connection->getDesc()
- << " Handle per peer queues: peer_id=" << peerId
- << " packet quota: " << peer->m_increment_packets_remaining
- << std::endl);
+ << " Handle per peer queues: peer_id=" << peerId
+ << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
// first send queued reliable packets for all peers (if possible)
for (unsigned int i = 0; i < CHANNEL_COUNT; i++) {
@@ -691,34 +692,38 @@ void ConnectionSendThread::sendPackets(float dtime)
u16 next_to_receive = 0;
channel.incoming_reliables.getFirstSeqnum(next_to_receive);
- LOG(dout_con << m_connection->getDesc() << "\t channel: " << i
- << ", peer quota:"
- << peer->m_increment_packets_remaining << std::endl
- << "\t\t\treliables on wire: "
- << channel.outgoing_reliables_sent.size()
- << ", waiting for ack for " << next_to_ack
- << std::endl
- << "\t\t\tincoming_reliables: "
- << channel.incoming_reliables.size()
- << ", next reliable packet: "
- << channel.readNextIncomingSeqNum()
- << ", next queued: " << next_to_receive << std::endl
- << "\t\t\treliables queued : "
- << channel.queued_reliables.size() << std::endl
- << "\t\t\tqueued commands : "
- << channel.queued_commands.size() << std::endl);
+ LOG(dout_con << m_connection->getDesc() << "\t channel: "
+ << i << ", peer quota:"
+ << peer->m_increment_packets_remaining
+ << std::endl
+ << "\t\t\treliables on wire: "
+ << channel.outgoing_reliables_sent.size()
+ << ", waiting for ack for " << next_to_ack
+ << std::endl
+ << "\t\t\tincoming_reliables: "
+ << channel.incoming_reliables.size()
+ << ", next reliable packet: "
+ << channel.readNextIncomingSeqNum()
+ << ", next queued: " << next_to_receive
+ << std::endl
+ << "\t\t\treliables queued : "
+ << channel.queued_reliables.size()
+ << std::endl
+ << "\t\t\tqueued commands : "
+ << channel.queued_commands.size()
+ << std::endl);
while (!channel.queued_reliables.empty() &&
- channel.outgoing_reliables_sent.size() <
- channel.getWindowSize() &&
+ channel.outgoing_reliables_sent.size()
+ < channel.getWindowSize() &&
peer->m_increment_packets_remaining > 0) {
BufferedPacket p = channel.queued_reliables.front();
channel.queued_reliables.pop();
LOG(dout_con << m_connection->getDesc()
- << " INFO: sending a queued reliable packet "
- << " channel: " << i << ", seqnum: "
- << readU16(&p.data[BASE_HEADER_SIZE + 1])
- << std::endl);
+ << " INFO: sending a queued reliable packet "
+ << " channel: " << i
+ << ", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE + 1])
+ << std::endl);
sendAsPacketReliable(p, &channel);
peer->m_increment_packets_remaining--;
}
@@ -726,8 +731,9 @@ void ConnectionSendThread::sendPackets(float dtime)
}
if (!m_outgoing_queue.empty()) {
- LOG(dout_con << m_connection->getDesc() << " Handle non reliable queue ("
- << m_outgoing_queue.size() << " pkts)" << std::endl);
+ LOG(dout_con << m_connection->getDesc()
+ << " Handle non reliable queue ("
+ << m_outgoing_queue.size() << " pkts)" << std::endl);
}
unsigned int initial_queuesize = m_outgoing_queue.size();
@@ -742,18 +748,17 @@ void ConnectionSendThread::sendPackets(float dtime)
PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
if (!peer) {
LOG(dout_con << m_connection->getDesc()
- << " Outgoing queue: peer_id=" << packet.peer_id
- << ">>>NOT<<< found on sending packet"
- << ", channel " << (packet.channelnum % 0xFF)
- << ", size: " << packet.data.getSize() << std::endl);
+ << " Outgoing queue: peer_id=" << packet.peer_id
+ << ">>>NOT<<< found on sending packet"
+ << ", channel " << (packet.channelnum % 0xFF)
+ << ", size: " << packet.data.getSize() << std::endl);
continue;
}
/* send acks immediately */
- if (packet.ack || peer->m_increment_packets_remaining > 0 ||
- stopRequested()) {
- rawSendAsPacket(packet.peer_id, packet.channelnum, packet.data,
- packet.reliable);
+ if (packet.ack || peer->m_increment_packets_remaining > 0 || stopRequested()) {
+ rawSendAsPacket(packet.peer_id, packet.channelnum,
+ packet.data, packet.reliable);
if (peer->m_increment_packets_remaining > 0)
peer->m_increment_packets_remaining--;
} else {
@@ -769,10 +774,8 @@ void ConnectionSendThread::sendPackets(float dtime)
continue;
if (peer->m_increment_packets_remaining == 0) {
LOG(warningstream << m_connection->getDesc()
- << " Packet quota used up for peer_id="
- << peerId << ", was "
- << peer_packet_quota << " pkts"
- << std::endl);
+ << " Packet quota used up for peer_id=" << peerId
+ << ", was " << peer_packet_quota << " pkts" << std::endl);
}
}
}
@@ -784,15 +787,15 @@ void ConnectionSendThread::sendPackets(float dtime)
}
}
-void ConnectionSendThread::sendAsPacket(
- session_t peer_id, u8 channelnum, const SharedBuffer<u8> &data, bool ack)
+void ConnectionSendThread::sendAsPacket(session_t peer_id, u8 channelnum,
+ const SharedBuffer<u8> &data, bool ack)
{
OutgoingPacket packet(peer_id, channelnum, data, false, ack);
m_outgoing_queue.push(packet);
}
ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
- Thread("ConnectionReceive")
+ Thread("ConnectionReceive")
{
}
@@ -800,12 +803,12 @@ void *ConnectionReceiveThread::run()
{
assert(m_connection);
- LOG(dout_con << m_connection->getDesc() << "ConnectionReceive thread started"
- << std::endl);
+ LOG(dout_con << m_connection->getDesc()
+ << "ConnectionReceive thread started" << std::endl);
- PROFILE(std::stringstream ThreadIdentifier);
- PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc()
- << "]");
+ PROFILE(std::stringstream
+ ThreadIdentifier);
+ PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
// use IPv6 minimum allowed MTU as receive buffer size as this is
// theoretical reliable upper boundary of a udp packet for all IPv6 enabled
@@ -823,12 +826,13 @@ void *ConnectionReceiveThread::run()
while (!stopRequested()) {
BEGIN_DEBUG_EXCEPTION_HANDLER
- PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
+ PROFILE(ScopeProfiler
+ sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
#ifdef DEBUG_CONNECTION_KBPS
lasttime = curtime;
curtime = porting::getTimeMs();
- float dtime = CALC_DTIME(lasttime, curtime);
+ float dtime = CALC_DTIME(lasttime,curtime);
#endif
/* receive packets */
@@ -842,7 +846,9 @@ void *ConnectionReceiveThread::run()
std::list<session_t> peerids = m_connection->getPeerIDs();
for (std::list<session_t>::iterator i = peerids.begin();
- i != peerids.end(); i++) {
+ i != peerids.end();
+ i++)
+ {
PeerHelper peer = m_connection->getPeerNoEx(*i);
if (!peer)
continue;
@@ -852,52 +858,35 @@ void *ConnectionReceiveThread::run()
float avg_rate = 0.0;
float avg_loss = 0.0;
- for (u16 j = 0; j < CHANNEL_COUNT; j++) {
- peer_current += peer->channels[j]
- .getCurrentDownloadRateKB();
- peer_loss += peer->channels[j]
- .getCurrentLossRateKB();
- avg_rate += peer->channels[j]
- .getAvgDownloadRateKB();
+ for(u16 j=0; j<CHANNEL_COUNT; j++)
+ {
+ peer_current +=peer->channels[j].getCurrentDownloadRateKB();
+ peer_loss += peer->channels[j].getCurrentLossRateKB();
+ avg_rate += peer->channels[j].getAvgDownloadRateKB();
avg_loss += peer->channels[j].getAvgLossRateKB();
}
std::stringstream output;
output << std::fixed << std::setprecision(1);
- output << "OUT to Peer " << *i << " RATES (good / loss) "
- << std::endl;
- output << "\tcurrent (sum): " << peer_current << "kb/s "
- << peer_loss << "kb/s" << std::endl;
- output << "\taverage (sum): " << avg_rate << "kb/s "
- << avg_loss << "kb/s" << std::endl;
+ output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
+ output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
+ output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
output << std::setfill(' ');
- for (u16 j = 0; j < CHANNEL_COUNT; j++) {
+ for(u16 j=0; j<CHANNEL_COUNT; j++)
+ {
output << "\tcha " << j << ":"
- << " CUR: " << std::setw(6)
- << peer->channels[j].getCurrentDownloadRateKB()
- << "kb/s"
- << " AVG: " << std::setw(6)
- << peer->channels[j].getAvgDownloadRateKB()
- << "kb/s"
- << " MAX: " << std::setw(6)
- << peer->channels[j].getMaxDownloadRateKB()
- << "kb/s"
- << " /"
- << " CUR: " << std::setw(6)
- << peer->channels[j].getCurrentLossRateKB()
- << "kb/s"
- << " AVG: " << std::setw(6)
- << peer->channels[j].getAvgLossRateKB()
- << "kb/s"
- << " MAX: " << std::setw(6)
- << peer->channels[j].getMaxLossRateKB()
- << "kb/s"
- << " / WS: "
- << peer->channels[j].getWindowSize()
- << std::endl;
+ << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
+ << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
+ << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
+ << " /"
+ << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
+ << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
+ << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
+ << " / WS: " << peer->channels[j].getWindowSize()
+ << std::endl;
}
- fprintf(stderr, "%s\n", output.str().c_str());
+ fprintf(stderr,"%s\n",output.str().c_str());
}
}
#endif
@@ -909,7 +898,8 @@ void *ConnectionReceiveThread::run()
}
// Receive packets from the network and buffers and create ConnectionEvents
-void ConnectionReceiveThread::receive(SharedBuffer<u8> &packetdata, bool &packet_queued)
+void ConnectionReceiveThread::receive(SharedBuffer<u8> &packetdata,
+ bool &packet_queued)
{
try {
// First, see if there any buffered packets we can process now
@@ -925,7 +915,8 @@ void ConnectionReceiveThread::receive(SharedBuffer<u8> &packetdata, bool &packet
e.dataReceived(peer_id, resultdata);
m_connection->putEvent(e);
}
- } catch (ProcessedSilentlyException &e) {
+ }
+ catch (ProcessedSilentlyException &e) {
/* try reading again */
}
}
@@ -934,20 +925,19 @@ void ConnectionReceiveThread::receive(SharedBuffer<u8> &packetdata, bool &packet
// Call Receive() to wait for incoming data
Address sender;
- s32 received_size = m_connection->m_udpSocket.Receive(
- sender, *packetdata, packetdata.getSize());
+ s32 received_size = m_connection->m_udpSocket.Receive(sender,
+ *packetdata, packetdata.getSize());
if (received_size < 0)
return;
if ((received_size < BASE_HEADER_SIZE) ||
- (readU32(&packetdata[0]) !=
- m_connection->GetProtocolID())) {
+ (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);
+ << "Receive(): Invalid incoming packet, "
+ << "size: " << received_size
+ << ", protocol: "
+ << ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
+ << std::endl);
return;
}
@@ -956,8 +946,7 @@ void ConnectionReceiveThread::receive(SharedBuffer<u8> &packetdata, bool &packet
if (channelnum > CHANNEL_COUNT - 1) {
LOG(derr_con << m_connection->getDesc()
- << "Receive(): Invalid channel " << (u32)channelnum
- << std::endl);
+ << "Receive(): Invalid channel " << (u32)channelnum << std::endl);
return;
}
@@ -971,15 +960,14 @@ void ConnectionReceiveThread::receive(SharedBuffer<u8> &packetdata, bool &packet
/* 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);
+ 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);
+ << " got packet from unknown peer_id: "
+ << peer_id << " Ignoring." << std::endl);
return;
}
@@ -988,18 +976,15 @@ void ConnectionReceiveThread::receive(SharedBuffer<u8> &packetdata, bool &packet
Address peer_address;
if (peer->getAddress(MTP_UDP, peer_address)) {
if (peer_address != sender) {
- LOG(derr_con << m_connection->getDesc() << " Peer "
- << peer_id
- << " sending from different address."
- " Ignoring."
- << std::endl);
+ LOG(derr_con << m_connection->getDesc()
+ << " Peer " << peer_id << " sending from different address."
+ " Ignoring." << std::endl);
return;
}
} else {
- LOG(derr_con << m_connection->getDesc() << " Peer " << peer_id
- << " doesn't have an address?!"
- " Ignoring."
- << std::endl);
+ LOG(derr_con << m_connection->getDesc()
+ << " Peer " << peer_id << " doesn't have an address?!"
+ " Ignoring." << std::endl);
return;
}
@@ -1010,10 +995,8 @@ void ConnectionReceiveThread::receive(SharedBuffer<u8> &packetdata, bool &packet
channel = &dynamic_cast<UDPPeer *>(&peer)->channels[channelnum];
} else {
LOG(derr_con << m_connection->getDesc()
- << "Receive(): peer_id=" << peer_id
- << " isn't an UDPPeer?!"
- " Ignoring."
- << std::endl);
+ << "Receive(): peer_id=" << peer_id << " isn't an UDPPeer?!"
+ " Ignoring." << std::endl);
return;
}
@@ -1024,30 +1007,33 @@ void ConnectionReceiveThread::receive(SharedBuffer<u8> &packetdata, bool &packet
// 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());
+ 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);
+ SharedBuffer<u8> resultdata = processPacket
+ (channel, strippeddata, peer_id, channelnum, false);
LOG(dout_con << m_connection->getDesc()
- << " ProcessPacket from peer_id: " << peer_id
- << ", channel: " << (u32)channelnum << ", returned "
- << resultdata.getSize() << " bytes" << std::endl);
+ << " ProcessPacket from peer_id: " << peer_id
+ << ", channel: " << (u32)channelnum << ", returned "
+ << resultdata.getSize() << " bytes" << std::endl);
ConnectionEvent e;
e.dataReceived(peer_id, resultdata);
m_connection->putEvent(e);
- } catch (ProcessedSilentlyException &e) {
- } catch (ProcessedQueued &e) {
+ }
+ catch (ProcessedSilentlyException &e) {
+ }
+ catch (ProcessedQueued &e) {
// we set it to true anyway (see below)
}
/* Every time we receive a packet it can happen that a previously
* buffered packet is now ready to process. */
packet_queued = true;
- } catch (InvalidIncomingDataException &e) {
+ }
+ catch (InvalidIncomingDataException &e) {
}
}
@@ -1072,8 +1058,8 @@ bool ConnectionReceiveThread::getFromBuffers(session_t &peer_id, SharedBuffer<u8
return false;
}
-bool ConnectionReceiveThread::checkIncomingBuffers(
- Channel *channel, session_t &peer_id, SharedBuffer<u8> &dst)
+bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
+ session_t &peer_id, SharedBuffer<u8> &dst)
{
u16 firstseqnum = 0;
if (channel->incoming_reliables.getFirstSeqnum(firstseqnum)) {
@@ -1084,10 +1070,11 @@ bool ConnectionReceiveThread::checkIncomingBuffers(
u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
LOG(dout_con << m_connection->getDesc()
- << "UNBUFFERING TYPE_RELIABLE"
- << " seqnum=" << seqnum << " peer_id=" << peer_id
- << " channel=" << ((int)channelnum & 0xff)
- << std::endl);
+ << "UNBUFFERING TYPE_RELIABLE"
+ << " seqnum=" << seqnum
+ << " peer_id=" << peer_id
+ << " channel=" << ((int) channelnum & 0xff)
+ << std::endl);
channel->incNextIncomingSeqNum();
@@ -1104,8 +1091,7 @@ bool ConnectionReceiveThread::checkIncomingBuffers(
}
SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
- const SharedBuffer<u8> &packetdata, session_t peer_id, u8 channelnum,
- bool reliable)
+ const SharedBuffer<u8> &packetdata, session_t peer_id, u8 channelnum, bool reliable)
{
PeerHelper peer = m_connection->getPeerNoEx(peer_id);
@@ -1126,8 +1112,8 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
}
if (type >= PACKET_TYPE_MAX) {
- derr_con << m_connection->getDesc()
- << "Got invalid type=" << ((int)type & 0xff) << std::endl;
+ derr_con << m_connection->getDesc() << "Got invalid type=" << ((int) type & 0xff)
+ << std::endl;
throw InvalidIncomingDataException("Invalid packet type");
}
@@ -1136,16 +1122,15 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
}
const ConnectionReceiveThread::PacketTypeHandler
- ConnectionReceiveThread::packetTypeRouter[PACKET_TYPE_MAX] = {
- {&ConnectionReceiveThread::handlePacketType_Control},
- {&ConnectionReceiveThread::handlePacketType_Original},
- {&ConnectionReceiveThread::handlePacketType_Split},
- {&ConnectionReceiveThread::handlePacketType_Reliable},
+ ConnectionReceiveThread::packetTypeRouter[PACKET_TYPE_MAX] = {
+ {&ConnectionReceiveThread::handlePacketType_Control},
+ {&ConnectionReceiveThread::handlePacketType_Original},
+ {&ConnectionReceiveThread::handlePacketType_Split},
+ {&ConnectionReceiveThread::handlePacketType_Reliable},
};
SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Control(Channel *channel,
- const SharedBuffer<u8> &packetdata, Peer *peer, u8 channelnum,
- bool reliable)
+ const SharedBuffer<u8> &packetdata, Peer *peer, u8 channelnum, bool reliable)
{
if (packetdata.getSize() < 2)
throw InvalidIncomingDataException("packetdata.getSize() < 2");
@@ -1157,29 +1142,26 @@ SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Control(Channel *chan
if (packetdata.getSize() < 4) {
throw InvalidIncomingDataException(
- "packetdata.getSize() < 4 (ACK header size)");
+ "packetdata.getSize() < 4 (ACK header size)");
}
u16 seqnum = readU16(&packetdata[2]);
- LOG(dout_con << m_connection->getDesc()
- << " [ CONTROLTYPE_ACK: channelnum="
- << ((int)channelnum & 0xff) << ", peer_id=" << peer->id
- << ", seqnum=" << seqnum << " ]" << std::endl);
+ LOG(dout_con << m_connection->getDesc() << " [ CONTROLTYPE_ACK: channelnum="
+ << ((int) channelnum & 0xff) << ", peer_id=" << peer->id << ", seqnum="
+ << seqnum << " ]" << std::endl);
try {
- BufferedPacket p = channel->outgoing_reliables_sent.popSeqnum(
- seqnum);
+ BufferedPacket p = channel->outgoing_reliables_sent.popSeqnum(seqnum);
// only calculate rtt from straight sent packets
if (p.resend_count == 0) {
// Get round trip time
u64 current_time = porting::getTimeMs();
- // a overflow is quite unlikely but as it'd result in
- // major rtt miscalculation we handle it here
+ // a overflow is quite unlikely but as it'd result in major
+ // rtt miscalculation we handle it here
if (current_time > p.absolute_send_time) {
- float rtt = (current_time - p.absolute_send_time) /
- 1000.0;
+ float rtt = (current_time - p.absolute_send_time) / 1000.0;
// Let peer calculate stuff according to it
// (avg_rtt and resend_timeout)
@@ -1198,8 +1180,8 @@ SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Control(Channel *chan
m_connection->TriggerSend();
} catch (NotFoundException &e) {
LOG(derr_con << m_connection->getDesc()
- << "WARNING: ACKed packet not in outgoing queue"
- << " seqnum=" << seqnum << std::endl);
+ << "WARNING: ACKed packet not in outgoing queue"
+ << " seqnum=" << seqnum << std::endl);
channel->UpdatePacketTooLateCounter();
}
@@ -1207,19 +1189,18 @@ SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Control(Channel *chan
} else if (controltype == CONTROLTYPE_SET_PEER_ID) {
// Got a packet to set our peer id
if (packetdata.getSize() < 4)
- throw InvalidIncomingDataException("packetdata.getSize() < 4 "
- "(SET_PEER_ID header size)");
+ throw InvalidIncomingDataException
+ ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
session_t peer_id_new = readU16(&packetdata[2]);
- LOG(dout_con << m_connection->getDesc() << "Got new peer id: "
- << peer_id_new << "... " << std::endl);
+ LOG(dout_con << m_connection->getDesc() << "Got new peer id: " << peer_id_new
+ << "... " << std::endl);
if (m_connection->GetPeerID() != PEER_ID_INEXISTENT) {
LOG(derr_con << m_connection->getDesc()
- << "WARNING: Not changing existing peer id."
- << std::endl);
+ << "WARNING: Not changing existing peer id." << std::endl);
} else {
LOG(dout_con << m_connection->getDesc() << "changing own peer id"
- << std::endl);
+ << std::endl);
m_connection->SetPeerID(peer_id_new);
}
@@ -1233,31 +1214,29 @@ SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Control(Channel *chan
// Just ignore it, the incoming data already reset
// the timeout counter
LOG(dout_con << m_connection->getDesc() << "DISCO: Removing peer "
- << peer->id << std::endl);
+ << peer->id << std::endl);
if (!m_connection->deletePeer(peer->id, false)) {
- derr_con << m_connection->getDesc() << "DISCO: Peer not found"
- << std::endl;
+ derr_con << m_connection->getDesc() << "DISCO: Peer not found" << std::endl;
}
throw ProcessedSilentlyException("Got a DISCO");
} else {
LOG(derr_con << m_connection->getDesc()
- << "INVALID TYPE_CONTROL: invalid controltype="
- << ((int)controltype & 0xff) << std::endl);
+ << "INVALID TYPE_CONTROL: invalid controltype="
+ << ((int) controltype & 0xff) << std::endl);
throw InvalidIncomingDataException("Invalid control type");
}
}
SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Original(Channel *channel,
- const SharedBuffer<u8> &packetdata, Peer *peer, u8 channelnum,
- bool reliable)
+ const SharedBuffer<u8> &packetdata, Peer *peer, u8 channelnum, bool reliable)
{
if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
- throw InvalidIncomingDataException(
- "packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
+ throw InvalidIncomingDataException
+ ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
LOG(dout_con << m_connection->getDesc() << "RETURNING TYPE_ORIGINAL to user"
- << std::endl);
+ << std::endl);
// Get the inside packet out and return it
SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
@@ -1265,29 +1244,29 @@ SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Original(Channel *cha
}
SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Split(Channel *channel,
- const SharedBuffer<u8> &packetdata, Peer *peer, u8 channelnum,
- bool reliable)
+ const SharedBuffer<u8> &packetdata, Peer *peer, u8 channelnum, bool reliable)
{
Address peer_address;
if (peer->getAddress(MTP_UDP, peer_address)) {
// We have to create a packet again for buffering
// This isn't actually too bad an idea.
- BufferedPacket packet = makePacket(peer_address, packetdata,
- m_connection->GetProtocolID(), peer->id, channelnum);
+ BufferedPacket packet = makePacket(peer_address,
+ packetdata,
+ m_connection->GetProtocolID(),
+ peer->id,
+ channelnum);
// Buffer the packet
- SharedBuffer<u8> data =
- peer->addSplitPacket(channelnum, packet, reliable);
+ SharedBuffer<u8> data = peer->addSplitPacket(channelnum, packet, reliable);
if (data.getSize() != 0) {
LOG(dout_con << m_connection->getDesc()
- << "RETURNING TYPE_SPLIT: Constructed full data, "
- << "size=" << data.getSize() << std::endl);
+ << "RETURNING TYPE_SPLIT: Constructed full data, "
+ << "size=" << data.getSize() << std::endl);
return data;
}
- LOG(dout_con << m_connection->getDesc() << "BUFFERED TYPE_SPLIT"
- << std::endl);
+ LOG(dout_con << m_connection->getDesc() << "BUFFERED TYPE_SPLIT" << std::endl);
throw ProcessedSilentlyException("Buffered a split packet chunk");
}
@@ -1296,8 +1275,7 @@ SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Split(Channel *channe
}
SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Reliable(Channel *channel,
- const SharedBuffer<u8> &packetdata, Peer *peer, u8 channelnum,
- bool reliable)
+ const SharedBuffer<u8> &packetdata, Peer *peer, u8 channelnum, bool reliable)
{
assert(channel != NULL);
@@ -1306,44 +1284,41 @@ SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Reliable(Channel *cha
throw InvalidIncomingDataException("Found nested reliable packets");
if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
- throw InvalidIncomingDataException(
- "packetdata.getSize() < RELIABLE_HEADER_SIZE");
+ throw InvalidIncomingDataException("packetdata.getSize() < RELIABLE_HEADER_SIZE");
u16 seqnum = readU16(&packetdata[1]);
bool is_future_packet = false;
bool is_old_packet = false;
/* packet is within our receive window send ack */
- if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),
- MAX_RELIABLE_WINDOW_SIZE)) {
+ if (seqnum_in_window(seqnum,
+ channel->readNextIncomingSeqNum(), MAX_RELIABLE_WINDOW_SIZE)) {
m_connection->sendAck(peer->id, channelnum, seqnum);
} else {
- is_future_packet =
- seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
+ is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
/* packet is not within receive window, don't send ack. *
* if this was a valid packet it's gonna be retransmitted */
if (is_future_packet)
- throw ProcessedSilentlyException("Received packet newer then "
- "expected, not sending ack");
+ throw ProcessedSilentlyException(
+ "Received packet newer then expected, not sending ack");
/* seems like our ack was lost, send another one for a old packet */
if (is_old_packet) {
LOG(dout_con << m_connection->getDesc()
- << "RE-SENDING ACK: peer_id: " << peer->id
- << ", channel: " << (channelnum & 0xFF)
- << ", seqnum: " << seqnum << std::endl;)
+ << "RE-SENDING ACK: peer_id: " << peer->id
+ << ", channel: " << (channelnum & 0xFF)
+ << ", seqnum: " << seqnum << std::endl;)
m_connection->sendAck(peer->id, channelnum, seqnum);
// we already have this packet so this one was on wire at least
// the current timeout
- // we don't know how long this packet was on wire don't do silly
- // guessing dynamic_cast<UDPPeer*>(&peer)->
+ // we don't know how long this packet was on wire don't do silly guessing
+ // dynamic_cast<UDPPeer*>(&peer)->
// reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
- throw ProcessedSilentlyException(
- "Retransmitting ack for old packet");
+ throw ProcessedSilentlyException("Retransmitting ack for old packet");
}
}
@@ -1355,16 +1330,19 @@ SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Reliable(Channel *cha
// This one comes later, buffer it.
// Actually we have to make a packet to buffer one.
// Well, we have all the ingredients, so just do it.
- BufferedPacket packet = con::makePacket(peer_address, packetdata,
- m_connection->GetProtocolID(), peer->id, channelnum);
+ BufferedPacket packet = con::makePacket(
+ peer_address,
+ packetdata,
+ m_connection->GetProtocolID(),
+ peer->id,
+ channelnum);
try {
- channel->incoming_reliables.insert(
- packet, channel->readNextIncomingSeqNum());
+ channel->incoming_reliables.insert(packet, channel->readNextIncomingSeqNum());
LOG(dout_con << m_connection->getDesc()
- << "BUFFERING, TYPE_RELIABLE peer_id: " << peer->id
- << ", channel: " << (channelnum & 0xFF)
- << ", seqnum: " << seqnum << std::endl;)
+ << "BUFFERING, TYPE_RELIABLE peer_id: " << peer->id
+ << ", channel: " << (channelnum & 0xFF)
+ << ", seqnum: " << seqnum << std::endl;)
throw ProcessedQueued("Buffered future reliable packet");
} catch (AlreadyExistsException &e) {
@@ -1374,24 +1352,25 @@ SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Reliable(Channel *cha
m_connection->putCommand(discon);
LOG(derr_con << m_connection->getDesc()
- << "INVALID, TYPE_RELIABLE peer_id: " << peer->id
- << ", channel: " << (channelnum & 0xFF)
- << ", seqnum: " << seqnum << "DROPPING CLIENT!"
- << std::endl;)
+ << "INVALID, TYPE_RELIABLE peer_id: " << peer->id
+ << ", channel: " << (channelnum & 0xFF)
+ << ", seqnum: " << seqnum
+ << "DROPPING CLIENT!" << std::endl;)
}
}
/* we got a packet to process right now */
- LOG(dout_con << m_connection->getDesc() << "RECURSIVE, TYPE_RELIABLE peer_id: "
- << peer->id << ", channel: " << (channelnum & 0xFF)
- << ", seqnum: " << seqnum << std::endl;)
+ LOG(dout_con << m_connection->getDesc()
+ << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer->id
+ << ", channel: " << (channelnum & 0xFF)
+ << ", seqnum: " << seqnum << std::endl;)
+
/* check for resend case */
u16 queued_seqnum = 0;
if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum)) {
if (queued_seqnum == seqnum) {
- BufferedPacket queued_packet =
- channel->incoming_reliables.popFirst();
+ BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
/** TODO find a way to verify the new against the old packet */
}
}
diff --git a/src/network/networkpacket.cpp b/src/network/networkpacket.cpp
index e82dd583e..4d531b611 100644
--- a/src/network/networkpacket.cpp
+++ b/src/network/networkpacket.cpp
@@ -23,14 +23,14 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "util/serialize.h"
#include "networkprotocol.h"
-NetworkPacket::NetworkPacket(u16 command, u32 datasize, session_t peer_id) :
- m_datasize(datasize), m_command(command), m_peer_id(peer_id)
+NetworkPacket::NetworkPacket(u16 command, u32 datasize, session_t peer_id):
+m_datasize(datasize), m_command(command), m_peer_id(peer_id)
{
m_data.resize(m_datasize);
}
-NetworkPacket::NetworkPacket(u16 command, u32 datasize) :
- m_datasize(datasize), m_command(command)
+NetworkPacket::NetworkPacket(u16 command, u32 datasize):
+m_datasize(datasize), m_command(command)
{
m_data.resize(m_datasize);
}
@@ -44,8 +44,8 @@ void NetworkPacket::checkReadOffset(u32 from_offset, u32 field_size)
{
if (from_offset + field_size > m_datasize) {
std::stringstream ss;
- ss << "Reading outside packet (offset: " << from_offset
- << ", packet size: " << getSize() << ")";
+ ss << "Reading outside packet (offset: " <<
+ from_offset << ", packet size: " << getSize() << ")";
throw PacketError(ss.str());
}
}
@@ -75,14 +75,14 @@ void NetworkPacket::clear()
m_peer_id = 0;
}
-const char *NetworkPacket::getString(u32 from_offset)
+const char* NetworkPacket::getString(u32 from_offset)
{
checkReadOffset(from_offset, 0);
- return (char *)&m_data[from_offset];
+ return (char*)&m_data[from_offset];
}
-void NetworkPacket::putRawString(const char *src, u32 len)
+void NetworkPacket::putRawString(const char* src, u32 len)
{
if (m_read_offset + len > m_datasize) {
m_datasize = m_read_offset + len;
@@ -96,7 +96,7 @@ void NetworkPacket::putRawString(const char *src, u32 len)
m_read_offset += len;
}
-NetworkPacket &NetworkPacket::operator>>(std::string &dst)
+NetworkPacket& NetworkPacket::operator>>(std::string& dst)
{
checkReadOffset(m_read_offset, 2);
u16 strLen = readU16(&m_data[m_read_offset]);
@@ -111,13 +111,13 @@ NetworkPacket &NetworkPacket::operator>>(std::string &dst)
checkReadOffset(m_read_offset, 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;
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(const std::string &src)
+NetworkPacket& NetworkPacket::operator<<(const std::string &src)
{
if (src.size() > STRING_MAX_LEN) {
throw PacketError("String too long");
@@ -145,7 +145,7 @@ void NetworkPacket::putLongString(const std::string &src)
putRawString(src.c_str(), msgsize);
}
-NetworkPacket &NetworkPacket::operator>>(std::wstring &dst)
+NetworkPacket& NetworkPacket::operator>>(std::wstring& dst)
{
checkReadOffset(m_read_offset, 2);
u16 strLen = readU16(&m_data[m_read_offset]);
@@ -160,7 +160,7 @@ NetworkPacket &NetworkPacket::operator>>(std::wstring &dst)
checkReadOffset(m_read_offset, strLen * 2);
dst.reserve(strLen);
- for (u16 i = 0; i < strLen; i++) {
+ for(u16 i=0; i<strLen; i++) {
wchar_t c16 = readU16(&m_data[m_read_offset]);
dst.append(&c16, 1);
m_read_offset += sizeof(u16);
@@ -169,7 +169,7 @@ NetworkPacket &NetworkPacket::operator>>(std::wstring &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(const std::wstring &src)
+NetworkPacket& NetworkPacket::operator<<(const std::wstring &src)
{
if (src.size() > WIDE_STRING_MAX_LEN) {
throw PacketError("String too long");
@@ -180,8 +180,8 @@ NetworkPacket &NetworkPacket::operator<<(const std::wstring &src)
*this << msgsize;
// Write string
- for (u16 i = 0; i < msgsize; i++) {
- *this << (u16)src[i];
+ for (u16 i=0; i<msgsize; i++) {
+ *this << (u16) src[i];
}
return *this;
@@ -206,14 +206,14 @@ std::string NetworkPacket::readLongString()
std::string dst;
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;
return dst;
}
-NetworkPacket &NetworkPacket::operator>>(char &dst)
+NetworkPacket& NetworkPacket::operator>>(char& dst)
{
checkReadOffset(m_read_offset, 1);
@@ -230,7 +230,7 @@ char NetworkPacket::getChar(u32 offset)
return readU8(&m_data[offset]);
}
-NetworkPacket &NetworkPacket::operator<<(char src)
+NetworkPacket& NetworkPacket::operator<<(char src)
{
checkDataSize(1);
@@ -240,7 +240,7 @@ NetworkPacket &NetworkPacket::operator<<(char src)
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(u8 src)
+NetworkPacket& NetworkPacket::operator<<(u8 src)
{
checkDataSize(1);
@@ -250,7 +250,7 @@ NetworkPacket &NetworkPacket::operator<<(u8 src)
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(bool src)
+NetworkPacket& NetworkPacket::operator<<(bool src)
{
checkDataSize(1);
@@ -260,7 +260,7 @@ NetworkPacket &NetworkPacket::operator<<(bool src)
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(u16 src)
+NetworkPacket& NetworkPacket::operator<<(u16 src)
{
checkDataSize(2);
@@ -270,7 +270,7 @@ NetworkPacket &NetworkPacket::operator<<(u16 src)
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(u32 src)
+NetworkPacket& NetworkPacket::operator<<(u32 src)
{
checkDataSize(4);
@@ -280,7 +280,7 @@ NetworkPacket &NetworkPacket::operator<<(u32 src)
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(u64 src)
+NetworkPacket& NetworkPacket::operator<<(u64 src)
{
checkDataSize(8);
@@ -290,7 +290,7 @@ NetworkPacket &NetworkPacket::operator<<(u64 src)
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(float src)
+NetworkPacket& NetworkPacket::operator<<(float src)
{
checkDataSize(4);
@@ -300,7 +300,7 @@ NetworkPacket &NetworkPacket::operator<<(float src)
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(bool &dst)
+NetworkPacket& NetworkPacket::operator>>(bool& dst)
{
checkReadOffset(m_read_offset, 1);
@@ -310,7 +310,7 @@ NetworkPacket &NetworkPacket::operator>>(bool &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(u8 &dst)
+NetworkPacket& NetworkPacket::operator>>(u8& dst)
{
checkReadOffset(m_read_offset, 1);
@@ -327,7 +327,7 @@ u8 NetworkPacket::getU8(u32 offset)
return readU8(&m_data[offset]);
}
-u8 *NetworkPacket::getU8Ptr(u32 from_offset)
+u8* NetworkPacket::getU8Ptr(u32 from_offset)
{
if (m_datasize == 0) {
return NULL;
@@ -335,10 +335,10 @@ u8 *NetworkPacket::getU8Ptr(u32 from_offset)
checkReadOffset(from_offset, 1);
- return (u8 *)&m_data[from_offset];
+ return (u8*)&m_data[from_offset];
}
-NetworkPacket &NetworkPacket::operator>>(u16 &dst)
+NetworkPacket& NetworkPacket::operator>>(u16& dst)
{
checkReadOffset(m_read_offset, 2);
@@ -355,7 +355,7 @@ u16 NetworkPacket::getU16(u32 from_offset)
return readU16(&m_data[from_offset]);
}
-NetworkPacket &NetworkPacket::operator>>(u32 &dst)
+NetworkPacket& NetworkPacket::operator>>(u32& dst)
{
checkReadOffset(m_read_offset, 4);
@@ -365,7 +365,7 @@ NetworkPacket &NetworkPacket::operator>>(u32 &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(u64 &dst)
+NetworkPacket& NetworkPacket::operator>>(u64& dst)
{
checkReadOffset(m_read_offset, 8);
@@ -375,7 +375,7 @@ NetworkPacket &NetworkPacket::operator>>(u64 &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(float &dst)
+NetworkPacket& NetworkPacket::operator>>(float& dst)
{
checkReadOffset(m_read_offset, 4);
@@ -385,7 +385,7 @@ NetworkPacket &NetworkPacket::operator>>(float &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(v2f &dst)
+NetworkPacket& NetworkPacket::operator>>(v2f& dst)
{
checkReadOffset(m_read_offset, 8);
@@ -395,7 +395,7 @@ NetworkPacket &NetworkPacket::operator>>(v2f &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(v3f &dst)
+NetworkPacket& NetworkPacket::operator>>(v3f& dst)
{
checkReadOffset(m_read_offset, 12);
@@ -405,7 +405,7 @@ NetworkPacket &NetworkPacket::operator>>(v3f &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(s16 &dst)
+NetworkPacket& NetworkPacket::operator>>(s16& dst)
{
checkReadOffset(m_read_offset, 2);
@@ -415,13 +415,13 @@ NetworkPacket &NetworkPacket::operator>>(s16 &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(s16 src)
+NetworkPacket& NetworkPacket::operator<<(s16 src)
{
- *this << (u16)src;
+ *this << (u16) src;
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(s32 &dst)
+NetworkPacket& NetworkPacket::operator>>(s32& dst)
{
checkReadOffset(m_read_offset, 4);
@@ -431,13 +431,13 @@ NetworkPacket &NetworkPacket::operator>>(s32 &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(s32 src)
+NetworkPacket& NetworkPacket::operator<<(s32 src)
{
- *this << (u32)src;
+ *this << (u32) src;
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(v3s16 &dst)
+NetworkPacket& NetworkPacket::operator>>(v3s16& dst)
{
checkReadOffset(m_read_offset, 6);
@@ -447,7 +447,7 @@ NetworkPacket &NetworkPacket::operator>>(v3s16 &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(v2s32 &dst)
+NetworkPacket& NetworkPacket::operator>>(v2s32& dst)
{
checkReadOffset(m_read_offset, 8);
@@ -457,7 +457,7 @@ NetworkPacket &NetworkPacket::operator>>(v2s32 &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(v3s32 &dst)
+NetworkPacket& NetworkPacket::operator>>(v3s32& dst)
{
checkReadOffset(m_read_offset, 12);
@@ -467,45 +467,45 @@ NetworkPacket &NetworkPacket::operator>>(v3s32 &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(v2f src)
+NetworkPacket& NetworkPacket::operator<<(v2f src)
{
- *this << (float)src.X;
- *this << (float)src.Y;
+ *this << (float) src.X;
+ *this << (float) src.Y;
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(v3f src)
+NetworkPacket& NetworkPacket::operator<<(v3f src)
{
- *this << (float)src.X;
- *this << (float)src.Y;
- *this << (float)src.Z;
+ *this << (float) src.X;
+ *this << (float) src.Y;
+ *this << (float) src.Z;
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(v3s16 src)
+NetworkPacket& NetworkPacket::operator<<(v3s16 src)
{
- *this << (s16)src.X;
- *this << (s16)src.Y;
- *this << (s16)src.Z;
+ *this << (s16) src.X;
+ *this << (s16) src.Y;
+ *this << (s16) src.Z;
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(v2s32 src)
+NetworkPacket& NetworkPacket::operator<<(v2s32 src)
{
- *this << (s32)src.X;
- *this << (s32)src.Y;
+ *this << (s32) src.X;
+ *this << (s32) src.Y;
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(v3s32 src)
+NetworkPacket& NetworkPacket::operator<<(v3s32 src)
{
- *this << (s32)src.X;
- *this << (s32)src.Y;
- *this << (s32)src.Z;
+ *this << (s32) src.X;
+ *this << (s32) src.Y;
+ *this << (s32) src.Z;
return *this;
}
-NetworkPacket &NetworkPacket::operator>>(video::SColor &dst)
+NetworkPacket& NetworkPacket::operator>>(video::SColor& dst)
{
checkReadOffset(m_read_offset, 4);
@@ -515,7 +515,7 @@ NetworkPacket &NetworkPacket::operator>>(video::SColor &dst)
return *this;
}
-NetworkPacket &NetworkPacket::operator<<(video::SColor src)
+NetworkPacket& NetworkPacket::operator<<(video::SColor src)
{
checkDataSize(4);
@@ -530,7 +530,7 @@ SharedBuffer<u8> NetworkPacket::oldForgePacket()
SharedBuffer<u8> sb(m_datasize + 2);
writeU16(&sb[0], m_command);
- u8 *datas = getU8Ptr(0);
+ u8* datas = getU8Ptr(0);
if (datas != NULL)
memcpy(&sb[2], datas, m_datasize);
diff --git a/src/network/networkprotocol.h b/src/network/networkprotocol.h
index c6b3d43d0..e57a7a794 100644
--- a/src/network/networkprotocol.h
+++ b/src/network/networkprotocol.h
@@ -127,8 +127,9 @@ with this program; if not, write to the Free Software Foundation, Inc.,
TOSERVER_SRP_BYTES_M, TOCLIENT_SRP_BYTES_S_B
for the three supported auth mechanisms around srp
Add new opcodes TOCLIENT_ACCEPT_SUDO_MODE and TOCLIENT_DENY_SUDO_MODE
- for sudo mode handling (auth mech generic way of changing
- password). Add TOCLIENT_HELLO for presenting server to client after client presentation
+ for sudo mode handling (auth mech generic way of changing password).
+ Add TOCLIENT_HELLO for presenting server to client after client
+ presentation
Add TOCLIENT_AUTH_ACCEPT to accept connection from client
Rename GENERIC_CMD_SET_ATTACHMENT to AO_CMD_ATTACH_TO
PROTOCOL_VERSION 26:
@@ -160,14 +161,14 @@ with this program; if not, write to the Free Software Foundation, Inc.,
PROTOCOL VERSION 34:
Add sound pitch
PROTOCOL VERSION 35:
- Rename TOCLIENT_CHAT_MESSAGE to TOCLIENT_CHAT_MESSAGE_OLD (0x30)
- Add TOCLIENT_CHAT_MESSAGE (0x2F)
- This chat message is a signalisation message containing various
+ Rename TOCLIENT_CHAT_MESSAGE to TOCLIENT_CHAT_MESSAGE_OLD (0x30)
+ Add TOCLIENT_CHAT_MESSAGE (0x2F)
+ This chat message is a signalisation message containing various
informations:
- * timestamp
- * sender
- * type (RAW, NORMAL, ANNOUNCE, SYSTEM)
- * content
+ * timestamp
+ * sender
+ * type (RAW, NORMAL, ANNOUNCE, SYSTEM)
+ * content
Add TOCLIENT_CSM_RESTRICTION_FLAGS to define which CSM features should be
limited
Add settable player collisionbox. Breaks compatibility with older
@@ -221,9 +222,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
// Constant that differentiates the protocol from random data and other protocols
#define PROTOCOL_ID 0x4f457403
-#define PASSWORD_SIZE \
- 28 // Maximum password length. Allows for
- // base64-encoded SHA-1 (27+\0).
+#define PASSWORD_SIZE 28 // Maximum password length. Allows for
+ // base64-encoded SHA-1 (27+\0).
/*
Changes by FORMSPEC_API_VERSION:
@@ -243,8 +243,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
*/
#define FORMSPEC_API_VERSION 4
-#define TEXTURENAME_ALLOWED_CHARS \
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-"
+#define TEXTURENAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-"
typedef u16 session_t;
@@ -258,8 +257,7 @@ enum ToClientCommand
u16 deployed network compression mode
u16 deployed protocol version
u32 supported auth methods
- std::string username that should be used for legacy hash (for proper
- casing)
+ std::string username that should be used for legacy hash (for proper casing)
*/
TOCLIENT_AUTH_ACCEPT = 0x03,
/*
@@ -288,7 +286,7 @@ enum ToClientCommand
TOCLIENT_INIT_LEGACY = 0x10, // Obsolete
- TOCLIENT_BLOCKDATA = 0x20, // TODO: Multiple blocks
+ TOCLIENT_BLOCKDATA = 0x20, //TODO: Multiple blocks
TOCLIENT_ADDNODE = 0x21,
/*
v3s16 position
@@ -297,10 +295,10 @@ enum ToClientCommand
*/
TOCLIENT_REMOVENODE = 0x22,
- TOCLIENT_PLAYERPOS = 0x23, // Obsolete
- TOCLIENT_PLAYERINFO = 0x24, // Obsolete
+ TOCLIENT_PLAYERPOS = 0x23, // Obsolete
+ TOCLIENT_PLAYERINFO = 0x24, // Obsolete
TOCLIENT_OPT_BLOCK_NOT_FOUND = 0x25, // Obsolete
- TOCLIENT_SECTORMETA = 0x26, // Obsolete
+ TOCLIENT_SECTORMETA = 0x26, // Obsolete
TOCLIENT_INVENTORY = 0x27,
/*
@@ -698,8 +696,8 @@ enum ToClientCommand
*/
TOCLIENT_UPDATE_PLAYER_LIST = 0x56,
/*
- u8 type
- u16 number of players
+ u8 type
+ u16 number of players
for each player
u16 len
u8[len] player name
@@ -708,18 +706,18 @@ enum ToClientCommand
TOCLIENT_MODCHANNEL_MSG = 0x57,
/*
u16 channel name length
- std::string channel name
- u16 channel name sender
- std::string channel name
- u16 message length
- std::string message
+ std::string channel name
+ u16 channel name sender
+ std::string channel name
+ u16 message length
+ std::string message
*/
TOCLIENT_MODCHANNEL_SIGNAL = 0x58,
/*
u8 signal id
- u16 channel name length
- std::string channel name
+ u16 channel name length
+ std::string channel name
*/
TOCLIENT_NODEMETA_CHANGED = 0x59,
@@ -795,25 +793,25 @@ enum ToServerCommand
TOSERVER_MODCHANNEL_JOIN = 0x17,
/*
u16 channel name length
- std::string channel name
+ std::string channel name
*/
TOSERVER_MODCHANNEL_LEAVE = 0x18,
/*
u16 channel name length
- std::string channel name
+ std::string channel name
*/
TOSERVER_MODCHANNEL_MSG = 0x19,
/*
u16 channel name length
- std::string channel name
- u16 message length
- std::string message
+ std::string channel name
+ u16 message length
+ std::string message
*/
- TOSERVER_GETBLOCK = 0x20, // Obsolete
- TOSERVER_ADDNODE = 0x21, // Obsolete
+ TOSERVER_GETBLOCK = 0x20, // Obsolete
+ TOSERVER_ADDNODE = 0x21, // Obsolete
TOSERVER_REMOVENODE = 0x22, // Obsolete
TOSERVER_PLAYERPOS = 0x23,
@@ -847,10 +845,10 @@ enum ToServerCommand
*/
TOSERVER_ADDNODE_FROM_INVENTORY = 0x26, // Obsolete
- TOSERVER_CLICK_OBJECT = 0x27, // Obsolete
- TOSERVER_GROUND_ACTION = 0x28, // Obsolete
- TOSERVER_RELEASE = 0x29, // Obsolete
- TOSERVER_SIGNTEXT = 0x30, // Obsolete
+ TOSERVER_CLICK_OBJECT = 0x27, // Obsolete
+ TOSERVER_GROUND_ACTION = 0x28, // Obsolete
+ TOSERVER_RELEASE = 0x29, // Obsolete
+ TOSERVER_SIGNTEXT = 0x30, // Obsolete
TOSERVER_INVENTORY_ACTION = 0x31,
/*
@@ -863,7 +861,7 @@ enum ToServerCommand
wstring message
*/
- TOSERVER_SIGNNODETEXT = 0x33, // Obsolete
+ TOSERVER_SIGNNODETEXT = 0x33, // Obsolete
TOSERVER_CLICK_ACTIVEOBJECT = 0x34, // Obsolete
TOSERVER_DAMAGE = 0x35,
@@ -942,7 +940,7 @@ enum ToServerCommand
*/
TOSERVER_RECEIVED_MEDIA = 0x41, // Obsolete
- TOSERVER_BREATH = 0x42, // Obsolete
+ TOSERVER_BREATH = 0x42, // Obsolete
TOSERVER_CLIENT_READY = 0x43,
/*
@@ -970,8 +968,8 @@ enum ToServerCommand
std::string bytes_A
u8 current_login_based_on : on which version of the password's
- hash this login is based on (0 legacy hash,
- or 1 directly the password)
+ hash this login is based on (0 legacy hash,
+ or 1 directly the password)
*/
TOSERVER_SRP_BYTES_M = 0x52,
@@ -999,8 +997,7 @@ enum AuthMechanism
AUTH_MECHANISM_FIRST_SRP = 1 << 2,
};
-enum AccessDeniedCode
-{
+enum AccessDeniedCode {
SERVER_ACCESSDENIED_WRONG_PASSWORD,
SERVER_ACCESSDENIED_UNEXPECTED_DATA,
SERVER_ACCESSDENIED_SINGLEPLAYER,
@@ -1017,58 +1014,54 @@ enum AccessDeniedCode
SERVER_ACCESSDENIED_MAX,
};
-enum NetProtoCompressionMode
-{
+enum NetProtoCompressionMode {
NETPROTO_COMPRESSION_NONE = 0,
};
const static std::string accessDeniedStrings[SERVER_ACCESSDENIED_MAX] = {
- "Invalid password",
- "Your client sent something the server didn't expect. Try reconnecting "
- "or updating your client",
- "The server is running in simple singleplayer mode. You cannot connect.",
- "Your client's version is not supported.\nPlease contact server "
- "administrator.",
- "Player name contains disallowed characters.", "Player name not allowed.",
- "Too many users.",
- "Empty passwords are disallowed. Set a password and try again.",
- "Another client is connected with this name. If your client closed "
- "unexpectedly, try again in a minute.",
- "Server authentication failed. This is likely a server error.", "",
- "Server shutting down.",
- "This server has experienced an internal error. You will now be "
- "disconnected."};
-
-enum PlayerListModifer : u8
+ "Invalid password",
+ "Your client sent something the server didn't expect. Try reconnecting or updating your client",
+ "The server is running in simple singleplayer mode. You cannot connect.",
+ "Your client's version is not supported.\nPlease contact server administrator.",
+ "Player name contains disallowed characters.",
+ "Player name not allowed.",
+ "Too many users.",
+ "Empty passwords are disallowed. Set a password and try again.",
+ "Another client is connected with this name. If your client closed unexpectedly, try again in a minute.",
+ "Server authentication failed. This is likely a server error.",
+ "",
+ "Server shutting down.",
+ "This server has experienced an internal error. You will now be disconnected."
+};
+
+enum PlayerListModifer: u8
{
PLAYER_LIST_INIT,
PLAYER_LIST_ADD,
PLAYER_LIST_REMOVE,
};
-enum CSMRestrictionFlags : u64
-{
+enum CSMRestrictionFlags : u64 {
CSM_RF_NONE = 0x00000000,
// Until server-sent CSM and verifying of builtin are complete,
// 'CSM_RF_LOAD_CLIENT_MODS' also disables loading 'builtin'.
// When those are complete, this should return to only being a restriction on the
// loading of client mods.
- CSM_RF_LOAD_CLIENT_MODS =
- 0x00000001, // Don't load client-provided mods or 'builtin'
- CSM_RF_CHAT_MESSAGES = 0x00000002, // Disable chat message sending from CSM
- CSM_RF_READ_ITEMDEFS = 0x00000004, // Disable itemdef lookups
- CSM_RF_READ_NODEDEFS = 0x00000008, // Disable nodedef lookups
- CSM_RF_LOOKUP_NODES = 0x00000010, // Limit node lookups
- CSM_RF_READ_PLAYERINFO = 0x00000020, // Disable player info lookups
+ CSM_RF_LOAD_CLIENT_MODS = 0x00000001, // Don't load client-provided mods or 'builtin'
+ CSM_RF_CHAT_MESSAGES = 0x00000002, // Disable chat message sending from CSM
+ CSM_RF_READ_ITEMDEFS = 0x00000004, // Disable itemdef lookups
+ CSM_RF_READ_NODEDEFS = 0x00000008, // Disable nodedef lookups
+ CSM_RF_LOOKUP_NODES = 0x00000010, // Limit node lookups
+ CSM_RF_READ_PLAYERINFO = 0x00000020, // Disable player info lookups
CSM_RF_ALL = 0xFFFFFFFF,
};
enum InteractAction : u8
{
- INTERACT_START_DIGGING, // 0: start digging (from undersurface) or use
- INTERACT_STOP_DIGGING, // 1: stop digging (all parameters ignored)
+ INTERACT_START_DIGGING, // 0: start digging (from undersurface) or use
+ INTERACT_STOP_DIGGING, // 1: stop digging (all parameters ignored)
INTERACT_DIGGING_COMPLETED, // 2: digging completed
- INTERACT_PLACE, // 3: place block or item (to abovesurface)
- INTERACT_USE, // 4: use item
- INTERACT_ACTIVATE // 5: rightclick air ("activate")
+ INTERACT_PLACE, // 3: place block or item (to abovesurface)
+ INTERACT_USE, // 4: use item
+ INTERACT_ACTIVATE // 5: rightclick air ("activate")
};
diff --git a/src/network/serveropcodes.cpp b/src/network/serveropcodes.cpp
index ecfac0fcd..2fc3197c2 100644
--- a/src/network/serveropcodes.cpp
+++ b/src/network/serveropcodes.cpp
@@ -20,118 +20,96 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "serveropcodes.h"
-const static ToServerCommandHandler null_command_handler = {
- "TOSERVER_NULL", TOSERVER_STATE_ALL, &Server::handleCommand_Null};
+const static ToServerCommandHandler null_command_handler = { "TOSERVER_NULL", TOSERVER_STATE_ALL, &Server::handleCommand_Null };
-const ToServerCommandHandler toServerCommandTable[TOSERVER_NUM_MSG_TYPES] = {
- null_command_handler, // 0x00 (never use this)
- null_command_handler, // 0x01
- {"TOSERVER_INIT", TOSERVER_STATE_NOT_CONNECTED,
- &Server::handleCommand_Init}, // 0x02
- null_command_handler, // 0x03
- null_command_handler, // 0x04
- null_command_handler, // 0x05
- null_command_handler, // 0x06
- null_command_handler, // 0x07
- null_command_handler, // 0x08
- null_command_handler, // 0x09
- null_command_handler, // 0x0a
- null_command_handler, // 0x0b
- null_command_handler, // 0x0c
- null_command_handler, // 0x0d
- null_command_handler, // 0x0e
- null_command_handler, // 0x0f
- null_command_handler, // 0x10
- {"TOSERVER_INIT2", TOSERVER_STATE_NOT_CONNECTED,
- &Server::handleCommand_Init2}, // 0x11
- null_command_handler, // 0x12
- null_command_handler, // 0x13
- null_command_handler, // 0x14
- null_command_handler, // 0x15
- null_command_handler, // 0x16
- {"TOSERVER_MODCHANNEL_JOIN", TOSERVER_STATE_INGAME,
- &Server::handleCommand_ModChannelJoin}, // 0x17
- {"TOSERVER_MODCHANNEL_LEAVE", TOSERVER_STATE_INGAME,
- &Server::handleCommand_ModChannelLeave}, // 0x18
- {"TOSERVER_MODCHANNEL_MSG", TOSERVER_STATE_INGAME,
- &Server::handleCommand_ModChannelMsg}, // 0x19
- null_command_handler, // 0x1a
- null_command_handler, // 0x1b
- null_command_handler, // 0x1c
- null_command_handler, // 0x1d
- null_command_handler, // 0x1e
- null_command_handler, // 0x1f
- null_command_handler, // 0x20
- null_command_handler, // 0x21
- null_command_handler, // 0x22
- {"TOSERVER_PLAYERPOS", TOSERVER_STATE_INGAME,
- &Server::handleCommand_PlayerPos}, // 0x23
- {"TOSERVER_GOTBLOCKS", TOSERVER_STATE_STARTUP,
- &Server::handleCommand_GotBlocks}, // 0x24
- {"TOSERVER_DELETEDBLOCKS", TOSERVER_STATE_INGAME,
- &Server::handleCommand_DeletedBlocks}, // 0x25
- null_command_handler, // 0x26
- null_command_handler, // 0x27
- null_command_handler, // 0x28
- null_command_handler, // 0x29
- null_command_handler, // 0x2a
- null_command_handler, // 0x2b
- null_command_handler, // 0x2c
- null_command_handler, // 0x2d
- null_command_handler, // 0x2e
- null_command_handler, // 0x2f
- null_command_handler, // 0x30
- {"TOSERVER_INVENTORY_ACTION", TOSERVER_STATE_INGAME,
- &Server::handleCommand_InventoryAction}, // 0x31
- {"TOSERVER_CHAT_MESSAGE", TOSERVER_STATE_INGAME,
- &Server::handleCommand_ChatMessage}, // 0x32
- null_command_handler, // 0x33
- null_command_handler, // 0x34
- {"TOSERVER_DAMAGE", TOSERVER_STATE_INGAME,
- &Server::handleCommand_Damage}, // 0x35
- null_command_handler, // 0x36
- {"TOSERVER_PLAYERITEM", TOSERVER_STATE_INGAME,
- &Server::handleCommand_PlayerItem}, // 0x37
- {"TOSERVER_RESPAWN", TOSERVER_STATE_INGAME,
- &Server::handleCommand_Respawn}, // 0x38
- {"TOSERVER_INTERACT", TOSERVER_STATE_INGAME,
- &Server::handleCommand_Interact}, // 0x39
- {"TOSERVER_REMOVED_SOUNDS", TOSERVER_STATE_INGAME,
- &Server::handleCommand_RemovedSounds}, // 0x3a
- {"TOSERVER_NODEMETA_FIELDS", TOSERVER_STATE_INGAME,
- &Server::handleCommand_NodeMetaFields}, // 0x3b
- {"TOSERVER_INVENTORY_FIELDS", TOSERVER_STATE_INGAME,
- &Server::handleCommand_InventoryFields}, // 0x3c
- null_command_handler, // 0x3d
- null_command_handler, // 0x3e
- null_command_handler, // 0x3f
- {"TOSERVER_REQUEST_MEDIA", TOSERVER_STATE_STARTUP,
- &Server::handleCommand_RequestMedia}, // 0x40
- null_command_handler, // 0x41
- null_command_handler, // 0x42
- {"TOSERVER_CLIENT_READY", TOSERVER_STATE_STARTUP,
- &Server::handleCommand_ClientReady}, // 0x43
- null_command_handler, // 0x44
- null_command_handler, // 0x45
- null_command_handler, // 0x46
- null_command_handler, // 0x47
- null_command_handler, // 0x48
- null_command_handler, // 0x49
- null_command_handler, // 0x4a
- null_command_handler, // 0x4b
- null_command_handler, // 0x4c
- null_command_handler, // 0x4d
- null_command_handler, // 0x4e
- null_command_handler, // 0x4f
- {"TOSERVER_FIRST_SRP", TOSERVER_STATE_NOT_CONNECTED,
- &Server::handleCommand_FirstSrp}, // 0x50
- {"TOSERVER_SRP_BYTES_A", TOSERVER_STATE_NOT_CONNECTED,
- &Server::handleCommand_SrpBytesA}, // 0x51
- {"TOSERVER_SRP_BYTES_M", TOSERVER_STATE_NOT_CONNECTED,
- &Server::handleCommand_SrpBytesM}, // 0x52
+const ToServerCommandHandler toServerCommandTable[TOSERVER_NUM_MSG_TYPES] =
+{
+ null_command_handler, // 0x00 (never use this)
+ null_command_handler, // 0x01
+ { "TOSERVER_INIT", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_Init }, // 0x02
+ null_command_handler, // 0x03
+ null_command_handler, // 0x04
+ null_command_handler, // 0x05
+ null_command_handler, // 0x06
+ null_command_handler, // 0x07
+ null_command_handler, // 0x08
+ null_command_handler, // 0x09
+ null_command_handler, // 0x0a
+ null_command_handler, // 0x0b
+ null_command_handler, // 0x0c
+ null_command_handler, // 0x0d
+ null_command_handler, // 0x0e
+ null_command_handler, // 0x0f
+ null_command_handler, // 0x10
+ { "TOSERVER_INIT2", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_Init2 }, // 0x11
+ null_command_handler, // 0x12
+ null_command_handler, // 0x13
+ null_command_handler, // 0x14
+ null_command_handler, // 0x15
+ null_command_handler, // 0x16
+ { "TOSERVER_MODCHANNEL_JOIN", TOSERVER_STATE_INGAME, &Server::handleCommand_ModChannelJoin }, // 0x17
+ { "TOSERVER_MODCHANNEL_LEAVE", TOSERVER_STATE_INGAME, &Server::handleCommand_ModChannelLeave }, // 0x18
+ { "TOSERVER_MODCHANNEL_MSG", TOSERVER_STATE_INGAME, &Server::handleCommand_ModChannelMsg }, // 0x19
+ null_command_handler, // 0x1a
+ null_command_handler, // 0x1b
+ null_command_handler, // 0x1c
+ null_command_handler, // 0x1d
+ null_command_handler, // 0x1e
+ null_command_handler, // 0x1f
+ null_command_handler, // 0x20
+ null_command_handler, // 0x21
+ null_command_handler, // 0x22
+ { "TOSERVER_PLAYERPOS", TOSERVER_STATE_INGAME, &Server::handleCommand_PlayerPos }, // 0x23
+ { "TOSERVER_GOTBLOCKS", TOSERVER_STATE_STARTUP, &Server::handleCommand_GotBlocks }, // 0x24
+ { "TOSERVER_DELETEDBLOCKS", TOSERVER_STATE_INGAME, &Server::handleCommand_DeletedBlocks }, // 0x25
+ null_command_handler, // 0x26
+ null_command_handler, // 0x27
+ null_command_handler, // 0x28
+ null_command_handler, // 0x29
+ null_command_handler, // 0x2a
+ null_command_handler, // 0x2b
+ null_command_handler, // 0x2c
+ null_command_handler, // 0x2d
+ null_command_handler, // 0x2e
+ null_command_handler, // 0x2f
+ null_command_handler, // 0x30
+ { "TOSERVER_INVENTORY_ACTION", TOSERVER_STATE_INGAME, &Server::handleCommand_InventoryAction }, // 0x31
+ { "TOSERVER_CHAT_MESSAGE", TOSERVER_STATE_INGAME, &Server::handleCommand_ChatMessage }, // 0x32
+ null_command_handler, // 0x33
+ null_command_handler, // 0x34
+ { "TOSERVER_DAMAGE", TOSERVER_STATE_INGAME, &Server::handleCommand_Damage }, // 0x35
+ null_command_handler, // 0x36
+ { "TOSERVER_PLAYERITEM", TOSERVER_STATE_INGAME, &Server::handleCommand_PlayerItem }, // 0x37
+ { "TOSERVER_RESPAWN", TOSERVER_STATE_INGAME, &Server::handleCommand_Respawn }, // 0x38
+ { "TOSERVER_INTERACT", TOSERVER_STATE_INGAME, &Server::handleCommand_Interact }, // 0x39
+ { "TOSERVER_REMOVED_SOUNDS", TOSERVER_STATE_INGAME, &Server::handleCommand_RemovedSounds }, // 0x3a
+ { "TOSERVER_NODEMETA_FIELDS", TOSERVER_STATE_INGAME, &Server::handleCommand_NodeMetaFields }, // 0x3b
+ { "TOSERVER_INVENTORY_FIELDS", TOSERVER_STATE_INGAME, &Server::handleCommand_InventoryFields }, // 0x3c
+ null_command_handler, // 0x3d
+ null_command_handler, // 0x3e
+ null_command_handler, // 0x3f
+ { "TOSERVER_REQUEST_MEDIA", TOSERVER_STATE_STARTUP, &Server::handleCommand_RequestMedia }, // 0x40
+ null_command_handler, // 0x41
+ null_command_handler, // 0x42
+ { "TOSERVER_CLIENT_READY", TOSERVER_STATE_STARTUP, &Server::handleCommand_ClientReady }, // 0x43
+ null_command_handler, // 0x44
+ null_command_handler, // 0x45
+ null_command_handler, // 0x46
+ null_command_handler, // 0x47
+ null_command_handler, // 0x48
+ null_command_handler, // 0x49
+ null_command_handler, // 0x4a
+ null_command_handler, // 0x4b
+ null_command_handler, // 0x4c
+ null_command_handler, // 0x4d
+ null_command_handler, // 0x4e
+ null_command_handler, // 0x4f
+ { "TOSERVER_FIRST_SRP", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_FirstSrp }, // 0x50
+ { "TOSERVER_SRP_BYTES_A", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_SrpBytesA }, // 0x51
+ { "TOSERVER_SRP_BYTES_M", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_SrpBytesM }, // 0x52
};
-const static ClientCommandFactory null_command_factory = {"TOCLIENT_NULL", 0, false};
+const static ClientCommandFactory null_command_factory = { "TOCLIENT_NULL", 0, false };
/*
Channels used for Server -> Client communication
@@ -143,104 +121,104 @@ const static ClientCommandFactory null_command_factory = {"TOCLIENT_NULL", 0, fa
the same objects are *required* to be in the same channel.
*/
-const ClientCommandFactory clientCommandFactoryTable[TOCLIENT_NUM_MSG_TYPES] = {
- null_command_factory, // 0x00
- null_command_factory, // 0x01
- {"TOCLIENT_HELLO", 0, true}, // 0x02
- {"TOCLIENT_AUTH_ACCEPT", 0, true}, // 0x03
- {"TOCLIENT_ACCEPT_SUDO_MODE", 0, true}, // 0x04
- {"TOCLIENT_DENY_SUDO_MODE", 0, true}, // 0x05
- null_command_factory, // 0x06
- null_command_factory, // 0x07
- null_command_factory, // 0x08
- null_command_factory, // 0x09
- {"TOCLIENT_ACCESS_DENIED", 0, true}, // 0x0A
- null_command_factory, // 0x0B
- null_command_factory, // 0x0C
- null_command_factory, // 0x0D
- null_command_factory, // 0x0E
- null_command_factory, // 0x0F
- {"TOCLIENT_INIT", 0, true}, // 0x10
- null_command_factory, // 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
- {"TOCLIENT_BLOCKDATA", 2, true}, // 0x20
- {"TOCLIENT_ADDNODE", 0, true}, // 0x21
- {"TOCLIENT_REMOVENODE", 0, true}, // 0x22
- null_command_factory, // 0x23
- null_command_factory, // 0x24
- null_command_factory, // 0x25
- null_command_factory, // 0x26
- {"TOCLIENT_INVENTORY", 0, true}, // 0x27
- null_command_factory, // 0x28
- {"TOCLIENT_TIME_OF_DAY", 0, true}, // 0x29
- {"TOCLIENT_CSM_RESTRICTION_FLAGS", 0, true}, // 0x2A
- {"TOCLIENT_PLAYER_SPEED", 0, true}, // 0x2B
- {"TOCLIENT_MEDIA_PUSH", 0, true}, // 0x2C (sent over channel 1 too)
- null_command_factory, // 0x2D
- null_command_factory, // 0x2E
- {"TOCLIENT_CHAT_MESSAGE", 0, true}, // 0x2F
- null_command_factory, // 0x30
- {"TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD", 0, true}, // 0x31
- {"TOCLIENT_ACTIVE_OBJECT_MESSAGES", 0,
- true}, // 0x32 (may be sent as unrel over channel 1 too)
- {"TOCLIENT_HP", 0, true}, // 0x33
- {"TOCLIENT_MOVE_PLAYER", 0, true}, // 0x34
- {"TOCLIENT_ACCESS_DENIED_LEGACY", 0, true}, // 0x35
- {"TOCLIENT_FOV", 0, true}, // 0x36
- {"TOCLIENT_DEATHSCREEN", 0, true}, // 0x37
- {"TOCLIENT_MEDIA", 2, true}, // 0x38
- null_command_factory, // 0x39
- {"TOCLIENT_NODEDEF", 0, true}, // 0x3A
- null_command_factory, // 0x3B
- {"TOCLIENT_ANNOUNCE_MEDIA", 0, true}, // 0x3C
- {"TOCLIENT_ITEMDEF", 0, true}, // 0x3D
- null_command_factory, // 0x3E
- {"TOCLIENT_PLAY_SOUND", 0, true}, // 0x3f (may be sent as unrel too)
- {"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
- null_command_factory, // 0x48
- {"TOCLIENT_HUDADD", 1, true}, // 0x49
- {"TOCLIENT_HUDRM", 1, true}, // 0x4a
- {"TOCLIENT_HUDCHANGE", 1, true}, // 0x4b
- {"TOCLIENT_HUD_SET_FLAGS", 1, true}, // 0x4c
- {"TOCLIENT_HUD_SET_PARAM", 1, 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
- {"TOCLIENT_DELETE_PARTICLESPAWNER", 0, true}, // 0x53
- {"TOCLIENT_CLOUD_PARAMS", 0, true}, // 0x54
- {"TOCLIENT_FADE_SOUND", 0, true}, // 0x55
- {"TOCLIENT_UPDATE_PLAYER_LIST", 0, true}, // 0x56
- {"TOCLIENT_MODCHANNEL_MSG", 0, true}, // 0x57
- {"TOCLIENT_MODCHANNEL_SIGNAL", 0, true}, // 0x58
- {"TOCLIENT_NODEMETA_CHANGED", 0, true}, // 0x59
- {"TOCLIENT_SET_SUN", 0, true}, // 0x5a
- {"TOCLIENT_SET_MOON", 0, true}, // 0x5b
- {"TOCLIENT_SET_STARS", 0, true}, // 0x5c
- null_command_factory, // 0x5d
- null_command_factory, // 0x5e
- null_command_factory, // 0x5f
- {"TOSERVER_SRP_BYTES_S_B", 0, true}, // 0x60
- {"TOCLIENT_FORMSPEC_PREPEND", 0, true}, // 0x61
+const ClientCommandFactory clientCommandFactoryTable[TOCLIENT_NUM_MSG_TYPES] =
+{
+ null_command_factory, // 0x00
+ null_command_factory, // 0x01
+ { "TOCLIENT_HELLO", 0, true }, // 0x02
+ { "TOCLIENT_AUTH_ACCEPT", 0, true }, // 0x03
+ { "TOCLIENT_ACCEPT_SUDO_MODE", 0, true }, // 0x04
+ { "TOCLIENT_DENY_SUDO_MODE", 0, true }, // 0x05
+ null_command_factory, // 0x06
+ null_command_factory, // 0x07
+ null_command_factory, // 0x08
+ null_command_factory, // 0x09
+ { "TOCLIENT_ACCESS_DENIED", 0, true }, // 0x0A
+ null_command_factory, // 0x0B
+ null_command_factory, // 0x0C
+ null_command_factory, // 0x0D
+ null_command_factory, // 0x0E
+ null_command_factory, // 0x0F
+ { "TOCLIENT_INIT", 0, true }, // 0x10
+ null_command_factory, // 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
+ { "TOCLIENT_BLOCKDATA", 2, true }, // 0x20
+ { "TOCLIENT_ADDNODE", 0, true }, // 0x21
+ { "TOCLIENT_REMOVENODE", 0, true }, // 0x22
+ null_command_factory, // 0x23
+ null_command_factory, // 0x24
+ null_command_factory, // 0x25
+ null_command_factory, // 0x26
+ { "TOCLIENT_INVENTORY", 0, true }, // 0x27
+ null_command_factory, // 0x28
+ { "TOCLIENT_TIME_OF_DAY", 0, true }, // 0x29
+ { "TOCLIENT_CSM_RESTRICTION_FLAGS", 0, true }, // 0x2A
+ { "TOCLIENT_PLAYER_SPEED", 0, true }, // 0x2B
+ { "TOCLIENT_MEDIA_PUSH", 0, true }, // 0x2C (sent over channel 1 too)
+ null_command_factory, // 0x2D
+ null_command_factory, // 0x2E
+ { "TOCLIENT_CHAT_MESSAGE", 0, true }, // 0x2F
+ null_command_factory, // 0x30
+ { "TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD", 0, true }, // 0x31
+ { "TOCLIENT_ACTIVE_OBJECT_MESSAGES", 0, true }, // 0x32 (may be sent as unrel over channel 1 too)
+ { "TOCLIENT_HP", 0, true }, // 0x33
+ { "TOCLIENT_MOVE_PLAYER", 0, true }, // 0x34
+ { "TOCLIENT_ACCESS_DENIED_LEGACY", 0, true }, // 0x35
+ { "TOCLIENT_FOV", 0, true }, // 0x36
+ { "TOCLIENT_DEATHSCREEN", 0, true }, // 0x37
+ { "TOCLIENT_MEDIA", 2, true }, // 0x38
+ null_command_factory, // 0x39
+ { "TOCLIENT_NODEDEF", 0, true }, // 0x3A
+ null_command_factory, // 0x3B
+ { "TOCLIENT_ANNOUNCE_MEDIA", 0, true }, // 0x3C
+ { "TOCLIENT_ITEMDEF", 0, true }, // 0x3D
+ null_command_factory, // 0x3E
+ { "TOCLIENT_PLAY_SOUND", 0, true }, // 0x3f (may be sent as unrel too)
+ { "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
+ null_command_factory, // 0x48
+ { "TOCLIENT_HUDADD", 1, true }, // 0x49
+ { "TOCLIENT_HUDRM", 1, true }, // 0x4a
+ { "TOCLIENT_HUDCHANGE", 1, true }, // 0x4b
+ { "TOCLIENT_HUD_SET_FLAGS", 1, true }, // 0x4c
+ { "TOCLIENT_HUD_SET_PARAM", 1, 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
+ { "TOCLIENT_DELETE_PARTICLESPAWNER", 0, true }, // 0x53
+ { "TOCLIENT_CLOUD_PARAMS", 0, true }, // 0x54
+ { "TOCLIENT_FADE_SOUND", 0, true }, // 0x55
+ { "TOCLIENT_UPDATE_PLAYER_LIST", 0, true }, // 0x56
+ { "TOCLIENT_MODCHANNEL_MSG", 0, true }, // 0x57
+ { "TOCLIENT_MODCHANNEL_SIGNAL", 0, true }, // 0x58
+ { "TOCLIENT_NODEMETA_CHANGED", 0, true }, // 0x59
+ { "TOCLIENT_SET_SUN", 0, true }, // 0x5a
+ { "TOCLIENT_SET_MOON", 0, true }, // 0x5b
+ { "TOCLIENT_SET_STARS", 0, true }, // 0x5c
+ null_command_factory, // 0x5d
+ null_command_factory, // 0x5e
+ null_command_factory, // 0x5f
+ { "TOSERVER_SRP_BYTES_S_B", 0, true }, // 0x60
+ { "TOCLIENT_FORMSPEC_PREPEND", 0, true }, // 0x61
};
diff --git a/src/network/serveropcodes.h b/src/network/serveropcodes.h
index 9d3c1ab9e..6df09d5ef 100644
--- a/src/network/serveropcodes.h
+++ b/src/network/serveropcodes.h
@@ -25,8 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
class NetworkPacket;
-enum ToServerConnectionState
-{
+enum ToServerConnectionState {
TOSERVER_STATE_NOT_CONNECTED,
TOSERVER_STATE_STARTUP,
TOSERVER_STATE_INGAME,
@@ -34,14 +33,14 @@ enum ToServerConnectionState
};
struct ToServerCommandHandler
{
- const std::string name;
- ToServerConnectionState state;
- void (Server::*handler)(NetworkPacket *pkt);
+ const std::string name;
+ ToServerConnectionState state;
+ void (Server::*handler)(NetworkPacket* pkt);
};
struct ClientCommandFactory
{
- const char *name;
+ const char* name;
u8 channel;
bool reliable;
};
diff --git a/src/network/serverpackethandler.cpp b/src/network/serverpackethandler.cpp
index 2b4c5c718..b3008bb50 100644
--- a/src/network/serverpackethandler.cpp
+++ b/src/network/serverpackethandler.cpp
@@ -41,16 +41,16 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "util/serialize.h"
#include "util/srp.h"
-void Server::handleCommand_Deprecated(NetworkPacket *pkt)
+void Server::handleCommand_Deprecated(NetworkPacket* pkt)
{
infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
- << " not supported anymore" << std::endl;
+ << " not supported anymore" << std::endl;
}
-void Server::handleCommand_Init(NetworkPacket *pkt)
+void Server::handleCommand_Init(NetworkPacket* pkt)
{
- if (pkt->getSize() < 1)
+ if(pkt->getSize() < 1)
return;
session_t peer_id = pkt->getPeerId();
@@ -60,33 +60,34 @@ void Server::handleCommand_Init(NetworkPacket *pkt)
try {
Address address = getPeerAddress(peer_id);
addr_s = address.serializeString();
- } catch (con::PeerNotFoundException &e) {
+ }
+ catch (con::PeerNotFoundException &e) {
/*
* no peer for this packet found
* most common reason is peer timeout, e.g. peer didn't
* respond for some time, your server was overloaded or
* things like that.
*/
- infostream << "Server::ProcessData(): Canceling: peer " << peer_id
- << " not found" << std::endl;
+ infostream << "Server::ProcessData(): Canceling: peer " << peer_id <<
+ " not found" << std::endl;
return;
}
// If net_proto_version is set, this client has already been handled
if (client->getState() > CS_Created) {
- verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
- << addr_s << " (peer_id=" << peer_id << ")" << std::endl;
+ verbosestream << "Server: Ignoring multiple TOSERVER_INITs from " <<
+ addr_s << " (peer_id=" << peer_id << ")" << std::endl;
return;
}
- verbosestream << "Server: Got TOSERVER_INIT from " << addr_s
- << " (peer_id=" << peer_id << ")" << std::endl;
+ verbosestream << "Server: Got TOSERVER_INIT from " << addr_s <<
+ " (peer_id=" << peer_id << ")" << std::endl;
// Do not allow multiple players in simple singleplayer mode.
// This isn't a perfect way to do it, but will suffice for now
if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
- infostream << "Server: Not allowing another client (" << addr_s
- << ") to connect in simple singleplayer mode" << std::endl;
+ infostream << "Server: Not allowing another client (" << addr_s <<
+ ") to connect in simple singleplayer mode" << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_SINGLEPLAYER);
return;
}
@@ -99,8 +100,8 @@ void Server::handleCommand_Init(NetworkPacket *pkt)
u16 max_net_proto_version;
std::string playerName;
- *pkt >> client_max >> supp_compr_modes >> min_net_proto_version >>
- max_net_proto_version >> playerName;
+ *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
+ >> max_net_proto_version >> playerName;
u8 our_max = SER_FMT_VER_HIGHEST_READ;
// Use the highest version supported by both
@@ -110,8 +111,8 @@ void Server::handleCommand_Init(NetworkPacket *pkt)
depl_serial_v = SER_FMT_VER_INVALID;
if (depl_serial_v == SER_FMT_VER_INVALID) {
- actionstream << "Server: A mismatched client tried to connect from "
- << addr_s << " ser_fmt_max=" << (int)client_max << std::endl;
+ actionstream << "Server: A mismatched client tried to connect from " <<
+ addr_s << " ser_fmt_max=" << (int)client_max << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
return;
}
@@ -135,20 +136,18 @@ void Server::handleCommand_Init(NetworkPacket *pkt)
net_proto_version = max_net_proto_version;
}
- verbosestream << "Server: " << addr_s
- << ": Protocol version: min: " << min_net_proto_version
- << ", max: " << max_net_proto_version
- << ", chosen: " << net_proto_version << std::endl;
+ verbosestream << "Server: " << addr_s << ": Protocol version: min: "
+ << min_net_proto_version << ", max: " << max_net_proto_version
+ << ", chosen: " << net_proto_version << std::endl;
client->net_proto_version = net_proto_version;
if ((g_settings->getBool("strict_protocol_version_checking") &&
- net_proto_version != LATEST_PROTOCOL_VERSION) ||
+ net_proto_version != LATEST_PROTOCOL_VERSION) ||
net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
- actionstream << "Server: A mismatched client tried to connect from "
- << addr_s << " proto_max=" << (int)max_net_proto_version
- << std::endl;
+ actionstream << "Server: A mismatched client tried to connect from " <<
+ addr_s << " proto_max=" << (int)max_net_proto_version << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
return;
}
@@ -156,34 +155,32 @@ void Server::handleCommand_Init(NetworkPacket *pkt)
/*
Validate player name
*/
- const char *playername = playerName.c_str();
+ const char* playername = playerName.c_str();
size_t pns = playerName.size();
if (pns == 0 || pns > PLAYERNAME_SIZE) {
- actionstream << "Server: Player with "
- << ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty")
- << " name tried to connect from " << addr_s << std::endl;
+ actionstream << "Server: Player with " <<
+ ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty") <<
+ " name tried to connect from " << addr_s << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
return;
}
if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
actionstream << "Server: Player with an invalid name tried to connect "
- "from "
- << addr_s << std::endl;
+ "from " << addr_s << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
return;
}
m_clients.setPlayerName(peer_id, playername);
- // TODO (later) case insensitivity
+ //TODO (later) case insensitivity
std::string legacyPlayerNameCasing = playerName;
if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
actionstream << "Server: Player with the name \"singleplayer\" tried "
- "to connect from "
- << addr_s << std::endl;
+ "to connect from " << addr_s << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
return;
}
@@ -191,27 +188,26 @@ void Server::handleCommand_Init(NetworkPacket *pkt)
{
std::string reason;
if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
- actionstream << "Server: Player with the name \"" << playerName
- << "\" tried to connect from " << addr_s
- << " but it was disallowed for the following "
- "reason: "
- << reason << std::endl;
+ actionstream << "Server: Player with the name \"" << playerName <<
+ "\" tried to connect from " << addr_s <<
+ " but it was disallowed for the following reason: " << reason <<
+ std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
return;
}
}
- infostream << "Server: New connection: \"" << playerName << "\" from " << addr_s
- << " (peer_id=" << peer_id << ")" << std::endl;
+ infostream << "Server: New connection: \"" << playerName << "\" from " <<
+ addr_s << " (peer_id=" << peer_id << ")" << std::endl;
// Enforce user limit.
// Don't enforce for users that have some admin right or mod permits it.
- if (m_clients.isUserLimitReached() && playername != g_settings->get("name") &&
+ if (m_clients.isUserLimitReached() &&
+ playername != g_settings->get("name") &&
!m_script->can_bypass_userlimit(playername, addr_s)) {
- actionstream << "Server: " << playername << " tried to join from "
- << addr_s << ", but there are already max_users="
- << g_settings->getU16("max_users") << " players."
- << std::endl;
+ actionstream << "Server: " << playername << " tried to join from " <<
+ addr_s << ", but there are already max_users=" <<
+ g_settings->getU16("max_users") << " players." << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_TOO_MANY_USERS);
return;
}
@@ -232,11 +228,9 @@ void Server::handleCommand_Init(NetworkPacket *pkt)
auth_mechs |= AUTH_MECHANISM_SRP;
client->enc_pwd = encpwd;
} else {
- actionstream << "User " << playername
- << " tried to log in, "
- "but password field was invalid (unknown "
- "mechcode)."
- << std::endl;
+ actionstream << "User " << playername << " tried to log in, "
+ "but password field was invalid (unknown mechcode)." <<
+ std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
return;
}
@@ -244,10 +238,8 @@ void Server::handleCommand_Init(NetworkPacket *pkt)
auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
client->enc_pwd = encpwd;
} else {
- actionstream << "User " << playername
- << " tried to log in, but "
- "password field was invalid (invalid base64)."
- << std::endl;
+ actionstream << "User " << playername << " tried to log in, but "
+ "password field was invalid (invalid base64)." << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
return;
}
@@ -257,8 +249,7 @@ void Server::handleCommand_Init(NetworkPacket *pkt)
auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
} else {
// Take care of default passwords.
- client->enc_pwd = get_encoded_srp_verifier(
- playerName, default_password);
+ client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
auth_mechs |= AUTH_MECHANISM_SRP;
// Allocate player in db, but only on successful login.
client->create_player_on_auth_success = true;
@@ -269,15 +260,15 @@ void Server::handleCommand_Init(NetworkPacket *pkt)
Answer with a TOCLIENT_HELLO
*/
- verbosestream << "Sending TOCLIENT_HELLO with auth method field: " << auth_mechs
- << std::endl;
+ verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
+ << auth_mechs << std::endl;
- NetworkPacket resp_pkt(
- TOCLIENT_HELLO, 1 + 4 + legacyPlayerNameCasing.size(), peer_id);
+ NetworkPacket resp_pkt(TOCLIENT_HELLO,
+ 1 + 4 + legacyPlayerNameCasing.size(), peer_id);
u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
- resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version << auth_mechs
- << legacyPlayerNameCasing;
+ resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
+ << auth_mechs << legacyPlayerNameCasing;
Send(&resp_pkt);
@@ -287,7 +278,7 @@ void Server::handleCommand_Init(NetworkPacket *pkt)
m_clients.event(peer_id, CSE_Hello);
}
-void Server::handleCommand_Init2(NetworkPacket *pkt)
+void Server::handleCommand_Init2(NetworkPacket* pkt)
{
session_t peer_id = pkt->getPeerId();
verbosestream << "Server: Got TOSERVER_INIT2 from " << peer_id << std::endl;
@@ -303,8 +294,8 @@ void Server::handleCommand_Init2(NetworkPacket *pkt)
Send some initialization data
*/
- infostream << "Server: Sending content to " << getPlayerName(peer_id)
- << std::endl;
+ infostream << "Server: Sending content to " << getPlayerName(peer_id) <<
+ std::endl;
// Send item definitions
SendItemDef(peer_id, m_itemdef, protocol_version);
@@ -344,15 +335,13 @@ void Server::handleCommand_Init2(NetworkPacket *pkt)
// Warnings about protocol version can be issued here
if (client->net_proto_version < LATEST_PROTOCOL_VERSION) {
- SendChatMessage(peer_id,
- ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
- L"# Server: WARNING: YOUR CLIENT'S "
- L"VERSION MAY NOT BE FULLY COMPATIBLE "
- L"WITH THIS SERVER!"));
+ SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
+ L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
+ L"WITH THIS SERVER!"));
}
}
-void Server::handleCommand_RequestMedia(NetworkPacket *pkt)
+void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
{
std::vector<std::string> tosend;
u16 numfiles;
@@ -360,8 +349,8 @@ void Server::handleCommand_RequestMedia(NetworkPacket *pkt)
*pkt >> numfiles;
session_t peer_id = pkt->getPeerId();
- infostream << "Sending " << numfiles << " files to " << getPlayerName(peer_id)
- << std::endl;
+ infostream << "Sending " << numfiles << " files to " <<
+ getPlayerName(peer_id) << std::endl;
verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
for (u16 i = 0; i < numfiles; i++) {
@@ -370,31 +359,30 @@ void Server::handleCommand_RequestMedia(NetworkPacket *pkt)
*pkt >> name;
tosend.push_back(name);
- verbosestream << "TOSERVER_REQUEST_MEDIA: requested file " << name
- << std::endl;
+ verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
+ << name << std::endl;
}
sendRequestedMedia(peer_id, tosend);
}
-void Server::handleCommand_ClientReady(NetworkPacket *pkt)
+void Server::handleCommand_ClientReady(NetworkPacket* pkt)
{
session_t peer_id = pkt->getPeerId();
- PlayerSAO *playersao = StageTwoClientInit(peer_id);
+ PlayerSAO* playersao = StageTwoClientInit(peer_id);
if (playersao == NULL) {
errorstream << "TOSERVER_CLIENT_READY stage 2 client init failed "
- "peer_id="
- << peer_id << std::endl;
+ "peer_id=" << peer_id << std::endl;
DisconnectPeer(peer_id);
return;
}
+
if (pkt->getSize() < 8) {
errorstream << "TOSERVER_CLIENT_READY client sent inconsistent data, "
- "disconnecting peer_id: "
- << peer_id << std::endl;
+ "disconnecting peer_id: " << peer_id << std::endl;
DisconnectPeer(peer_id);
return;
}
@@ -403,29 +391,28 @@ void Server::handleCommand_ClientReady(NetworkPacket *pkt)
std::string full_ver;
*pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
- m_clients.setClientVersion(peer_id, major_ver, minor_ver, patch_ver, full_ver);
+ m_clients.setClientVersion(peer_id, major_ver, minor_ver, patch_ver,
+ full_ver);
if (pkt->getRemainingBytes() >= 2)
*pkt >> playersao->getPlayer()->formspec_version;
const std::vector<std::string> &players = m_clients.getPlayerNames();
NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
- list_pkt << (u8)PLAYER_LIST_INIT << (u16)players.size();
- for (const std::string &player : players) {
- list_pkt << player;
+ list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
+ for (const std::string &player: players) {
+ list_pkt << player;
}
m_clients.send(peer_id, 0, &list_pkt, true);
NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
// (u16) 1 + std::string represents a pseudo vector serialization representation
- notice_pkt << (u8)PLAYER_LIST_ADD << (u16)1
- << std::string(playersao->getPlayer()->getName());
+ notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
m_clients.sendToAll(&notice_pkt);
m_clients.event(peer_id, CSE_SetClientReady);
s64 last_login;
- m_script->getAuth(
- playersao->getPlayer()->getName(), nullptr, nullptr, &last_login);
+ m_script->getAuth(playersao->getPlayer()->getName(), nullptr, nullptr, &last_login);
m_script->on_joinplayer(playersao, last_login);
// Send shutdown timer if shutdown has been scheduled
@@ -434,7 +421,7 @@ void Server::handleCommand_ClientReady(NetworkPacket *pkt)
}
}
-void Server::handleCommand_GotBlocks(NetworkPacket *pkt)
+void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
{
if (pkt->getSize() < 1)
return;
@@ -453,7 +440,8 @@ void Server::handleCommand_GotBlocks(NetworkPacket *pkt)
RemoteClient *client = getClient(pkt->getPeerId());
if ((s16)pkt->getSize() < 1 + (int)count * 6) {
- throw con::InvalidIncomingDataException("GOTBLOCKS length is too short");
+ throw con::InvalidIncomingDataException
+ ("GOTBLOCKS length is too short");
}
for (u16 i = 0; i < count; i++) {
@@ -463,8 +451,8 @@ void Server::handleCommand_GotBlocks(NetworkPacket *pkt)
}
}
-void Server::process_PlayerPos(
- RemotePlayer *player, PlayerSAO *playersao, NetworkPacket *pkt)
+void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
+ NetworkPacket *pkt)
{
if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
return;
@@ -522,22 +510,23 @@ void Server::process_PlayerPos(
}
}
-void Server::handleCommand_PlayerPos(NetworkPacket *pkt)
+void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
{
session_t peer_id = pkt->getPeerId();
RemotePlayer *player = m_env->getPlayer(peer_id);
if (player == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player for peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player object for "
- "peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player object for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
@@ -545,14 +534,14 @@ void Server::handleCommand_PlayerPos(NetworkPacket *pkt)
// If player is dead we don't care of this packet
if (playersao->isDead()) {
verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
- << " is dead. Ignoring packet";
+ << " is dead. Ignoring packet";
return;
}
process_PlayerPos(player, playersao, pkt);
}
-void Server::handleCommand_DeletedBlocks(NetworkPacket *pkt)
+void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
{
if (pkt->getSize() < 1)
return;
@@ -571,8 +560,8 @@ void Server::handleCommand_DeletedBlocks(NetworkPacket *pkt)
RemoteClient *client = getClient(pkt->getPeerId());
if ((s16)pkt->getSize() < 1 + (int)count * 6) {
- throw con::InvalidIncomingDataException(
- "DELETEDBLOCKS length is too short");
+ throw con::InvalidIncomingDataException
+ ("DELETEDBLOCKS length is too short");
}
for (u16 i = 0; i < count; i++) {
@@ -582,42 +571,45 @@ void Server::handleCommand_DeletedBlocks(NetworkPacket *pkt)
}
}
-void Server::handleCommand_InventoryAction(NetworkPacket *pkt)
+void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
{
session_t peer_id = pkt->getPeerId();
RemotePlayer *player = m_env->getPlayer(peer_id);
if (player == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player for peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player object for "
- "peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player object for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
// Strip command and create a stream
std::string datastring(pkt->getString(0), pkt->getSize());
- verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring << std::endl;
+ verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
+ << std::endl;
std::istringstream is(datastring, std::ios_base::binary);
// Create an action
InventoryAction *a = InventoryAction::deSerialize(is);
if (!a) {
infostream << "TOSERVER_INVENTORY_ACTION: "
- << "InventoryAction::deSerialize() returned NULL" << std::endl;
+ << "InventoryAction::deSerialize() returned NULL"
+ << std::endl;
return;
}
// If something goes wrong, this player is to blame
- RollbackScopeActor rollback_scope(
- m_rollback, std::string("player:") + player->getName());
+ RollbackScopeActor rollback_scope(m_rollback,
+ std::string("player:")+player->getName());
/*
Note: Always set inventory not sent, to repair cases
@@ -628,7 +620,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt)
Handle restrictions and special cases of the move action
*/
if (a->getType() == IAction::Move) {
- IMoveAction *ma = (IMoveAction *)a;
+ IMoveAction *ma = (IMoveAction*)a;
ma->from_inv.applyCurrentPlayer(player->getName());
ma->to_inv.applyCurrentPlayer(player->getName());
@@ -638,19 +630,19 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt)
m_inventory_mgr->setInventoryModified(ma->to_inv);
bool from_inv_is_current_player =
- (ma->from_inv.type == InventoryLocation::PLAYER) &&
- (ma->from_inv.name == player->getName());
+ (ma->from_inv.type == InventoryLocation::PLAYER) &&
+ (ma->from_inv.name == player->getName());
bool to_inv_is_current_player =
- (ma->to_inv.type == InventoryLocation::PLAYER) &&
- (ma->to_inv.name == player->getName());
+ (ma->to_inv.type == InventoryLocation::PLAYER) &&
+ (ma->to_inv.name == player->getName());
- InventoryLocation *remote =
- from_inv_is_current_player ? &ma->to_inv : &ma->from_inv;
+ InventoryLocation *remote = from_inv_is_current_player ?
+ &ma->to_inv : &ma->from_inv;
// Check for out-of-range interaction
if (remote->type == InventoryLocation::NODEMETA) {
- v3f node_pos = intToFloat(remote->p, BS);
+ v3f node_pos = intToFloat(remote->p, BS);
v3f player_pos = player->getPlayerSAO()->getEyePosition();
f32 d = player_pos.getDistanceFrom(node_pos);
if (!checkInteractDistance(player, d, "inventory"))
@@ -662,9 +654,9 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt)
*/
if (ma->from_list == "craftpreview") {
infostream << "Ignoring IMoveAction from "
- << (ma->from_inv.dump()) << ":" << ma->from_list
- << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
- << " because src is " << ma->from_list << std::endl;
+ << (ma->from_inv.dump()) << ":" << ma->from_list
+ << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
+ << " because src is " << ma->from_list << std::endl;
delete a;
return;
}
@@ -674,9 +666,9 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt)
*/
if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
infostream << "Ignoring IMoveAction from "
- << (ma->from_inv.dump()) << ":" << ma->from_list
- << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
- << " because dst is " << ma->to_list << std::endl;
+ << (ma->from_inv.dump()) << ":" << ma->from_list
+ << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
+ << " because dst is " << ma->to_list << std::endl;
delete a;
return;
}
@@ -685,9 +677,9 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt)
// if not allowed to interact
if (!checkPriv(player->getName(), "interact") &&
(!from_inv_is_current_player ||
- !to_inv_is_current_player)) {
+ !to_inv_is_current_player)) {
infostream << "Cannot move outside of player's inventory: "
- << "No interact privilege" << std::endl;
+ << "No interact privilege" << std::endl;
delete a;
return;
}
@@ -696,7 +688,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt)
Handle restrictions and special cases of the drop action
*/
else if (a->getType() == IAction::Drop) {
- IDropAction *da = (IDropAction *)a;
+ IDropAction *da = (IDropAction*)a;
da->from_inv.applyCurrentPlayer(player->getName());
@@ -707,8 +699,8 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt)
*/
if (da->from_list == "craftpreview") {
infostream << "Ignoring IDropAction from "
- << (da->from_inv.dump()) << ":" << da->from_list
- << " because src is " << da->from_list << std::endl;
+ << (da->from_inv.dump()) << ":" << da->from_list
+ << " because src is " << da->from_list << std::endl;
delete a;
return;
}
@@ -722,8 +714,8 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt)
// Disallow dropping items if dead
if (playersao->isDead()) {
infostream << "Ignoring IDropAction from "
- << (da->from_inv.dump()) << ":" << da->from_list
- << " because player is dead." << std::endl;
+ << (da->from_inv.dump()) << ":" << da->from_list
+ << " because player is dead." << std::endl;
delete a;
return;
}
@@ -732,20 +724,20 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt)
Handle restrictions and special cases of the craft action
*/
else if (a->getType() == IAction::Craft) {
- ICraftAction *ca = (ICraftAction *)a;
+ ICraftAction *ca = (ICraftAction*)a;
ca->craft_inv.applyCurrentPlayer(player->getName());
m_inventory_mgr->setInventoryModified(ca->craft_inv);
- // bool craft_inv_is_current_player =
+ //bool craft_inv_is_current_player =
// (ca->craft_inv.type == InventoryLocation::PLAYER) &&
// (ca->craft_inv.name == player->getName());
// Disallow crafting if not allowed to interact
if (!checkPriv(player->getName(), "interact")) {
infostream << "Cannot craft: "
- << "No interact privilege" << std::endl;
+ << "No interact privilege" << std::endl;
delete a;
return;
}
@@ -757,7 +749,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt)
delete a;
}
-void Server::handleCommand_ChatMessage(NetworkPacket *pkt)
+void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
{
/*
u16 command
@@ -778,8 +770,9 @@ void Server::handleCommand_ChatMessage(NetworkPacket *pkt)
session_t peer_id = pkt->getPeerId();
RemotePlayer *player = m_env->getPlayer(peer_id);
if (player == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player for peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
@@ -792,11 +785,11 @@ void Server::handleCommand_ChatMessage(NetworkPacket *pkt)
if (!answer_to_sender.empty()) {
// Send the answer to sender
SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_NORMAL,
- answer_to_sender, wname));
+ answer_to_sender, wname));
}
}
-void Server::handleCommand_Damage(NetworkPacket *pkt)
+void Server::handleCommand_Damage(NetworkPacket* pkt)
{
u16 damage;
@@ -806,17 +799,18 @@ void Server::handleCommand_Damage(NetworkPacket *pkt)
RemotePlayer *player = m_env->getPlayer(peer_id);
if (player == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player for peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player object for "
- "peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player object for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
@@ -824,15 +818,14 @@ void Server::handleCommand_Damage(NetworkPacket *pkt)
if (!playersao->isImmortal()) {
if (playersao->isDead()) {
verbosestream << "Server::ProcessData(): Info: "
- "Ignoring damage as player "
- << player->getName() << " is already dead."
- << std::endl;
+ "Ignoring damage as player " << player->getName()
+ << " is already dead." << std::endl;
return;
}
- actionstream << player->getName() << " damaged by " << (int)damage
- << " hp at " << PP(playersao->getBasePosition() / BS)
- << std::endl;
+ actionstream << player->getName() << " damaged by "
+ << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
+ << std::endl;
PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
@@ -840,7 +833,7 @@ void Server::handleCommand_Damage(NetworkPacket *pkt)
}
}
-void Server::handleCommand_PlayerItem(NetworkPacket *pkt)
+void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
{
if (pkt->getSize() < 2)
return;
@@ -849,17 +842,18 @@ void Server::handleCommand_PlayerItem(NetworkPacket *pkt)
RemotePlayer *player = m_env->getPlayer(peer_id);
if (player == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player for peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player object for "
- "peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player object for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
@@ -871,13 +865,14 @@ void Server::handleCommand_PlayerItem(NetworkPacket *pkt)
playersao->getPlayer()->setWieldIndex(item);
}
-void Server::handleCommand_Respawn(NetworkPacket *pkt)
+void Server::handleCommand_Respawn(NetworkPacket* pkt)
{
session_t peer_id = pkt->getPeerId();
RemotePlayer *player = m_env->getPlayer(peer_id);
if (player == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player for peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
@@ -891,27 +886,27 @@ void Server::handleCommand_Respawn(NetworkPacket *pkt)
RespawnPlayer(peer_id);
actionstream << player->getName() << " respawns at "
- << PP(playersao->getBasePosition() / BS) << std::endl;
+ << PP(playersao->getBasePosition() / BS) << std::endl;
// ActiveObject is added to environment in AsyncRunStep after
// the previous addition has been successfully removed
}
-bool Server::checkInteractDistance(
- RemotePlayer *player, const f32 d, const std::string &what)
+bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
{
ItemStack selected_item, hand_item;
player->getWieldedItem(&selected_item, &hand_item);
f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
- hand_item.getDefinition(m_itemdef));
+ hand_item.getDefinition(m_itemdef));
// Cube diagonal * 1.5 for maximal supported node extents:
// sqrt(3) * 1.5 ≅ 2.6
if (d > max_d + 2.6f * BS) {
- actionstream << "Player " << player->getName() << " tried to access "
- << what << " from too far: "
- << "d=" << d << ", max_d=" << max_d << "; ignoring."
- << std::endl;
+ actionstream << "Player " << player->getName()
+ << " tried to access " << what
+ << " from too far: "
+ << "d=" << d << ", max_d=" << max_d
+ << "; ignoring." << std::endl;
// Call callbacks
m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
return false;
@@ -940,32 +935,32 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
PointedThing pointed;
pointed.deSerialize(tmp_is);
- verbosestream << "TOSERVER_INTERACT: action=" << (int)action
- << ", item=" << item_i << ", pointed=" << pointed.dump()
- << std::endl;
+ verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
+ << item_i << ", pointed=" << pointed.dump() << std::endl;
session_t peer_id = pkt->getPeerId();
RemotePlayer *player = m_env->getPlayer(peer_id);
if (player == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player for peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player object for "
- "peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player object for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
if (playersao->isDead()) {
actionstream << "Server: " << player->getName()
- << " tried to interact while dead; ignoring." << std::endl;
+ << " tried to interact while dead; ignoring." << std::endl;
if (pointed.type == POINTEDTHING_NODE) {
// Re-send block to revert change on client-side
RemoteClient *client = getClient(peer_id);
@@ -994,10 +989,10 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
pointed_object = m_env->getActiveObject(pointed.object_id);
if (pointed_object == NULL) {
verbosestream << "TOSERVER_INTERACT: "
- "pointed object is NULL"
- << std::endl;
+ "pointed object is NULL" << std::endl;
return;
}
+
}
v3f pointed_pos_under = player_pos;
@@ -1005,7 +1000,8 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
if (pointed.type == POINTEDTHING_NODE) {
pointed_pos_under = intToFloat(p_under, BS);
pointed_pos_above = intToFloat(p_above, BS);
- } else if (pointed.type == POINTEDTHING_OBJECT) {
+ }
+ else if (pointed.type == POINTEDTHING_OBJECT) {
pointed_pos_under = pointed_object->getBasePosition();
pointed_pos_above = pointed_pos_under;
}
@@ -1014,22 +1010,19 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
Make sure the player is allowed to do it
*/
if (!checkPriv(player->getName(), "interact")) {
- actionstream << player->getName() << " attempted to interact with "
- << pointed.dump() << " without 'interact' privilege"
- << std::endl;
+ actionstream << player->getName() << " attempted to interact with " <<
+ pointed.dump() << " without 'interact' privilege" << std::endl;
// Re-send block to revert change on client-side
RemoteClient *client = getClient(peer_id);
// Digging completed -> under
if (action == INTERACT_DIGGING_COMPLETED) {
- v3s16 blockpos = getNodeBlockPos(
- floatToInt(pointed_pos_under, BS));
+ v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
client->SetBlockNotSent(blockpos);
}
// Placement -> above
else if (action == INTERACT_PLACE) {
- v3s16 blockpos = getNodeBlockPos(
- floatToInt(pointed_pos_above, BS));
+ v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
client->SetBlockNotSent(blockpos);
}
return;
@@ -1043,15 +1036,14 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
!g_settings->getBool("disable_anticheat");
if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
- action == INTERACT_PLACE || action == INTERACT_USE) &&
+ action == INTERACT_PLACE || action == INTERACT_USE) &&
enable_anticheat && !isSingleplayer()) {
float d = playersao->getEyePosition().getDistanceFrom(pointed_pos_under);
if (!checkInteractDistance(player, d, pointed.dump())) {
// Re-send block to revert change on client-side
RemoteClient *client = getClient(peer_id);
- v3s16 blockpos = getNodeBlockPos(
- floatToInt(pointed_pos_under, BS));
+ v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
client->SetBlockNotSent(blockpos);
return;
}
@@ -1060,8 +1052,8 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
/*
If something goes wrong, this player is to blame
*/
- RollbackScopeActor rollback_scope(
- m_rollback, std::string("player:") + player->getName());
+ RollbackScopeActor rollback_scope(m_rollback,
+ std::string("player:")+player->getName());
/*
0: start digging or punch object
@@ -1074,10 +1066,9 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
n = m_env->getMap().getNode(p_under, &pos_ok);
if (!pos_ok) {
infostream << "Server: Not punching: Node not found. "
- "Adding block to emerge queue."
- << std::endl;
- m_emerge->enqueueBlockEmerge(
- peer_id, getNodeBlockPos(p_above), false);
+ "Adding block to emerge queue." << std::endl;
+ m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above),
+ false);
}
if (n.getContent() != CONTENT_IGNORE)
@@ -1085,27 +1076,27 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
// Cheat prevention
playersao->noCheatDigStart(p_under);
- } else if (pointed.type == POINTEDTHING_OBJECT) {
+ }
+ else if (pointed.type == POINTEDTHING_OBJECT) {
// Skip if object can't be interacted with anymore
if (pointed_object->isGone())
return;
ItemStack selected_item, hand_item;
- ItemStack tool_item = playersao->getWieldedItem(
- &selected_item, &hand_item);
+ ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
ToolCapabilities toolcap =
tool_item.getToolCapabilities(m_itemdef);
v3f dir = (pointed_object->getBasePosition() -
- (playersao->getBasePosition() +
- playersao->getEyeOffset()))
- .normalize();
- float time_from_last_punch = playersao->resetTimeFromLastPunch();
+ (playersao->getBasePosition() + playersao->getEyeOffset())
+ ).normalize();
+ float time_from_last_punch =
+ playersao->resetTimeFromLastPunch();
u16 src_original_hp = pointed_object->getHP();
u16 dst_origin_hp = playersao->getHP();
- u16 wear = pointed_object->punch(
- dir, &toolcap, playersao, time_from_last_punch);
+ u16 wear = pointed_object->punch(dir, &toolcap, playersao,
+ time_from_last_punch);
// Callback may have changed item, so get it again
playersao->getWieldedItem(&selected_item);
@@ -1115,22 +1106,15 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
// If the object is a player and its HP changed
if (src_original_hp != pointed_object->getHP() &&
- pointed_object->getType() ==
- ACTIVEOBJECT_TYPE_PLAYER) {
+ pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
SendPlayerHPOrDie((PlayerSAO *)pointed_object,
- PlayerHPChangeReason(
- PlayerHPChangeReason::
- PLAYER_PUNCH,
- playersao));
+ PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
}
// If the puncher is a player and its HP changed
if (dst_origin_hp != playersao->getHP())
SendPlayerHPOrDie(playersao,
- PlayerHPChangeReason(
- PlayerHPChangeReason::
- PLAYER_PUNCH,
- pointed_object));
+ PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
}
} // action == INTERACT_START_DIGGING
@@ -1150,12 +1134,10 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
bool pos_ok;
MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
if (!pos_ok) {
- infostream << "Server: Not finishing digging: Node not "
- "found. "
- "Adding block to emerge queue."
- << std::endl;
- m_emerge->enqueueBlockEmerge(
- peer_id, getNodeBlockPos(p_above), false);
+ infostream << "Server: Not finishing digging: Node not found. "
+ "Adding block to emerge queue." << std::endl;
+ m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above),
+ false);
}
/* Cheat prevention */
@@ -1167,39 +1149,33 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
// If player didn't start digging this, ignore dig
if (nocheat_p != p_under) {
infostream << "Server: " << player->getName()
- << " started digging " << PP(nocheat_p)
- << " and completed digging "
- << PP(p_under) << "; not digging."
- << std::endl;
+ << " started digging "
+ << PP(nocheat_p) << " and completed digging "
+ << PP(p_under) << "; not digging." << std::endl;
is_valid_dig = false;
// Call callbacks
- m_script->on_cheat(playersao,
- "finished_unknown_dig");
+ m_script->on_cheat(playersao, "finished_unknown_dig");
}
// Get player's wielded item
// See also: Game::handleDigging
ItemStack selected_item, hand_item;
- playersao->getPlayer()->getWieldedItem(
- &selected_item, &hand_item);
+ playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
// Get diggability and expected digging time
DigParams params = getDigParams(m_nodedef->get(n).groups,
- &selected_item.getToolCapabilities(
- m_itemdef));
+ &selected_item.getToolCapabilities(m_itemdef));
// If can't dig, try hand
if (!params.diggable) {
params = getDigParams(m_nodedef->get(n).groups,
- &hand_item.getToolCapabilities(
- m_itemdef));
+ &hand_item.getToolCapabilities(m_itemdef));
}
// If can't dig, ignore dig
if (!params.diggable) {
infostream << "Server: " << player->getName()
- << " completed digging " << PP(p_under)
- << ", which is not diggable with "
- "tool; not digging."
- << std::endl;
+ << " completed digging " << PP(p_under)
+ << ", which is not diggable with tool; not digging."
+ << std::endl;
is_valid_dig = false;
// Call callbacks
m_script->on_cheat(playersao, "dug_unbreakable");
@@ -1210,10 +1186,9 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
// Well not our problem then
}
// Clean and long dig
- else if (params.time > 2.0 &&
- nocheat_t * 1.2 > params.time) {
- // All is good, but grab time from pool; don't
- // care if it's actually available
+ else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
+ // All is good, but grab time from pool; don't care if
+ // it's actually available
playersao->getDigPool().grab(params.time);
}
// Short or laggy dig
@@ -1224,9 +1199,8 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
// Dig not possible
else {
infostream << "Server: " << player->getName()
- << " completed digging " << PP(p_under)
- << "too fast; not digging."
- << std::endl;
+ << " completed digging " << PP(p_under)
+ << "too fast; not digging." << std::endl;
is_valid_dig = false;
// Call callbacks
m_script->on_cheat(playersao, "dug_too_fast");
@@ -1238,15 +1212,14 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
m_script->node_on_dig(p_under, n, playersao);
- v3s16 blockpos = getNodeBlockPos(
- floatToInt(pointed_pos_under, BS));
+ v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
RemoteClient *client = getClient(peer_id);
// Send unusual result (that is, node not being removed)
- if (m_env->getMap().getNode(p_under).getContent() !=
- CONTENT_AIR) {
+ if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR) {
// Re-send block to revert change on client-side
client->SetBlockNotSent(blockpos);
- } else {
+ }
+ else {
client->ResendBlockIfOnWire(blockpos);
}
}
@@ -1272,19 +1245,20 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
return;
actionstream << player->getName() << " right-clicks object "
- << pointed.object_id << ": "
- << pointed_object->getDescription() << std::endl;
+ << pointed.object_id << ": "
+ << pointed_object->getDescription() << std::endl;
// Do stuff
if (m_script->item_OnSecondaryUse(
- selected_item, playersao, pointed)) {
+ selected_item, playersao, pointed)) {
if (playersao->setWieldedItem(selected_item)) {
SendInventory(playersao, true);
}
}
pointed_object->rightClick(playersao);
- } else if (m_script->item_OnPlace(selected_item, playersao, pointed)) {
+ } else if (m_script->item_OnPlace(
+ selected_item, playersao, pointed)) {
// Placement was handled in lua
// Apply returned ItemStack
@@ -1298,13 +1272,13 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
RemoteClient *client = getClient(peer_id);
v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
- if (!selected_item.getDefinition(m_itemdef)
- .node_placement_prediction.empty()) {
+ if (!selected_item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
client->SetBlockNotSent(blockpos);
if (blockpos2 != blockpos) {
client->SetBlockNotSent(blockpos2);
}
- } else {
+ }
+ else {
client->ResendBlockIfOnWire(blockpos);
if (blockpos2 != blockpos) {
client->ResendBlockIfOnWire(blockpos2);
@@ -1320,9 +1294,10 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
playersao->getWieldedItem(&selected_item, nullptr);
actionstream << player->getName() << " uses " << selected_item.name
- << ", pointing at " << pointed.dump() << std::endl;
+ << ", pointing at " << pointed.dump() << std::endl;
- if (m_script->item_OnUse(selected_item, playersao, pointed)) {
+ if (m_script->item_OnUse(
+ selected_item, playersao, pointed)) {
// Apply returned ItemStack
if (playersao->setWieldedItem(selected_item)) {
SendInventory(playersao, true);
@@ -1338,27 +1313,30 @@ void Server::handleCommand_Interact(NetworkPacket *pkt)
ItemStack selected_item;
playersao->getWieldedItem(&selected_item, nullptr);
- actionstream << player->getName() << " activates " << selected_item.name
- << std::endl;
+ actionstream << player->getName() << " activates "
+ << selected_item.name << std::endl;
pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
- if (m_script->item_OnSecondaryUse(selected_item, playersao, pointed)) {
+ if (m_script->item_OnSecondaryUse(
+ selected_item, playersao, pointed)) {
if (playersao->setWieldedItem(selected_item)) {
SendInventory(playersao, true);
}
}
} // action == INTERACT_ACTIVATE
+
/*
Catch invalid actions
*/
else {
- warningstream << "Server: Invalid action " << action << std::endl;
+ warningstream << "Server: Invalid action "
+ << action << std::endl;
}
}
-void Server::handleCommand_RemovedSounds(NetworkPacket *pkt)
+void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
{
u16 num;
*pkt >> num;
@@ -1368,7 +1346,7 @@ void Server::handleCommand_RemovedSounds(NetworkPacket *pkt)
*pkt >> id;
std::unordered_map<s32, ServerPlayingSound>::iterator i =
- m_playing_sounds.find(id);
+ m_playing_sounds.find(id);
if (i == m_playing_sounds.end())
continue;
@@ -1379,7 +1357,7 @@ void Server::handleCommand_RemovedSounds(NetworkPacket *pkt)
}
}
-void Server::handleCommand_NodeMetaFields(NetworkPacket *pkt)
+void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
{
v3s16 p;
std::string formname;
@@ -1398,24 +1376,25 @@ void Server::handleCommand_NodeMetaFields(NetworkPacket *pkt)
RemotePlayer *player = m_env->getPlayer(peer_id);
if (player == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player for peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player object for "
- "peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player object for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
// If something goes wrong, this player is to blame
- RollbackScopeActor rollback_scope(
- m_rollback, std::string("player:") + player->getName());
+ RollbackScopeActor rollback_scope(m_rollback,
+ std::string("player:")+player->getName());
// Check the target node for rollback data; leave others unnoticed
RollbackNode rn_old(&m_env->getMap(), p, this);
@@ -1431,7 +1410,7 @@ void Server::handleCommand_NodeMetaFields(NetworkPacket *pkt)
}
}
-void Server::handleCommand_InventoryFields(NetworkPacket *pkt)
+void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
{
std::string client_formspec_name;
u16 num;
@@ -1449,17 +1428,18 @@ void Server::handleCommand_InventoryFields(NetworkPacket *pkt)
RemotePlayer *player = m_env->getPlayer(peer_id);
if (player == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player for peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
- errorstream << "Server::ProcessData(): Canceling: No player object for "
- "peer_id="
- << peer_id << " disconnecting peer!" << std::endl;
+ errorstream <<
+ "Server::ProcessData(): Canceling: No player object for peer_id=" <<
+ peer_id << " disconnecting peer!" << std::endl;
DisconnectPeer(peer_id);
return;
}
@@ -1478,25 +1458,23 @@ void Server::handleCommand_InventoryFields(NetworkPacket *pkt)
if (it != fields.end() && it->second == "true")
m_formspec_state_data.erase(peer_state_iterator);
- m_script->on_playerReceiveFields(
- playersao, client_formspec_name, fields);
+ m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
return;
}
- actionstream << "'" << player->getName() << "' submitted formspec ('"
- << client_formspec_name
- << "') but the name of the formspec doesn't match the"
- " expected name ('"
- << server_formspec_name << "')";
+ actionstream << "'" << player->getName()
+ << "' submitted formspec ('" << client_formspec_name
+ << "') but the name of the formspec doesn't match the"
+ " expected name ('" << server_formspec_name << "')";
} else {
- actionstream << "'" << player->getName() << "' submitted formspec ('"
- << client_formspec_name
- << "') but server hasn't sent formspec to client";
+ actionstream << "'" << player->getName()
+ << "' submitted formspec ('" << client_formspec_name
+ << "') but server hasn't sent formspec to client";
}
actionstream << ", possible exploitation attempt" << std::endl;
}
-void Server::handleCommand_FirstSrp(NetworkPacket *pkt)
+void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
{
session_t peer_id = pkt->getPeerId();
RemoteClient *client = getClient(peer_id, CS_Invalid);
@@ -1513,24 +1491,23 @@ void Server::handleCommand_FirstSrp(NetworkPacket *pkt)
*pkt >> salt >> verification_key >> is_empty;
verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
- << ", with is_empty=" << (is_empty == 1) << std::endl;
+ << ", with is_empty=" << (is_empty == 1) << std::endl;
// Either this packet is sent because the user is new or to change the password
if (cstate == CS_HelloSent) {
if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
actionstream << "Server: Client from " << addr_s
- << " tried to set password without being "
- << "authenticated, or the username being new."
- << std::endl;
+ << " tried to set password without being "
+ << "authenticated, or the username being new." << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
}
- if (!isSingleplayer() && g_settings->getBool("disallow_empty_password") &&
+ if (!isSingleplayer() &&
+ g_settings->getBool("disallow_empty_password") &&
is_empty == 1) {
actionstream << "Server: " << playername
- << " supplied empty password from " << addr_s
- << std::endl;
+ << " supplied empty password from " << addr_s << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD);
return;
}
@@ -1544,11 +1521,9 @@ void Server::handleCommand_FirstSrp(NetworkPacket *pkt)
acceptAuth(peer_id, false);
} else {
if (cstate < CS_SudoMode) {
- infostream << "Server::ProcessData(): Ignoring "
- "TOSERVER_FIRST_SRP from "
- << addr_s << ": "
- << "Client has wrong state " << cstate << "."
- << std::endl;
+ infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
+ << addr_s << ": " << "Client has wrong state " << cstate << "."
+ << std::endl;
return;
}
m_clients.event(peer_id, CSE_SudoLeave);
@@ -1556,22 +1531,18 @@ void Server::handleCommand_FirstSrp(NetworkPacket *pkt)
bool success = m_script->setPassword(playername, pw_db_field);
if (success) {
actionstream << playername << " changes password" << std::endl;
- SendChatMessage(peer_id,
- ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
- L"Password change successful."));
+ SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
+ L"Password change successful."));
} else {
- actionstream << playername
- << " tries to change password but it fails"
- << std::endl;
- SendChatMessage(peer_id,
- ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
- L"Password change failed or "
- L"unavailable."));
+ actionstream << playername <<
+ " tries to change password but it fails" << std::endl;
+ SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
+ L"Password change failed or unavailable."));
}
}
}
-void Server::handleCommand_SrpBytesA(NetworkPacket *pkt)
+void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
{
session_t peer_id = pkt->getPeerId();
RemoteClient *client = getClient(peer_id, CS_Invalid);
@@ -1580,18 +1551,17 @@ void Server::handleCommand_SrpBytesA(NetworkPacket *pkt)
bool wantSudo = (cstate == CS_Active);
if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
- actionstream << "Server: got SRP _A packet in wrong state " << cstate
- << " from " << getPeerAddress(peer_id).serializeString()
- << ". Ignoring." << std::endl;
+ actionstream << "Server: got SRP _A packet in wrong state " << cstate <<
+ " from " << getPeerAddress(peer_id).serializeString() <<
+ ". Ignoring." << std::endl;
return;
}
if (client->chosen_mech != AUTH_MECHANISM_NONE) {
actionstream << "Server: got SRP _A packet, while auth is already "
- "going on with mech "
- << client->chosen_mech << " from "
- << getPeerAddress(peer_id).serializeString()
- << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
+ "going on with mech " << client->chosen_mech << " from " <<
+ getPeerAddress(peer_id).serializeString() <<
+ " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
if (wantSudo) {
DenySudoAccess(peer_id);
return;
@@ -1606,28 +1576,26 @@ void Server::handleCommand_SrpBytesA(NetworkPacket *pkt)
*pkt >> bytes_A >> based_on;
infostream << "Server: TOSERVER_SRP_BYTES_A received with "
- << "based_on=" << int(based_on) << " and len_A=" << bytes_A.length()
- << "." << std::endl;
+ << "based_on=" << int(based_on) << " and len_A="
+ << bytes_A.length() << "." << std::endl;
- AuthMechanism chosen = (based_on == 0) ? AUTH_MECHANISM_LEGACY_PASSWORD
- : AUTH_MECHANISM_SRP;
+ AuthMechanism chosen = (based_on == 0) ?
+ AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
if (wantSudo) {
if (!client->isSudoMechAllowed(chosen)) {
- actionstream << "Server: Player \"" << client->getName()
- << "\" at "
- << getPeerAddress(peer_id).serializeString()
- << " tried to change password using unallowed mech "
- << chosen << "." << std::endl;
+ actionstream << "Server: Player \"" << client->getName() <<
+ "\" at " << getPeerAddress(peer_id).serializeString() <<
+ " tried to change password using unallowed mech " << chosen <<
+ "." << std::endl;
DenySudoAccess(peer_id);
return;
}
} else {
if (!client->isMechAllowed(chosen)) {
- actionstream << "Server: Client tried to authenticate from "
- << getPeerAddress(peer_id).serializeString()
- << " using unallowed mech " << chosen << "."
- << std::endl;
+ actionstream << "Server: Client tried to authenticate from " <<
+ getPeerAddress(peer_id).serializeString() <<
+ " using unallowed mech " << chosen << "." << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
}
@@ -1640,15 +1608,13 @@ void Server::handleCommand_SrpBytesA(NetworkPacket *pkt)
if (based_on == 0) {
- generate_srp_verifier_and_salt(
- client->getName(), client->enc_pwd, &verifier, &salt);
+ generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
+ &verifier, &salt);
} else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
// Non-base64 errors should have been catched in the init handler
- actionstream << "Server: User " << client->getName()
- << " tried to log in, but srp verifier field was invalid "
- "(most likely "
- "invalid base64)."
- << std::endl;
+ actionstream << "Server: User " << client->getName() <<
+ " tried to log in, but srp verifier field was invalid (most likely "
+ "invalid base64)." << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
return;
}
@@ -1657,17 +1623,17 @@ void Server::handleCommand_SrpBytesA(NetworkPacket *pkt)
size_t len_B = 0;
client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
- client->getName().c_str(), (const unsigned char *)salt.c_str(),
- salt.size(), (const unsigned char *)verifier.c_str(),
- verifier.size(), (const unsigned char *)bytes_A.c_str(),
- bytes_A.size(), NULL, 0, (unsigned char **)&bytes_B, &len_B, NULL,
- NULL);
+ client->getName().c_str(),
+ (const unsigned char *) salt.c_str(), salt.size(),
+ (const unsigned char *) verifier.c_str(), verifier.size(),
+ (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
+ NULL, 0,
+ (unsigned char **) &bytes_B, &len_B, NULL, NULL);
if (!bytes_B) {
actionstream << "Server: User " << client->getName()
- << " tried to log in, SRP-6a safety check violated in _A "
- "handler."
- << std::endl;
+ << " tried to log in, SRP-6a safety check violated in _A handler."
+ << std::endl;
if (wantSudo) {
DenySudoAccess(peer_id);
return;
@@ -1682,7 +1648,7 @@ void Server::handleCommand_SrpBytesA(NetworkPacket *pkt)
Send(&resp_pkt);
}
-void Server::handleCommand_SrpBytesM(NetworkPacket *pkt)
+void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
{
session_t peer_id = pkt->getPeerId();
RemoteClient *client = getClient(peer_id, CS_Invalid);
@@ -1695,17 +1661,17 @@ void Server::handleCommand_SrpBytesM(NetworkPacket *pkt)
verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl;
if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
- actionstream << "Server: got SRP _M packet in wrong state " << cstate
- << " from " << addr_s << ". Ignoring." << std::endl;
+ actionstream << "Server: got SRP _M packet in wrong state "
+ << cstate << " from " << addr_s
+ << ". Ignoring." << std::endl;
return;
}
if (client->chosen_mech != AUTH_MECHANISM_SRP &&
client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
actionstream << "Server: got SRP _M packet, while auth"
- << "is going on with mech " << client->chosen_mech
- << " from " << addr_s << " (wantSudo=" << wantSudo
- << "). Denying." << std::endl;
+ << "is going on with mech " << client->chosen_mech << " from "
+ << addr_s << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
if (wantSudo) {
DenySudoAccess(peer_id);
return;
@@ -1718,34 +1684,30 @@ void Server::handleCommand_SrpBytesM(NetworkPacket *pkt)
std::string bytes_M;
*pkt >> bytes_M;
- if (srp_verifier_get_session_key_length((SRPVerifier *)client->auth_data) !=
- bytes_M.size()) {
+ if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
+ != bytes_M.size()) {
actionstream << "Server: User " << playername << " at " << addr_s
- << " sent bytes_M with invalid length " << bytes_M.size()
- << std::endl;
+ << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
}
unsigned char *bytes_HAMK = 0;
- srp_verifier_verify_session((SRPVerifier *)client->auth_data,
- (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
+ srp_verifier_verify_session((SRPVerifier *) client->auth_data,
+ (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
if (!bytes_HAMK) {
if (wantSudo) {
actionstream << "Server: User " << playername << " at " << addr_s
- << " tried to change their password, but supplied "
- "wrong"
- << " (SRP) password for authentication."
- << std::endl;
+ << " tried to change their password, but supplied wrong"
+ << " (SRP) password for authentication." << std::endl;
DenySudoAccess(peer_id);
return;
}
actionstream << "Server: User " << playername << " at " << addr_s
- << " supplied wrong password (auth mechanism: SRP)."
- << std::endl;
+ << " supplied wrong password (auth mechanism: SRP)." << std::endl;
m_script->on_authplayer(playername, addr_s, false);
DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD);
return;
@@ -1756,10 +1718,9 @@ void Server::handleCommand_SrpBytesM(NetworkPacket *pkt)
std::string checkpwd; // not used, but needed for passing something
if (!m_script->getAuth(playername, &checkpwd, NULL)) {
- actionstream << "Server: " << playername
- << " cannot be authenticated (auth handler does not "
- "work?)"
- << std::endl;
+ actionstream << "Server: " << playername <<
+ " cannot be authenticated (auth handler does not work?)" <<
+ std::endl;
DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
return;
}
@@ -1780,20 +1741,20 @@ void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
*pkt >> channel_name;
session_t peer_id = pkt->getPeerId();
- NetworkPacket resp_pkt(
- TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(), peer_id);
+ NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
+ 1 + 2 + channel_name.size(), peer_id);
// Send signal to client to notify join succeed or not
if (g_settings->getBool("enable_mod_channels") &&
m_modchannel_mgr->joinChannel(channel_name, peer_id)) {
- resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_OK;
- infostream << "Peer " << peer_id << " joined channel " << channel_name
- << std::endl;
- } else {
+ resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
+ infostream << "Peer " << peer_id << " joined channel " <<
+ channel_name << std::endl;
+ }
+ else {
resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
- infostream << "Peer " << peer_id << " tried to join channel "
- << channel_name << ", but was already registered."
- << std::endl;
+ infostream << "Peer " << peer_id << " tried to join channel " <<
+ channel_name << ", but was already registered." << std::endl;
}
resp_pkt << channel_name;
Send(&resp_pkt);
@@ -1805,19 +1766,19 @@ void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
*pkt >> channel_name;
session_t peer_id = pkt->getPeerId();
- NetworkPacket resp_pkt(
- TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(), peer_id);
+ NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
+ 1 + 2 + channel_name.size(), peer_id);
// Send signal to client to notify join succeed or not
if (g_settings->getBool("enable_mod_channels") &&
m_modchannel_mgr->leaveChannel(channel_name, peer_id)) {
resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
- infostream << "Peer " << peer_id << " left channel " << channel_name
- << std::endl;
+ infostream << "Peer " << peer_id << " left channel " << channel_name <<
+ std::endl;
} else {
- resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_FAILURE;
- infostream << "Peer " << peer_id << " left channel " << channel_name
- << ", but was not registered." << std::endl;
+ resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
+ infostream << "Peer " << peer_id << " left channel " << channel_name <<
+ ", but was not registered." << std::endl;
}
resp_pkt << channel_name;
Send(&resp_pkt);
@@ -1829,9 +1790,9 @@ void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
*pkt >> channel_name >> channel_msg;
session_t peer_id = pkt->getPeerId();
- verbosestream << "Mod channel message received from peer " << peer_id
- << " on channel " << channel_name << " message: " << channel_msg
- << std::endl;
+ verbosestream << "Mod channel message received from peer " << peer_id <<
+ " on channel " << channel_name << " message: " << channel_msg <<
+ std::endl;
// If mod channels are not enabled, discard message
if (!g_settings->getBool("enable_mod_channels")) {
@@ -1841,7 +1802,7 @@ void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
// If channel not registered, signal it and ignore message
if (!m_modchannel_mgr->channelRegistered(channel_name)) {
NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
- 1 + 2 + channel_name.size(), peer_id);
+ 1 + 2 + channel_name.size(), peer_id);
resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
Send(&resp_pkt);
return;