From f434aae3afe5a3b21bbf7a71cabe9961d1d23e7d Mon Sep 17 00:00:00 2001 From: DrPerkyLegit <116128211+DrPerkyLegit@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:24:01 -0500 Subject: [PATCH] replace WinsockNetLayer with PlatformNetworkManagerWindows, implement external server stats --- Minecraft.Client/CMakeLists.txt | 1 + Minecraft.Client/ClientConnection.cpp | 41 +- Minecraft.Client/Common/Consoles_App.cpp | 7 +- .../Common/Network/ExternalServerList.h | 179 ++ .../Common/Network/GameNetworkManager.cpp | 24 +- .../Common/Network/GameNetworkManager.h | 8 +- .../Network/PlatformNetworkManagerInterface.h | 1 + .../Network/PlatformNetworkManagerStub.cpp | 424 ---- Minecraft.Client/Common/Network/SessionInfo.h | 22 +- .../Common/UI/UIScene_ConnectingProgress.cpp | 102 - .../Common/UI/UIScene_ConnectingProgress.h | 5 - Minecraft.Client/Common/UI/UIScene_Intro.cpp | 2 +- .../Common/UI/UIScene_JoinMenu.cpp | 422 +--- Minecraft.Client/Common/UI/UIScene_JoinMenu.h | 25 +- .../Common/UI/UIScene_LoadCreateJoinMenu.cpp | 415 ++-- .../Common/UI/UIScene_LoadCreateJoinMenu.h | 9 + .../Common/UI/UIScene_LoadOrJoinMenu.cpp | 107 +- Minecraft.Client/Extrax64Stubs.cpp | 64 +- Minecraft.Client/Minecraft.cpp | 3 +- Minecraft.Client/MinecraftServer.cpp | 6 +- Minecraft.Client/PendingConnection.cpp | 23 +- Minecraft.Client/PlayerList.cpp | 27 +- .../Network/NetworkPlayerWindows.cpp | 287 +++ .../Windows64/Network/NetworkPlayerWindows.h | 91 + .../Network/PlatformNetworkManagerWindows.cpp | 1370 ++++++++++++ .../Network/PlatformNetworkManagerWindows.h | 133 ++ .../Windows64/Network/WindowsNetworkConfig.h | 17 + .../Windows64/Network/WinsockNetLayer.cpp | 1860 ----------------- .../Windows64/Network/WinsockNetLayer.h | 207 -- .../Windows64/Windows64_Minecraft.cpp | 30 +- Minecraft.Client/cmake/sources/Common.cmake | 7 +- Minecraft.Client/cmake/sources/Windows.cmake | 6 - Minecraft.Server/FourKitNatives.cpp | 9 +- Minecraft.Server/Windows64/ServerMain.cpp | 9 +- Minecraft.Server/cmake/sources/Common.cmake | 17 +- Minecraft.World/ByteBuffer.cpp | 38 +- Minecraft.World/CompressedTileStorage.cpp | 4 +- Minecraft.World/Definitions.h | 8 +- Minecraft.World/FileHeader.cpp | 10 +- Minecraft.World/FileHeader.h | 4 +- Minecraft.World/ZonedChunkStorage.cpp | 2 +- cmake/ServerTarget.cmake | 1 + 42 files changed, 2621 insertions(+), 3406 deletions(-) create mode 100644 Minecraft.Client/Common/Network/ExternalServerList.h create mode 100644 Minecraft.Client/Windows64/Network/NetworkPlayerWindows.cpp create mode 100644 Minecraft.Client/Windows64/Network/NetworkPlayerWindows.h create mode 100644 Minecraft.Client/Windows64/Network/PlatformNetworkManagerWindows.cpp create mode 100644 Minecraft.Client/Windows64/Network/PlatformNetworkManagerWindows.h create mode 100644 Minecraft.Client/Windows64/Network/WindowsNetworkConfig.h delete mode 100644 Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp delete mode 100644 Minecraft.Client/Windows64/Network/WinsockNetLayer.h diff --git a/Minecraft.Client/CMakeLists.txt b/Minecraft.Client/CMakeLists.txt index e8f0c38c..4a86df1e 100644 --- a/Minecraft.Client/CMakeLists.txt +++ b/Minecraft.Client/CMakeLists.txt @@ -87,6 +87,7 @@ target_link_libraries(Minecraft.Client PRIVATE d3dcompiler XInput9_1_0 wsock32 + ws2_32 dbghelp legacy_stdio_definitions 4JLibs.${PLATFORM_NAME}.Input diff --git a/Minecraft.Client/ClientConnection.cpp b/Minecraft.Client/ClientConnection.cpp index 7e33035b..6d42b701 100644 --- a/Minecraft.Client/ClientConnection.cpp +++ b/Minecraft.Client/ClientConnection.cpp @@ -57,9 +57,9 @@ #include "DLCTexturePack.h" #ifdef _WINDOWS64 -#include "Xbox/Network/NetworkPlayerXbox.h" -#include "Common/Network/PlatformNetworkManagerStub.h" -#include "Windows64/Network/WinsockNetLayer.h" +#include "Windows64/Network/PlatformNetworkManagerWindows.h" +#include "Windows64/Network/WindowsNetworkConfig.h" +#include "Windows64/Windows64_Xuid.h" #endif #include "../Minecraft.World/Recipes.h" @@ -963,16 +963,15 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) { IQNetPlayer* matchedQNetPlayer = nullptr; PlayerUID pktXuid = player->getXuid(); - const PlayerUID WIN64_XUID_BASE = (PlayerUID)0xe000d45248242f2e; + const PlayerUID WIN64_XUID_BASE = Win64Xuid::GetLegacyEmbeddedBaseXuid(); // Legacy compatibility path for peers still using embedded smallId XUIDs. if (pktXuid >= WIN64_XUID_BASE && pktXuid < WIN64_XUID_BASE + MINECRAFT_NET_MAX_PLAYERS) { BYTE smallId = (BYTE)(pktXuid - WIN64_XUID_BASE); INetworkPlayer* np = g_NetworkManager.GetPlayerBySmallId(smallId); - if (np != nullptr) + if (np != nullptr && !np->IsLocal()) { - NetworkPlayerXbox* npx = (NetworkPlayerXbox*)np; - matchedQNetPlayer = npx->GetQNetPlayer(); + matchedQNetPlayer = &IQNet::m_player[smallId]; } } @@ -986,11 +985,10 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) if (np == nullptr) continue; - NetworkPlayerXbox* npx = (NetworkPlayerXbox*)np; - IQNetPlayer* qp = npx->GetQNetPlayer(); - if (qp != nullptr && _wcsicmp(qp->m_gamertag, packet->name.c_str()) == 0) + const wchar_t* onlineName = np->GetOnlineName(); + if (onlineName != nullptr && _wcsicmp(onlineName, packet->name.c_str()) == 0) { - matchedQNetPlayer = qp; + matchedQNetPlayer = &IQNet::m_player[smallId]; break; } } @@ -1018,8 +1016,7 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) if (smallId >= IQNet::s_playerCount) IQNet::s_playerCount = smallId + 1; - extern CPlatformNetworkManagerStub* g_pPlatformNetworkManager; - g_pPlatformNetworkManager->NotifyPlayerJoined(qp); + g_pPlatformNetworkManagerWindows->RegisterMirroredPlayer(qp); matchedQNetPlayer = qp; break; } @@ -1035,6 +1032,7 @@ void ClientConnection::handleAddPlayer(shared_ptr packet) { wcsncpy_s(matchedQNetPlayer->m_gamertag, 32, packet->name.c_str(), _TRUNCATE); } + g_pPlatformNetworkManagerWindows->RegisterMirroredPlayer(matchedQNetPlayer); } } #endif @@ -1213,8 +1211,7 @@ void ClientConnection::handleRemoveEntity(shared_ptr packe if (qp->GetCustomDataValue() != 0 && _wcsicmp(qp->m_gamertag, player->getName().c_str()) == 0) { - extern CPlatformNetworkManagerStub* g_pPlatformNetworkManager; - g_pPlatformNetworkManager->NotifyPlayerLeaving(qp); + g_pPlatformNetworkManagerWindows->UnregisterMirroredPlayer(qp); qp->m_smallId = 0; qp->m_isRemote = false; qp->m_isHostPlayer = false; @@ -3008,8 +3005,10 @@ void ClientConnection::handleTextureAndGeometryChange(shared_ptr packet) { + const bool dimensionChanged = packet->dimension != minecraft->localplayers[m_userIndex]->dimension + || packet->mapSeed != minecraft->localplayers[m_userIndex]->level->getSeed(); //if (packet->dimension != minecraft->player->dimension) - if( packet->dimension != minecraft->localplayers[m_userIndex]->dimension || packet->mapSeed != minecraft->localplayers[m_userIndex]->level->getSeed() ) + if (dimensionChanged) { int oldDimension = minecraft->localplayers[m_userIndex]->dimension; started = false; @@ -3121,9 +3120,14 @@ void ClientConnection::handleRespawn(shared_ptr packet) // in there assume that we are set up for the player that the respawn is coming in for int oldIndex = minecraft->getLocalPlayerIdx(); minecraft->setLocalPlayerIdx(m_userIndex); - minecraft->respawnPlayer(minecraft->localplayers[m_userIndex]->GetXboxPad(),packet->dimension,packet->m_newEntityId); + minecraft->respawnPlayer(m_userIndex, packet->dimension, packet->m_newEntityId); ((MultiPlayerGameMode *) minecraft->localgameModes[m_userIndex])->setLocalMode(packet->playerGameType); minecraft->setLocalPlayerIdx(oldIndex); + + if (!dimensionChanged) + { + app.SetAction(m_userIndex, eAppAction_WaitForRespawnComplete); + } } void ClientConnection::handleExplosion(shared_ptr packet) @@ -3966,8 +3970,7 @@ void ClientConnection::handleCustomPayload(shared_ptr custo if (qp->GetCustomDataValue() != 0 && _wcsicmp(qp->m_gamertag, leavingName.c_str()) == 0) { - extern CPlatformNetworkManagerStub* g_pPlatformNetworkManager; - g_pPlatformNetworkManager->NotifyPlayerLeaving(qp); + g_pPlatformNetworkManagerWindows->UnregisterMirroredPlayer(qp); qp->m_smallId = 0; qp->m_isRemote = false; qp->m_isHostPlayer = false; diff --git a/Minecraft.Client/Common/Consoles_App.cpp b/Minecraft.Client/Common/Consoles_App.cpp index a0fdfb1d..6f27e6e1 100644 --- a/Minecraft.Client/Common/Consoles_App.cpp +++ b/Minecraft.Client/Common/Consoles_App.cpp @@ -29,7 +29,7 @@ #include "Tutorial/TutorialMode.h" #include "UI/UICustomStrings.h" #ifdef _WINDOWS64 -#include "../Windows64/Network/WinsockNetLayer.h" // HUCKLE - added for quit on disconnect +#include "../Windows64/Network/WindowsNetworkConfig.h" #endif #if defined _XBOX || defined _WINDOWS64 #include "../Xbox/XML/ATGXmlParser.h" @@ -58,7 +58,6 @@ #include "../Minecraft.h" #ifdef _XBOX #include "../Xbox/GameConfig/Minecraft.spa.h" -#include "../Xbox/Network/NetworkPlayerXbox.h" #include "XUI/XUI_TextEntry.h" #include "XUI/XUI_XZP_Icons.h" #include "XUI/XUI_PauseMenu.h" @@ -4689,7 +4688,7 @@ void CMinecraftApp::HandleXuiActions(void) #if defined _XBOX INetworkPlayer *pHost=g_NetworkManager.GetHostPlayer(); // write the level to the banned level list, and exit the world - AddLevelToBannedLevelList(i,((NetworkPlayerXbox *)pHost)->GetUID(),GetUniqueMapName(),true); + AddLevelToBannedLevelList(i, pHost->GetUID(), GetUniqueMapName(), true); #elif defined _XBOX_ONE INetworkPlayer *pHost=g_NetworkManager.GetHostPlayer(); AddLevelToBannedLevelList(i,pHost->GetUID(),GetUniqueMapName(),true); @@ -5026,7 +5025,7 @@ int CMinecraftApp::BannedLevelDialogReturned(void *pParam,int iPad,const C4JStor if (pHost != nullptr) { #if defined _XBOX - pApp->RemoveLevelFromBannedLevelList(iPad,((NetworkPlayerXbox *)pHost)->GetUID(),pApp->GetUniqueMapName()); + pApp->RemoveLevelFromBannedLevelList(iPad, pHost->GetUID(), pApp->GetUniqueMapName()); #else pApp->RemoveLevelFromBannedLevelList(iPad,pHost->GetUID(),pApp->GetUniqueMapName()); #endif diff --git a/Minecraft.Client/Common/Network/ExternalServerList.h b/Minecraft.Client/Common/Network/ExternalServerList.h new file mode 100644 index 00000000..39f900c3 --- /dev/null +++ b/Minecraft.Client/Common/Network/ExternalServerList.h @@ -0,0 +1,179 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +class ExternalServerList { +public: + typedef struct _Entry { + std::string address; + uint16_t port; + std::string name; + } Entry; + + static const uint32_t MaxEntries = 4096; + + static bool Read(std::vector& entries) { + entries.clear(); + FILE* file = nullptr; + if (fopen_s(&file, "servers.db", "rb") != 0) return errno == ENOENT; + + char magic[4] = {}; + uint32_t version = 0; + uint32_t count = 0; + bool success = (fread(magic, 1, sizeof(magic), file) == sizeof(magic) && memcmp(magic, "MCSV", sizeof(magic)) == 0) && (fread(&version, sizeof(version), 1, file) == 1 && fread(&count, sizeof(count), 1, file) == 1) && version == 1 && count <= MaxEntries; + + std::vector loadedEntries; + if (success) { + loadedEntries.reserve(count); + for (uint32_t index = 0; index < count; ++index) { + uint16_t addressLength = 0; + uint16_t port = 0; + uint16_t nameLength = 0; + if (fread(&addressLength, sizeof(addressLength), 1, file) != 1 || addressLength == 0 || addressLength > 256) { + success = false; + break; + } + + char address[257] = {}; + if (fread(address, 1, addressLength, file) != addressLength || fread(&port, sizeof(port), 1, file) != 1 || fread(&nameLength, sizeof(nameLength), 1, file) != 1 || nameLength > 256) { + success = false; + break; + } + + char name[257] = {}; + if ((nameLength != 0 && fread(name, 1, nameLength, file) != nameLength) || port == 0) { + success = false; + break; + } + + loadedEntries.push_back({ std::string(address, addressLength), port, std::string(name, nameLength) }); + } + } + + if (fclose(file) != 0) success = false; + if (success) entries.swap(loadedEntries); + + return success; + } + + static bool Write(const std::vector& entries) { + if (entries.size() > MaxEntries) return false; + + FILE* file = nullptr; + if (fopen_s(&file, "servers.db.tmp", "wb") != 0) return false; + + bool success = fwrite("MCSV", 1, 4, file) == 4; + const uint32_t version = 1; + const uint32_t count = static_cast(entries.size()); + success = success && fwrite(&version, sizeof(version), 1, file) == 1 && fwrite(&count, sizeof(count), 1, file) == 1; + + for (size_t index = 0; success && index < entries.size(); ++index) { + const Entry& entry = entries[index]; + uint64_t sessionId = 0; + if (entry.address.size() > 256 || entry.name.size() > 256 || + !MakeSessionId(entry.address, entry.port, sessionId)) { + success = false; + break; + } + + const uint16_t addressLength = static_cast(entry.address.size()); + const uint16_t nameLength = static_cast(entry.name.size()); + success = fwrite(&addressLength, sizeof(addressLength), 1, file) == 1 && fwrite(entry.address.data(), 1, addressLength, file) == addressLength && fwrite(&entry.port, sizeof(entry.port), 1, file) == 1 && fwrite(&nameLength, sizeof(nameLength), 1, file) == 1 && (nameLength == 0 || fwrite(entry.name.data(), 1, nameLength, file) == nameLength); + } + + if (fclose(file) != 0) success = false; + if (!success || !MoveFileExA("servers.db.tmp", "servers.db", MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + DeleteFileA("servers.db.tmp"); + return false; + } + return true; + } + + static bool Append(const Entry& entry) { + std::vector entries; + if (!Read(entries)) return false; + + entries.push_back(entry); + return Write(entries); + } + + static bool MakeSessionId(const std::string& address, uint16_t port, uint64_t& sessionId) { + if (address.empty() || address.size() > 253 || port == 0) return false; + + uint32_t ipAddress = 0; + size_t position = 0; + bool isIPv4 = true; + for (int octetIndex = 0; octetIndex < 4; ++octetIndex) { + if (position >= address.size()) { + isIPv4 = false; + break; + } + + uint32_t octet = 0; + size_t digits = 0; + while (position < address.size() && address[position] >= '0' && address[position] <= '9') { + octet = octet * 10 + static_cast(address[position] - '0'); + if (octet > 255) return false; + + ++position; + ++digits; + } + if (digits == 0) { + isIPv4 = false; + break; + } + + ipAddress = (ipAddress << 8) | octet; + if (octetIndex < 3) { + if (position >= address.size() || address[position] != '.') { + isIPv4 = false; + break; + } + + ++position; + } + } + if (isIPv4 && position == address.size()) { + sessionId = 0x4C41000000000000ULL | (static_cast(ipAddress) << 16) | static_cast(port); + return true; + } + + uint64_t hash = 14695981039346656037ULL; + size_t labelLength = 0; + char previous = '\0'; + for (size_t index = 0; index < address.size(); ++index) { + char character = address[index]; + if (character == '.') { + if (labelLength == 0 || previous == '-') return false; + labelLength = 0; + } else { + if (!((character >= 'a' && character <= 'z') || + (character >= 'A' && character <= 'Z') || + (character >= '0' && character <= '9') || character == '-')) { + return false; + } + if (labelLength == 0 && character == '-') return false; + ++labelLength; + if (labelLength > 63) return false; + if (character >= 'A' && character <= 'Z') character = static_cast(character - 'A' + 'a'); + } + hash ^= static_cast(character); + hash *= 1099511628211ULL; + previous = character; + } + if (labelLength == 0 || previous == '-') return false; + + hash ^= static_cast(port & 0xFF); + hash *= 1099511628211ULL; + hash ^= static_cast(port >> 8); + hash *= 1099511628211ULL; + sessionId = 0x4C53000000000000ULL | (hash & 0x0000FFFFFFFFFFFFULL); + return true; + } +}; \ No newline at end of file diff --git a/Minecraft.Client/Common/Network/GameNetworkManager.cpp b/Minecraft.Client/Common/Network/GameNetworkManager.cpp index e0291cb4..b35a9a5c 100644 --- a/Minecraft.Client/Common/Network/GameNetworkManager.cpp +++ b/Minecraft.Client/Common/Network/GameNetworkManager.cpp @@ -42,7 +42,8 @@ #endif #ifdef _WINDOWS64 -#include "../../Windows64/Network/WinsockNetLayer.h" +#include "../../Windows64/Network/PlatformNetworkManagerWindows.h" +#include "../../Windows64/Network/NetworkPlayerWindows.h" #include "../../Windows64/Windows64_Xuid.h" #endif @@ -79,6 +80,8 @@ void CGameNetworkManager::Initialise() s_pPlatformNetworkManager = new CPlatformNetworkManagerSony(); #elif defined _DURANGO s_pPlatformNetworkManager = new CPlatformNetworkManagerDurango(); +#elif defined _WINDOWS64 + s_pPlatformNetworkManager = new CPlatformNetworkManagerWindows(); #else s_pPlatformNetworkManager = new CPlatformNetworkManagerStub(); #endif @@ -808,7 +811,6 @@ void CGameNetworkManager::CancelJoinGame(LPVOID lpParam) s_pPlatformNetworkManager->CancelJoinGame(); #endif #ifdef _WINDOWS64 - WinsockNetLayer::CancelJoinGame(); #endif } @@ -1577,18 +1579,20 @@ void CGameNetworkManager::CreateSocket( INetworkPlayer *pNetworkPlayer, bool loc int padIdx = pNetworkPlayer->GetUserIndex(); BYTE assignedSmallId = 0; - if (!WinsockNetLayer::JoinSplitScreen(padIdx, &assignedSmallId)) + CPlatformNetworkManagerWindows* windowsNetworkManager = dynamic_cast(s_pPlatformNetworkManager); + if (windowsNetworkManager == nullptr || !windowsNetworkManager->JoinSplitScreen(padIdx, &assignedSmallId)) { app.DebugPrintf("Split-screen pad %d: failed to open TCP to host\n", padIdx); pMinecraft->connectionDisconnected(padIdx, DisconnectPacket::eDisconnect_ConnectionCreationFailed); return; } - // Update the local IQNetPlayer (at pad index) with the host-assigned smallId. - // The NetworkPlayerXbox created by NotifyPlayerJoined already points to - // m_player[padIdx], so we just set the smallId for network routing. - IQNet::m_player[padIdx].m_smallId = assignedSmallId; - IQNet::m_player[padIdx].m_resolvedXuid = Win64Xuid::DeriveXuidForPad(Win64Xuid::ResolvePersistentXuid(), padIdx); + NetworkPlayerWindows* windowsPlayer = dynamic_cast(pNetworkPlayer); + if (windowsPlayer != nullptr) + { + windowsPlayer->SetSmallId(assignedSmallId); + windowsPlayer->SetUID(Win64Xuid::DeriveXuidForPad(Win64Xuid::ResolvePersistentXuid(), padIdx)); + } // Network socket (not hostLocal) — data goes through TCP via GetLocalSocket socket = new Socket(pNetworkPlayer, false, false); @@ -2173,9 +2177,9 @@ int CGameNetworkManager::GetJoiningReadyPercentage() } #ifndef _XBOX -void CGameNetworkManager::FakeLocalPlayerJoined() +void CGameNetworkManager::FakeLocalPlayerJoined(bool fakeHost) { - s_pPlatformNetworkManager->FakeLocalPlayerJoined(); + s_pPlatformNetworkManager->FakeLocalPlayerJoined(fakeHost); } #endif diff --git a/Minecraft.Client/Common/Network/GameNetworkManager.h b/Minecraft.Client/Common/Network/GameNetworkManager.h index 59ee2201..9b6aa290 100644 --- a/Minecraft.Client/Common/Network/GameNetworkManager.h +++ b/Minecraft.Client/Common/Network/GameNetworkManager.h @@ -5,11 +5,13 @@ using namespace std; #include "../../../Minecraft.World/C4JThread.h" #include "NetworkPlayerInterface.h" #ifdef _XBOX -#include "../../Xbox/Network/PlatformNetworkManagerXbox.h" + void FakeLocalPlayerJoined(bool fakeHost = false); // Temporary method whilst we don't have real networking to make this happen #elif defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ #include "../../Common/Network/Sony/PlatformNetworkManagerSony.h" #elif defined _DURANGO #include "../../Durango/Network/PlatformNetworkManagerDurango.h" +#elif defined _WINDOWS64 +#include "../../Windows64/Network/PlatformNetworkManagerWindows.h" #else #include "PlatformNetworkManagerStub.h" #endif @@ -36,6 +38,8 @@ class CGameNetworkManager friend class CPlatformNetworkManagerSony; #elif defined _DURANGO friend class CPlatformNetworkManagerDurango; +#elif defined _WINDOWS64 + friend class CPlatformNetworkManagerWindows; #else friend class CPlatformNetworkManagerStub; #endif @@ -227,7 +231,7 @@ private: public: #ifndef _XBOX - void FakeLocalPlayerJoined(); // Temporary method whilst we don't have real networking to make this happen + void FakeLocalPlayerJoined(bool fakeHost = false); // Temporary method whilst we don't have real networking to make this happen #endif }; diff --git a/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h b/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h index d24fb229..6df6d99d 100644 --- a/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h +++ b/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h @@ -119,6 +119,7 @@ public: #ifndef _XBOX virtual void FakeLocalPlayerJoined() {}; // Temporary method whilst we don't have real networking to make this happen + virtual void FakeLocalPlayerJoined(bool fakeHost) { FakeLocalPlayerJoined(); } #endif #ifdef _DURANGO diff --git a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp index 6b0d9b97..628d7efa 100644 --- a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp +++ b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp @@ -3,15 +3,6 @@ #include "../../../Minecraft.World/StringHelpers.h" #include "PlatformNetworkManagerStub.h" #include "../../Xbox/Network/NetworkPlayerXbox.h" -#ifdef _WINDOWS64 -#include "../../Windows64/Network/WinsockNetLayer.h" -#include "../../Windows64/Windows64_Xuid.h" -#include "../../Minecraft.h" -#include "../../User.h" -#include "../../MinecraftServer.h" -#include "../../PlayerList.h" -#include -#endif #include #include @@ -28,111 +19,11 @@ void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer ) // for each client player. bool createFakeSocket = false; bool localPlayer = false; - - NetworkPlayerXbox *networkPlayer = static_cast(addNetworkPlayer(pQNetPlayer)); - - if( pQNetPlayer->IsLocal() ) - { - localPlayer = true; - if( pQNetPlayer->IsHost() ) - { - pszDescription = "local host"; - // 4J Stu - No socket for the localhost as it uses a special loopback queue - - m_machineQNetPrimaryPlayers.push_back( pQNetPlayer ); } else { pszDescription = "local"; - // We need an inbound queue on all local players to receive data from the host - createFakeSocket = true; - } - } - else - { - if( pQNetPlayer->IsHost() ) - { - pszDescription = "remote host"; - } - else - { - pszDescription = "remote"; - - // If we are the host, then create a fake socket for every remote player - if( m_pIQNet->IsHost() ) - { - createFakeSocket = true; - } - } - - if( m_pIQNet->IsHost() && !m_bHostChanged ) - { - // Do we already have a primary player for this system? - bool systemHasPrimaryPlayer = false; - for (auto& pQNetPrimaryPlayer : m_machineQNetPrimaryPlayers) - { - if( pQNetPlayer->IsSameSystem(pQNetPrimaryPlayer) ) - { - systemHasPrimaryPlayer = true; - break; - } - } - if( !systemHasPrimaryPlayer ) - m_machineQNetPrimaryPlayers.push_back( pQNetPlayer ); - } - } - g_NetworkManager.PlayerJoining( networkPlayer ); - - if( createFakeSocket == true && !m_bHostChanged ) - { - g_NetworkManager.CreateSocket( networkPlayer, localPlayer ); - } - - app.DebugPrintf( "Player 0x%p \"%ls\" joined; %s; voice %i; camera %i.\n", - pQNetPlayer, - pQNetPlayer->GetGamertag(), - pszDescription, - pQNetPlayer->HasVoice(), - pQNetPlayer->HasCamera() ); - - - if( m_pIQNet->IsHost() ) - { - // 4J-PB - only the host should do this -// g_NetworkManager.UpdateAndSetGameSessionData(); - SystemFlagAddPlayer( networkPlayer ); - } - - for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if(playerChangedCallback[idx] != nullptr) - playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, false ); - } - - if(m_pIQNet->GetState() == QNET_STATE_GAME_PLAY) - { - int localPlayerCount = 0; - for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if( m_pIQNet->GetLocalPlayerByUserIndex(idx) != nullptr ) ++localPlayerCount; - } - - float appTime = app.getAppTime(); - - // Only record stats for the primary player here - m_lastPlayerEventTimeStart = appTime; - } -} - -void CPlatformNetworkManagerStub::NotifyPlayerLeaving(IQNetPlayer* pQNetPlayer) -{ - app.DebugPrintf("Player 0x%p \"%ls\" leaving.\n", pQNetPlayer, pQNetPlayer->GetGamertag()); - - INetworkPlayer* networkPlayer = getNetworkPlayer(pQNetPlayer); - if (networkPlayer == nullptr) - return; - Socket* socket = networkPlayer->GetSocket(); if (socket != nullptr) { @@ -230,121 +121,11 @@ bool CPlatformNetworkManagerStub::isSystemPrimaryPlayer(IQNetPlayer *pQNetPlayer // We call this twice a frame, either side of the render call so is a good place to "tick" things void CPlatformNetworkManagerStub::DoWork() { -#ifdef _WINDOWS64 - extern QNET_STATE _iQNetStubState; - if (_iQNetStubState == QNET_STATE_SESSION_STARTING && app.GetGameStarted()) - { - _iQNetStubState = QNET_STATE_GAME_PLAY; - if (m_pIQNet->IsHost()) - WinsockNetLayer::UpdateAdvertiseJoinable(true); - } - if (_iQNetStubState == QNET_STATE_IDLE) - TickSearch(); - if (_iQNetStubState == QNET_STATE_GAME_PLAY && m_pIQNet->IsHost()) - { - BYTE disconnectedSmallId; - while (WinsockNetLayer::PopDisconnectedSmallId(&disconnectedSmallId)) - { - IQNetPlayer* qnetPlayer = m_pIQNet->GetPlayerBySmallId(disconnectedSmallId); - if (qnetPlayer != nullptr && qnetPlayer->m_smallId == disconnectedSmallId) - { - NotifyPlayerLeaving(qnetPlayer); - qnetPlayer->m_smallId = 0; - qnetPlayer->m_isRemote = false; - qnetPlayer->m_isHostPlayer = false; - qnetPlayer->m_resolvedXuid = INVALID_XUID; - qnetPlayer->m_gamertag[0] = 0; - qnetPlayer->SetCustomDataValue(0); - // Recalculate s_playerCount as the highest active slot + 1. - // A blind decrement would hide players at higher-indexed slots when a - // lower-indexed player disconnects first: GetPlayerBySmallId scans - // [0, s_playerCount) so any slot at or above the decremented count - // becomes invisible, causing its disconnect to be missed (ghost player). - while (IQNet::s_playerCount > 1 && - IQNet::m_player[IQNet::s_playerCount - 1].GetCustomDataValue() == 0) - IQNet::s_playerCount--; - } - // NOTE: Do NOT call PushFreeSmallId here. The old PlayerConnection's - // write thread may still be alive (it dies in PlayerList::tick when - // m_smallIdsToClose is processed). If we recycle the smallId now, - // AcceptThread can reuse it for a new connection, and the old write - // thread's getPlayer() lookup will resolve to the NEW player, sending - // stale game packets to the new client's TCP socket — corrupting its - // login handshake (bad packet id crash). PushFreeSmallId and - // ClearSocketForSmallId are called from PlayerList::tick after the - // old Connection threads are dead. - // - // Clear chunk visibility flags for this system so rejoin gets fresh chunk state. - SystemFlagRemoveBySmallId(disconnectedSmallId); - } - } - - // Client-side host disconnect detection: - // if TCP is gone, propagate through normal network-disconnect flow so UI returns to menus. - // The processing from the Xbox version will be reused. - if (_iQNetStubState == QNET_STATE_GAME_PLAY && !m_pIQNet->IsHost() && !m_bLeavingGame) - { - if (!WinsockNetLayer::IsConnected()) - { - if (!m_bLeaveGameOnTick) - { - m_bLeaveGameOnTick = true; - g_NetworkManager.HandleDisconnect(false); - } - } - else - { - m_bLeaveGameOnTick = false; - } - } - - // Async join finalization: when the background thread reports success, - // register players and transition the session to starting state. - if (m_bJoinPending) - { - WinsockNetLayer::eJoinState state = WinsockNetLayer::GetJoinState(); - if (state == WinsockNetLayer::eJoinState_Success) - { - WinsockNetLayer::FinalizeJoin(); - - BYTE localSmallId = WinsockNetLayer::GetLocalSmallId(); - - IQNet::m_player[localSmallId].m_smallId = localSmallId; - IQNet::m_player[localSmallId].m_isRemote = false; - IQNet::m_player[localSmallId].m_isHostPlayer = false; - IQNet::m_player[localSmallId].m_resolvedXuid = Win64Xuid::ResolvePersistentXuid(); - - Minecraft* pMinecraft = Minecraft::GetInstance(); - wcscpy_s(IQNet::m_player[localSmallId].m_gamertag, 32, pMinecraft->user->name.c_str()); - IQNet::s_playerCount = localSmallId + 1; - - NotifyPlayerJoined(&IQNet::m_player[0]); - NotifyPlayerJoined(&IQNet::m_player[localSmallId]); - - m_pGameNetworkManager->StateChange_AnyToStarting(); - m_bJoinPending = false; - } - else if (state == WinsockNetLayer::eJoinState_Failed || - state == WinsockNetLayer::eJoinState_Rejected || - state == WinsockNetLayer::eJoinState_Cancelled) - { - m_bJoinPending = false; - } - } -#endif } bool CPlatformNetworkManagerStub::CanAcceptMoreConnections() { -#ifdef _WINDOWS64 - MinecraftServer* server = MinecraftServer::getInstance(); - if (server == NULL) return true; - PlayerList* list = server->getPlayerList(); - if (list == NULL) return true; - return static_cast(list->players.size()) < static_cast(list->getMaxPlayers()); -#else return true; -#endif } int CPlatformNetworkManagerStub::GetPlayerCount() @@ -380,29 +161,6 @@ bool CPlatformNetworkManagerStub::AddLocalPlayerByUserIndex( int userIndex ) bool CPlatformNetworkManagerStub::RemoveLocalPlayerByUserIndex( int userIndex ) { -#ifdef _WINDOWS64 - if (userIndex > 0 && userIndex < XUSER_MAX_COUNT && !m_pIQNet->IsHost()) - { - IQNetPlayer* qp = &IQNet::m_player[userIndex]; - - // Notify the network layer before clearing the slot - if (qp->GetCustomDataValue() != 0) - { - NotifyPlayerLeaving(qp); - } - - // Close the split-screen TCP connection and reset WinsockNetLayer state - WinsockNetLayer::CloseSplitScreenConnection(userIndex); - - // Clear the IQNet slot so it can be reused on rejoin - qp->m_smallId = 0; - qp->m_isRemote = false; - qp->m_isHostPlayer = false; - qp->m_resolvedXuid = INVALID_XUID; - qp->m_gamertag[0] = 0; - qp->SetCustomDataValue(0); - } -#endif return true; } @@ -432,10 +190,6 @@ bool CPlatformNetworkManagerStub::LeaveGame(bool bMigrateHost) m_bLeavingGame = true; m_bLeaveGameOnTick = false; -#ifdef _WINDOWS64 - WinsockNetLayer::StopAdvertising(); -#endif - // If we are the host wait for the game server to end if(m_pIQNet->IsHost() && g_NetworkManager.ServerStoppedValid()) { @@ -454,11 +208,6 @@ bool CPlatformNetworkManagerStub::LeaveGame(bool bMigrateHost) m_machineQNetPrimaryPlayers.clear(); SystemFlagReset(); -#ifdef _WINDOWS64 - WinsockNetLayer::Shutdown(); - WinsockNetLayer::Initialize(); -#endif - return true; } @@ -483,51 +232,7 @@ void CPlatformNetworkManagerStub::HostGame(int localUsersMask, bool bOnlineGame, m_pIQNet->HostGame(); -#ifdef _WINDOWS64 - IQNet::m_player[0].m_smallId = 0; - IQNet::m_player[0].m_isRemote = false; - // world host is pinned to legacy host XUID to keep old player data compatibility. - IQNet::m_player[0].m_isHostPlayer = true; - IQNet::m_player[0].m_resolvedXuid = Win64Xuid::GetLegacyEmbeddedHostXuid(); - IQNet::s_playerCount = 1; -#endif - _HostGame( localUsersMask, publicSlots, privateSlots ); - -#ifdef _WINDOWS64 - int port = WIN64_NET_DEFAULT_PORT; - const char* bindIp = nullptr; - if (g_Win64DedicatedServer) - { - if (g_Win64DedicatedServerPort > 0) - port = g_Win64DedicatedServerPort; - if (g_Win64DedicatedServerBindIP[0] != 0) - bindIp = g_Win64DedicatedServerBindIP; - } - if (!WinsockNetLayer::IsActive()) - WinsockNetLayer::HostGame(port, bindIp); - - if (WinsockNetLayer::IsActive()) - { - // For Dedicated Server, refer to `lan-advertise` in `server.properties` - bool enableLanAdvertising = true; - if (g_Win64DedicatedServer) - { - enableLanAdvertising = g_Win64DedicatedServerLanAdvertise; - } - - if (enableLanAdvertising) - { - const wchar_t* hostName = IQNet::m_player[0].m_gamertag; - unsigned int settings = app.GetGameHostOption(eGameHostOption_All); - WinsockNetLayer::StartAdvertising(port, hostName, settings, 0, 0, MINECRAFT_NET_VERSION); - } - else - { - WinsockNetLayer::StopAdvertising(); - } - } -#endif //#endif } @@ -542,44 +247,7 @@ bool CPlatformNetworkManagerStub::_StartGame() int CPlatformNetworkManagerStub::JoinGame(FriendSessionInfo* searchResult, int localUsersMask, int primaryUserIndex) { -#ifdef _WINDOWS64 - if (searchResult == nullptr) - return CGameNetworkManager::JOINGAME_FAIL_GENERAL; - - const char* hostIP = searchResult->data.hostIP; - int hostPort = searchResult->data.hostPort; - - if (hostPort <= 0 || hostIP[0] == 0) - return CGameNetworkManager::JOINGAME_FAIL_GENERAL; - - m_bLeavingGame = false; - m_bLeaveGameOnTick = false; - IQNet::s_isHosting = false; - m_pIQNet->ClientJoinGame(); - - IQNet::m_player[0].m_smallId = 0; - IQNet::m_player[0].m_isRemote = true; - IQNet::m_player[0].m_isHostPlayer = true; - // Remote host still maps to legacy host XUID in mixed old/new sessions. - IQNet::m_player[0].m_resolvedXuid = Win64Xuid::GetLegacyEmbeddedHostXuid(); - wcsncpy_s(IQNet::m_player[0].m_gamertag, 32, searchResult->data.hostName, _TRUNCATE); - - WinsockNetLayer::StopDiscovery(); - - wcsncpy_s(m_joinHostName, 32, searchResult->data.hostName, _TRUNCATE); - m_joinLocalUsersMask = localUsersMask; - - if (!WinsockNetLayer::BeginJoinGame(hostIP, hostPort)) - { - app.DebugPrintf("Win64 LAN: Failed to start async join to %s:%d\n", hostIP, hostPort); - return CGameNetworkManager::JOINGAME_FAIL_GENERAL; - } - - m_bJoinPending = true; - return CGameNetworkManager::JOINGAME_PENDING; -#else return CGameNetworkManager::JOINGAME_SUCCESS; -#endif } bool CPlatformNetworkManagerStub::SetLocalGame(bool isLocal) @@ -855,98 +523,6 @@ void CPlatformNetworkManagerStub::TickSearch() void CPlatformNetworkManagerStub::SearchForGames() { -#ifdef _WINDOWS64 - std::vector lanSessions = WinsockNetLayer::GetDiscoveredSessions(); - - //THEY GET DELETED HERE DAMMIT - for (size_t i = 0; i < friendsSessions[0].size(); i++) - delete friendsSessions[0][i]; - friendsSessions[0].clear(); - - for (size_t i = 0; i < lanSessions.size(); i++) - { - FriendSessionInfo* info = new FriendSessionInfo(); - size_t nameLen = wcslen(lanSessions[i].hostName); - info->displayLabel = new wchar_t[nameLen + 1]; - wcscpy_s(info->displayLabel, nameLen + 1, lanSessions[i].hostName); - info->displayLabelLength = static_cast(nameLen); - info->displayLabelViewableStartIndex = 0; - - info->data.netVersion = lanSessions[i].netVersion; - info->data.m_uiGameHostSettings = lanSessions[i].gameHostSettings; - info->data.texturePackParentId = lanSessions[i].texturePackParentId; - info->data.subTexturePackId = lanSessions[i].subTexturePackId; - info->data.isReadyToJoin = lanSessions[i].isJoinable; - info->data.isJoinable = lanSessions[i].isJoinable; - strncpy_s(info->data.hostIP, sizeof(info->data.hostIP), lanSessions[i].hostIP, _TRUNCATE); - info->data.hostPort = lanSessions[i].hostPort; - wcsncpy_s(info->data.hostName, XUSER_NAME_SIZE, lanSessions[i].hostName, _TRUNCATE); - info->data.playerCount = lanSessions[i].playerCount; - info->data.maxPlayers = lanSessions[i].maxPlayers; - - info->sessionId = static_cast(inet_addr(lanSessions[i].hostIP)) | - static_cast(lanSessions[i].hostPort) << 32; - - friendsSessions[0].push_back(info); - } - - if (std::FILE* file = std::fopen("servers.db", "rb")) { - char magic[4] = {}; - if (std::fread(magic, 1, 4, file) == 4 && memcmp(magic, "MCSV", 4) == 0) - { - uint32_t version = 0, count = 0; - std::fread(&version, sizeof(uint32_t), 1, file); - std::fread(&count, sizeof(uint32_t), 1, file); - - if (version == 1) - { - for (uint32_t s = 0; s < count; s++) - { - uint16_t ipLen = 0, port = 0, nameLen = 0; - if (std::fread(&ipLen, sizeof(uint16_t), 1, file) != 1) break; - if (ipLen == 0 || ipLen > 256) break; - - char ipBuf[257] = {}; - if (std::fread(ipBuf, 1, ipLen, file) != ipLen) break; - if (std::fread(&port, sizeof(uint16_t), 1, file) != 1) break; - - if (std::fread(&nameLen, sizeof(uint16_t), 1, file) != 1) break; - if (nameLen > 256) break; - - wstring wName = L""; - for (int l = 0; l < nameLen; l++) { - uint16_t _char = 0; - if (std::fread(&_char, 1, 1, file) != 1) break; - wName += _char; - } - - FriendSessionInfo* info = new FriendSessionInfo(); - size_t nLen = wName.length(); - info->displayLabel = new wchar_t[nLen + 1]; - wcscpy_s(info->displayLabel, nLen + 1, wName.c_str()); - info->displayLabelLength = static_cast(nLen); - info->displayLabelViewableStartIndex = 0; - info->data.isReadyToJoin = true; - info->data.isJoinable = true; - strncpy_s(info->data.hostIP, sizeof(info->data.hostIP), ipBuf, _TRUNCATE); - info->data.hostPort = port; - info->sessionId = static_cast(inet_addr(ipBuf)) | static_cast(port) << 32; - //Fix null crash? I think its here... - if (info) { - friendsSessions[0].push_back(info); - } - - } - } - } - std::fclose(file); - } - - m_searchResultsCount[0] = static_cast(friendsSessions[0].size()); - - if (m_SessionsUpdatedCallback != nullptr) - m_SessionsUpdatedCallback(m_pSearchParam); -#endif } int CPlatformNetworkManagerStub::SearchForGamesThreadProc( void* lpParameter ) diff --git a/Minecraft.Client/Common/Network/SessionInfo.h b/Minecraft.Client/Common/Network/SessionInfo.h index c32ab8e1..d8ba33da 100644 --- a/Minecraft.Client/Common/Network/SessionInfo.h +++ b/Minecraft.Client/Common/Network/SessionInfo.h @@ -1,5 +1,8 @@ #pragma once +#include +#include + #if defined(__PS3__) || defined(__ORBIS__) #include "../../Common/Network/Sony/SQRNetworkManager.h" #endif @@ -71,7 +74,7 @@ typedef struct _GameSessionData bool isReadyToJoin; bool isJoinable; - char hostIP[64]; + char hostIP[256]; int hostPort; wchar_t hostName[XUSER_NAME_SIZE]; unsigned char playerCount; @@ -110,6 +113,12 @@ public: unsigned char displayLabelViewableStartIndex; GameSessionData data; bool hasPartyMember; + bool isDedicatedSession; + bool hasServerInfo; + std::vector serverPlayerNames; +#ifdef _WINDOWS64 + int savedServerIndex; +#endif FriendSessionInfo() { @@ -117,6 +126,11 @@ public: displayLabelLength = 0; displayLabelViewableStartIndex = 0; hasPartyMember = false; + isDedicatedSession = false; + hasServerInfo = false; +#ifdef _WINDOWS64 + savedServerIndex = -1; +#endif } FriendSessionInfo(const FriendSessionInfo& other) @@ -133,6 +147,12 @@ public: displayLabelViewableStartIndex = other.displayLabelViewableStartIndex; data = other.data; hasPartyMember = other.hasPartyMember; + isDedicatedSession = other.isDedicatedSession; + hasServerInfo = other.hasServerInfo; + serverPlayerNames = other.serverPlayerNames; +#ifdef _WINDOWS64 + savedServerIndex = other.savedServerIndex; +#endif if (other.displayLabel != NULL) { displayLabel = new wchar_t[displayLabelLength + 1]; diff --git a/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.cpp b/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.cpp index 69ab82a4..4f6beb1c 100644 --- a/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.cpp +++ b/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.cpp @@ -2,15 +2,6 @@ #include "UI.h" #include "UIScene_ConnectingProgress.h" #include "../../Minecraft.h" -#ifdef _WINDOWS64 -#include "../../Windows64/Network/WinsockNetLayer.h" - -static int ConnectingProgress_OnRejectedDialogOK(LPVOID, int iPad, const C4JStorage::EMessageResult) -{ - ui.NavigateBack(iPad); - return 0; -} -#endif UIScene_ConnectingProgress::UIScene_ConnectingProgress(int iPad, void *_initData, UILayer *parentLayer) : UIScene(iPad, parentLayer) { @@ -52,12 +43,6 @@ UIScene_ConnectingProgress::UIScene_ConnectingProgress(int iPad, void *_initData m_cancelFuncParam = param->cancelFuncParam; m_removeLocalPlayer = false; m_showingButton = false; -#ifdef _WINDOWS64 - WinsockNetLayer::eJoinState initState = WinsockNetLayer::GetJoinState(); - m_asyncJoinActive = (initState == WinsockNetLayer::eJoinState_Connecting || - initState == WinsockNetLayer::eJoinState_Success); - m_asyncJoinFailed = false; -#endif } UIScene_ConnectingProgress::~UIScene_ConnectingProgress() @@ -68,18 +53,6 @@ UIScene_ConnectingProgress::~UIScene_ConnectingProgress() void UIScene_ConnectingProgress::updateTooltips() { -#ifdef _WINDOWS64 - if (m_asyncJoinActive) - { - ui.SetTooltips(m_iPad, -1, IDS_TOOLTIPS_BACK); - return; - } - if (m_asyncJoinFailed) - { - ui.SetTooltips(m_iPad, IDS_TOOLTIPS_SELECT, -1); - return; - } -#endif // 4J-PB - removing the option of cancel join, since it didn't work anyway //ui.SetTooltips( m_iPad, -1, m_showTooltips?IDS_TOOLTIPS_CANCEL_JOIN:-1); ui.SetTooltips( m_iPad, -1, -1); @@ -88,62 +61,6 @@ void UIScene_ConnectingProgress::updateTooltips() void UIScene_ConnectingProgress::tick() { UIScene::tick(); - -#ifdef _WINDOWS64 - if (m_asyncJoinActive) - { - WinsockNetLayer::eJoinState state = WinsockNetLayer::GetJoinState(); - switch (state) - { - case WinsockNetLayer::eJoinState_Connecting: - { - int attempt = WinsockNetLayer::GetJoinAttempt(); - int maxAttempts = WinsockNetLayer::GetJoinMaxAttempts(); - wchar_t buf[128]; - if (attempt > 1) - swprintf_s(buf, L"Connecting... (attempt %d/%d)", attempt, maxAttempts); - else - swprintf_s(buf, L"Connecting..."); - m_labelTitle.setLabel(buf); - break; - } - case WinsockNetLayer::eJoinState_Success: - m_asyncJoinActive = false; - m_labelTitle.setLabel(L"Joining world..."); - break; - case WinsockNetLayer::eJoinState_Cancelled: - m_asyncJoinActive = false; - navigateBack(); - break; - case WinsockNetLayer::eJoinState_Rejected: - { - m_asyncJoinActive = false; - DisconnectPacket::eDisconnectReason reason = WinsockNetLayer::GetJoinRejectReason(); - int reasonStringId = IDS_CONNECTION_LOST_SERVER; - if (reason == DisconnectPacket::eDisconnect_ServerFull) - reasonStringId = IDS_DISCONNECTED_SERVER_FULL; - else if (reason == DisconnectPacket::eDisconnect_Kicked) - reasonStringId = IDS_DISCONNECTED_KICKED; - - UINT uiIDA[1]; - uiIDA[0] = IDS_CONFIRM_OK; - ui.RequestErrorMessage(IDS_CONNECTION_FAILED, reasonStringId, uiIDA, 1, m_iPad, ConnectingProgress_OnRejectedDialogOK, nullptr); - break; - } - case WinsockNetLayer::eJoinState_Failed: - m_asyncJoinActive = false; - m_asyncJoinFailed = true; - m_labelTitle.setLabel(app.GetString(IDS_CONNECTION_FAILED)); - m_buttonConfirm.setVisible(true); - m_showingButton = true; - updateTooltips(); - break; - default: - break; - } - } -#endif - if( m_removeLocalPlayer ) { m_removeLocalPlayer = false; @@ -290,18 +207,6 @@ void UIScene_ConnectingProgress::handleInput(int iPad, int key, bool repeat, boo switch(key) { -#ifdef _WINDOWS64 - case ACTION_MENU_CANCEL: - if (pressed && m_asyncJoinActive) - { - m_asyncJoinActive = false; - WinsockNetLayer::CancelJoinGame(); - navigateBack(); - handled = true; - return; - } - break; -#endif // 4J-PB - Removed the option to cancel join - it didn't work anyway // case ACTION_MENU_CANCEL: // { @@ -345,13 +250,6 @@ void UIScene_ConnectingProgress::handlePress(F64 controlId, F64 childId) case eControl_Confirm: if(m_showingButton) { -#ifdef _WINDOWS64 - if (m_asyncJoinFailed) - { - navigateBack(); - break; - } -#endif if( m_iPad != ProfileManager.GetPrimaryPad() && g_NetworkManager.IsInSession() ) { // The connection failed if we see the button, so the temp player should be removed and the viewports updated again diff --git a/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.h b/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.h index 09eddc18..e297456d 100644 --- a/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.h +++ b/Minecraft.Client/Common/UI/UIScene_ConnectingProgress.h @@ -12,11 +12,6 @@ private: bool m_showingButton; void (*m_cancelFunc)(LPVOID param); LPVOID m_cancelFuncParam; -#ifdef _WINDOWS64 - bool m_asyncJoinActive; - bool m_asyncJoinFailed; -#endif - enum EControls { eControl_Confirm diff --git a/Minecraft.Client/Common/UI/UIScene_Intro.cpp b/Minecraft.Client/Common/UI/UIScene_Intro.cpp index 975df407..1cbc5d03 100644 --- a/Minecraft.Client/Common/UI/UIScene_Intro.cpp +++ b/Minecraft.Client/Common/UI/UIScene_Intro.cpp @@ -4,7 +4,7 @@ // HUCKLE - added below for joining game on launch #ifdef _WINDOWS64 -#include "../../Windows64/Network/WinsockNetLayer.h" +#include "../../Windows64/Network/WindowsNetworkConfig.h" #include "../../User.h" #endif diff --git a/Minecraft.Client/Common/UI/UIScene_JoinMenu.cpp b/Minecraft.Client/Common/UI/UIScene_JoinMenu.cpp index b8c86337..361351da 100644 --- a/Minecraft.Client/Common/UI/UIScene_JoinMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_JoinMenu.cpp @@ -10,11 +10,6 @@ #include "../../../Minecraft.World/net.minecraft.world.level.h" #include "../../../Minecraft.World/net.minecraft.world.h" -#ifdef _WINDOWS64 -#include "../../Windows64/Network/WinsockNetLayer.h" -#include "../../Windows64/4JLibs/inc/4J_Input.h" -#endif - #define UPDATE_PLAYERS_TIMER_ID 0 #define UPDATE_PLAYERS_TIMER_TIME 400.0 @@ -36,11 +31,7 @@ UIScene_JoinMenu::UIScene_JoinMenu(int iPad, void *_initData, UILayer *parentLay m_friendInfoUpdatedERROR = false; m_friendInfoRequestIssued = false; #ifdef _WINDOWS64 - m_serverIndex = initData->serverIndex; - m_editServerPhase = eEditServer_Idle; - m_bPendingEditClose = false; - m_editServerButtonIndex = -1; - m_deleteServerButtonIndex = -1; + m_bViewingPlayerList = false; // reset the howtoplay state s_textInjected = false; @@ -118,14 +109,6 @@ void UIScene_JoinMenu::updateTooltips() iA = IDS_TOOLTIPS_SELECT; } -#ifdef _WINDOWS64 - if (m_serverIndex >= 0) - { - iX = IDS_TOOLTIPS_DELETE; - iY = IDS_TITLE_RENAME; - } -#endif - ui.SetTooltips( DEFAULT_XUI_MENU_USER, iA, IDS_TOOLTIPS_BACK, iX, iY ); } @@ -133,14 +116,6 @@ void UIScene_JoinMenu::updateTooltips() void UIScene_JoinMenu::tick() { if (this == nullptr) return; -#ifdef _WINDOWS64 - if (m_bPendingEditClose && hasFocus(m_iPad)) - { - m_bPendingEditClose = false; - navigateBack(); - return; - } -#endif if (!m_friendInfoRequestIssued) { ui.NavigateToScene(m_iPad, eUIScene_Timer); @@ -155,7 +130,7 @@ void UIScene_JoinMenu::tick() m_buttonJoinGame.init(app.GetString(IDS_JOIN_GAME), eControl_JoinGame); m_buttonListPlayers.init(eControl_GamePlayers); - m_buttonListPlayers.setYPos(m_buttonListPlayers.getYPos() + 300); + m_buttonListPlayers.setYPos(m_buttonListPlayers.getYPos() + 320); #if defined(__PS3__) || defined(__ORBIS__) || defined __PSVITA__ for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++) @@ -205,16 +180,6 @@ void UIScene_JoinMenu::tick() } #endif -#ifdef _WINDOWS64 - if (m_serverIndex >= 0) - { - m_editServerButtonIndex = m_buttonListPlayers.getItemCount(); - m_buttonListPlayers.addItem(L"Edit Server"); - m_deleteServerButtonIndex = m_buttonListPlayers.getItemCount(); - m_buttonListPlayers.addItem(L"Delete Server"); - } -#endif - m_labelLabels[eLabel_Difficulty].init(app.GetString(IDS_LABEL_DIFFICULTY)); m_labelLabels[eLabel_GameType].init(app.GetString(IDS_LABEL_GAME_TYPE)); m_labelLabels[eLabel_GamertagsOn].init(app.GetString(IDS_LABEL_GAMERTAGS)); @@ -278,6 +243,15 @@ void UIScene_JoinMenu::tick() if (app.GetGameHostOption(uiGameHostSettings, eGameHostOption_FireSpreads)) m_labelValues[eLabel_FireOn].init(app.GetString(IDS_ON)); else m_labelValues[eLabel_FireOn].init(app.GetString(IDS_OFF)); +#ifdef _WINDOWS64 + if (m_selectedSession->savedServerIndex >= 0 && !m_selectedSession->hasServerInfo) + { + for (int index = 0; index < eLabel_COUNT; ++index) + m_labelValues[index].init(L"-"); + } + SetPlayerListPage(m_bViewingPlayerList); +#endif + m_bIgnoreInput = false; // Alert the app the we want to be informed of ethernet connections @@ -293,7 +267,7 @@ void UIScene_JoinMenu::tick() m_buttonJoinGame.init(app.GetString(IDS_JOIN_GAME), eControl_JoinGame); m_buttonListPlayers.init(eControl_GamePlayers); - m_buttonListPlayers.setYPos(m_buttonListPlayers.getYPos() + 300); + m_buttonListPlayers.setYPos(m_buttonListPlayers.getYPos() + 320); m_labelLabels[eLabel_Difficulty].init(app.GetString(IDS_LABEL_DIFFICULTY)); m_labelLabels[eLabel_GameType].init(app.GetString(IDS_LABEL_GAME_TYPE)); @@ -315,6 +289,10 @@ void UIScene_JoinMenu::tick() m_labelValues[eLabel_TNTOn].init(app.GetString(IDS_OFF)); m_labelValues[eLabel_FireOn].init(app.GetString(IDS_OFF)); +#ifdef _WINDOWS64 + SetPlayerListPage(m_bViewingPlayerList); +#endif + m_friendInfoUpdatedERROR = false; // Show a generic network error message, not always safe to assume the error was host quitting @@ -360,7 +338,7 @@ void UIScene_JoinMenu::updateServerDescription() { { IggyValueSetF64RS(&textPath, nameX, nullptr, 333.0);// horizontal IggyValueSetF64RS(&textPath, nameY, nullptr, 340.0);// vertical - IggyValueSetF64RS(&textPath, nameW, nullptr, 580.0); + IggyValueSetF64RS(&textPath, nameW, nullptr, 575.0); IggyValueSetF64RS(&textPath, nameH, nullptr, 270.0); } else //720 @@ -425,6 +403,40 @@ void UIScene_JoinMenu::updateServerDescription() { } } +#ifdef _WINDOWS64 +void UIScene_JoinMenu::RebuildServerPlayerList() +{ + m_buttonListPlayers.clearList(); + + if (m_bViewingPlayerList) { + if (m_selectedSession->hasServerInfo) { + for (const wstring& playerName : m_selectedSession->serverPlayerNames) { + m_buttonListPlayers.addItem(playerName); + } + } + } else { + m_buttonListPlayers.addItem(L"Show Player List"); + } + + m_buttonListPlayers.setCurrentSelection(0); + m_buttonListPlayers.updateChildFocus(0); +} + +void UIScene_JoinMenu::SetPlayerListPage(bool visible) { + if (visible != m_bViewingPlayerList) + m_buttonListPlayers.setYPos(m_buttonListPlayers.getYPos() + (visible ? -320 : 320)); + + m_bViewingPlayerList = visible; + m_buttonListPlayers.setVisible(true); + + // (int index = 0; index < eLabel_COUNT; ++index) { + // m_labelLabels[index].setVisible(!visible); + // m_labelValues[index].setVisible(!visible); + //} + RebuildServerPlayerList(); +} +#endif + void UIScene_JoinMenu::friendSessionUpdated(bool success, void *pParam) { UIScene_JoinMenu *scene = static_cast(pParam); @@ -464,7 +476,7 @@ void UIScene_JoinMenu::render(S32 width, S32 height, C4JRender::eViewportType vi UIScene::render(width, height, viewpBort); #ifdef _WINDOWS64 - if (s_movieServerDesc) + if (s_movieServerDesc && !m_bViewingPlayerList) { IggyPlayerSetDisplaySize(s_movieServerDesc, width, height); IggyPlayerDraw(s_movieServerDesc); @@ -483,6 +495,14 @@ void UIScene_JoinMenu::handleInput(int iPad, int key, bool repeat, bool pressed, case ACTION_MENU_CANCEL: if(pressed) { +#ifdef _WINDOWS64 + if (m_bViewingPlayerList) + { + SetPlayerListPage(false); + handled = true; + break; + } +#endif navigateBack(); handled = true; } @@ -495,22 +515,6 @@ void UIScene_JoinMenu::handleInput(int iPad, int key, bool repeat, bool pressed, if( uid != INVALID_XUID ) ProfileManager.ShowProfileCard(ProfileManager.GetLockedProfile(),uid); } break; -#endif -#ifdef _WINDOWS64 - case ACTION_MENU_X: - if(pressed && m_serverIndex >= 0) - { - BeginDeleteServer(); - handled = true; - } - break; - case ACTION_MENU_Y: - if(pressed && m_serverIndex >= 0) - { - BeginEditServer(); - handled = true; - } - break; #endif case ACTION_MENU_OK: if (getControlFocus() != eControl_GamePlayers) @@ -518,13 +522,11 @@ void UIScene_JoinMenu::handleInput(int iPad, int key, bool repeat, bool pressed, sendInputToMovie(key, repeat, pressed, released); } #ifdef _WINDOWS64 - else if (pressed && m_serverIndex >= 0) + else if (pressed) { int sel = m_buttonListPlayers.getCurrentSelection(); - if (sel == m_editServerButtonIndex) - BeginEditServer(); - else if (sel == m_deleteServerButtonIndex) - BeginDeleteServer(); + if (!m_bViewingPlayerList && sel == 0) + SetPlayerListPage(true); } #endif handled = true; @@ -577,14 +579,8 @@ void UIScene_JoinMenu::handlePress(F64 controlId, F64 childId) break; case eControl_GamePlayers: #ifdef _WINDOWS64 - if (m_serverIndex >= 0) - { - int sel = (int)childId; - if (sel == m_editServerButtonIndex) - BeginEditServer(); - else if (sel == m_deleteServerButtonIndex) - BeginDeleteServer(); - } + if (!m_bViewingPlayerList && static_cast(childId) == 0) + SetPlayerListPage(true); #endif break; }; @@ -923,291 +919,3 @@ void UIScene_JoinMenu::handleTimerComplete(int id) break; }; } - -#ifdef _WINDOWS64 -void UIScene_JoinMenu::BeginDeleteServer() -{ - m_bIgnoreInput = true; - UINT uiIDA[2]; - uiIDA[0] = IDS_CONFIRM_CANCEL; - uiIDA[1] = IDS_CONFIRM_OK; - ui.RequestAlertMessage(IDS_TOOLTIPS_DELETE, IDS_TEXT_DELETE_SAVE, uiIDA, 2, m_iPad, &UIScene_JoinMenu::DeleteServerDialogReturned, this); -} - -int UIScene_JoinMenu::DeleteServerDialogReturned(void *pParam, int iPad, C4JStorage::EMessageResult result) -{ - UIScene_JoinMenu* pClass = (UIScene_JoinMenu*)pParam; - - if (result == C4JStorage::EMessage_ResultDecline) - { - pClass->RemoveServerFromFile(); - g_NetworkManager.ForceFriendsSessionRefresh(); - pClass->navigateBack(); - } - else - { - pClass->m_bIgnoreInput = false; - } - - return 0; -} - -void UIScene_JoinMenu::BeginEditServer() -{ - m_bIgnoreInput = true; - m_editServerPhase = eEditServer_Idle; - - wchar_t wIP[256] = {}; - mbstowcs(wIP, m_selectedSession->data.hostIP, 255); - wchar_t wPort[16] = {}; - swprintf(wPort, 16, L"%d", m_selectedSession->data.hostPort); - - m_editServerData = EditServerInitData(); - m_editServerData.name = m_selectedSession->displayLabel ? m_selectedSession->displayLabel : L""; - m_editServerData.address = wstring(wIP); - if (wcscmp(wPort, L"25565") != 0) - m_editServerData.address += wstring(L":") + wPort; - m_editServerData.callback = &UIScene_JoinMenu::EditServerDoneCallback; - m_editServerData.lpParam = this; - ui.NavigateToScene(m_iPad, eUIScene_EditServerMenu, &m_editServerData); -} - -int UIScene_JoinMenu::EditServerDoneCallback(LPVOID lpParam, bool confirmed, const wstring &name, const wstring &ip, const wstring &port) -{ - UIScene_JoinMenu *pClass = static_cast(lpParam); - pClass->m_bIgnoreInput = false; - if (confirmed && !ip.empty()) - { - pClass->UpdateServerInFile(ip, port, name); - g_NetworkManager.ForceFriendsSessionRefresh(); - pClass->m_bPendingEditClose = true; - } - return 0; -} - -int UIScene_JoinMenu::EditServerKeyboardCallback(LPVOID lpParam, bool bRes) -{ - UIScene_JoinMenu *pClass = (UIScene_JoinMenu *)lpParam; - - if (!bRes) - { - pClass->m_editServerPhase = eEditServer_Idle; - pClass->m_bIgnoreInput = false; - return 0; - } - - uint16_t ui16Text[256]; - ZeroMemory(ui16Text, sizeof(ui16Text)); - Win64_GetKeyboardText(ui16Text, 256); - - wchar_t wBuf[256] = {}; - for (int k = 0; k < 255 && ui16Text[k]; k++) - wBuf[k] = (wchar_t)ui16Text[k]; - - if (wBuf[0] == 0) - { - pClass->m_editServerPhase = eEditServer_Idle; - pClass->m_bIgnoreInput = false; - return 0; - } - - switch (pClass->m_editServerPhase) - { - case eEditServer_IP: - { - pClass->m_editServerIP = wBuf; - pClass->m_editServerPhase = eEditServer_Port; - - wchar_t wDefaultPort[16] = {}; - swprintf(wDefaultPort, 16, L"%d", pClass->m_selectedSession->data.hostPort); - - UIKeyboardInitData kbData; - kbData.title = L"Server Port"; - kbData.defaultText = wDefaultPort; - kbData.maxChars = 6; - kbData.callback = &UIScene_JoinMenu::EditServerKeyboardCallback; - kbData.lpParam = pClass; - kbData.pcMode = g_KBMInput.IsKBMActive(); - ui.NavigateToScene(pClass->m_iPad, eUIScene_Keyboard, &kbData); - break; - } - case eEditServer_Port: - { - pClass->m_editServerPort = wBuf; - pClass->m_editServerPhase = eEditServer_Name; - - wchar_t wDefaultName[64] = {}; - if (pClass->m_selectedSession->displayLabel) - wcsncpy(wDefaultName, pClass->m_selectedSession->displayLabel, 63); - - UIKeyboardInitData kbData; - kbData.title = L"Server Name"; - kbData.defaultText = wDefaultName; - kbData.maxChars = 64; - kbData.callback = &UIScene_JoinMenu::EditServerKeyboardCallback; - kbData.lpParam = pClass; - kbData.pcMode = g_KBMInput.IsKBMActive(); - ui.NavigateToScene(pClass->m_iPad, eUIScene_Keyboard, &kbData); - break; - } - case eEditServer_Name: - { - wstring newName = wBuf; - pClass->UpdateServerInFile(pClass->m_editServerIP, pClass->m_editServerPort, newName); - pClass->m_editServerPhase = eEditServer_Idle; - pClass->m_bIgnoreInput = false; - - g_NetworkManager.ForceFriendsSessionRefresh(); - pClass->navigateBack(); - break; - } - default: - pClass->m_editServerPhase = eEditServer_Idle; - pClass->m_bIgnoreInput = false; - break; - } - - return 0; -} - -void UIScene_JoinMenu::UpdateServerInFile(const wstring& newIP, const wstring& newPort, const wstring& newName) -{ - char narrowNewIP[256] = {}; - char narrowNewPort[16] = {}; - char narrowNewName[256] = {}; - wcstombs(narrowNewIP, newIP.c_str(), sizeof(narrowNewIP) - 1); - wcstombs(narrowNewPort, newPort.c_str(), sizeof(narrowNewPort) - 1); - wcstombs(narrowNewName, newName.c_str(), sizeof(narrowNewName) - 1); - - uint16_t newPortNum = (uint16_t)atoi(narrowNewPort); - - struct ServerEntry { std::string ip; uint16_t port; std::string name; }; - std::vector entries; - - FILE* file = fopen("servers.db", "rb"); - if (file) - { - char magic[4] = {}; - if (fread(magic, 1, 4, file) == 4 && memcmp(magic, "MCSV", 4) == 0) - { - uint32_t version = 0, count = 0; - fread(&version, sizeof(uint32_t), 1, file); - fread(&count, sizeof(uint32_t), 1, file); - if (version == 1) - { - for (uint32_t s = 0; s < count; s++) - { - uint16_t ipLen = 0, p = 0, nameLen = 0; - if (fread(&ipLen, sizeof(uint16_t), 1, file) != 1) break; - if (ipLen == 0 || ipLen > 256) break; - char ipBuf[257] = {}; - if (fread(ipBuf, 1, ipLen, file) != ipLen) break; - if (fread(&p, sizeof(uint16_t), 1, file) != 1) break; - if (fread(&nameLen, sizeof(uint16_t), 1, file) != 1) break; - if (nameLen > 256) break; - char nameBuf[257] = {}; - if (nameLen > 0 && fread(nameBuf, 1, nameLen, file) != nameLen) break; - entries.push_back({std::string(ipBuf), p, std::string(nameBuf)}); - } - } - } - fclose(file); - } - - // Find and update the matching entry by original IP and port - int idx = m_serverIndex; - if (idx >= 0 && idx < (int)entries.size()) - { - entries[idx].ip = std::string(narrowNewIP); - entries[idx].port = newPortNum; - entries[idx].name = std::string(narrowNewName); - } - - file = fopen("servers.db", "wb"); - if (file) - { - fwrite("MCSV", 1, 4, file); - uint32_t version = 1; - uint32_t count = (uint32_t)entries.size(); - fwrite(&version, sizeof(uint32_t), 1, file); - fwrite(&count, sizeof(uint32_t), 1, file); - - for (size_t i = 0; i < entries.size(); i++) - { - uint16_t ipLen = (uint16_t)entries[i].ip.length(); - fwrite(&ipLen, sizeof(uint16_t), 1, file); - fwrite(entries[i].ip.c_str(), 1, ipLen, file); - fwrite(&entries[i].port, sizeof(uint16_t), 1, file); - uint16_t nameLen = (uint16_t)entries[i].name.length(); - fwrite(&nameLen, sizeof(uint16_t), 1, file); - fwrite(entries[i].name.c_str(), 1, nameLen, file); - } - fclose(file); - } -} - -void UIScene_JoinMenu::RemoveServerFromFile() -{ - struct ServerEntry { std::string ip; uint16_t port; std::string name; }; - std::vector entries; - - FILE* file = fopen("servers.db", "rb"); - if (file) - { - char magic[4] = {}; - if (fread(magic, 1, 4, file) == 4 && memcmp(magic, "MCSV", 4) == 0) - { - uint32_t version = 0, count = 0; - fread(&version, sizeof(uint32_t), 1, file); - fread(&count, sizeof(uint32_t), 1, file); - if (version == 1) - { - for (uint32_t s = 0; s < count; s++) - { - uint16_t ipLen = 0, p = 0, nameLen = 0; - if (fread(&ipLen, sizeof(uint16_t), 1, file) != 1) break; - if (ipLen == 0 || ipLen > 256) break; - char ipBuf[257] = {}; - if (fread(ipBuf, 1, ipLen, file) != ipLen) break; - if (fread(&p, sizeof(uint16_t), 1, file) != 1) break; - if (fread(&nameLen, sizeof(uint16_t), 1, file) != 1) break; - if (nameLen > 256) break; - char nameBuf[257] = {}; - if (nameLen > 0 && fread(nameBuf, 1, nameLen, file) != nameLen) break; - entries.push_back({std::string(ipBuf), p, std::string(nameBuf)}); - } - } - } - fclose(file); - } - - // Remove the entry at m_serverIndex - int idx = m_serverIndex; - if (idx >= 0 && idx < (int)entries.size()) - { - entries.erase(entries.begin() + idx); - } - - file = fopen("servers.db", "wb"); - if (file) - { - fwrite("MCSV", 1, 4, file); - uint32_t version = 1; - uint32_t count = (uint32_t)entries.size(); - fwrite(&version, sizeof(uint32_t), 1, file); - fwrite(&count, sizeof(uint32_t), 1, file); - - for (size_t i = 0; i < entries.size(); i++) - { - uint16_t ipLen = (uint16_t)entries[i].ip.length(); - fwrite(&ipLen, sizeof(uint16_t), 1, file); - fwrite(entries[i].ip.c_str(), 1, ipLen, file); - fwrite(&entries[i].port, sizeof(uint16_t), 1, file); - uint16_t nameLen = (uint16_t)entries[i].name.length(); - fwrite(&nameLen, sizeof(uint16_t), 1, file); - fwrite(entries[i].name.c_str(), 1, nameLen, file); - } - fclose(file); - } -} -#endif // _WINDOWS64 \ No newline at end of file diff --git a/Minecraft.Client/Common/UI/UIScene_JoinMenu.h b/Minecraft.Client/Common/UI/UIScene_JoinMenu.h index 7b6f3794..06cf3b65 100644 --- a/Minecraft.Client/Common/UI/UIScene_JoinMenu.h +++ b/Minecraft.Client/Common/UI/UIScene_JoinMenu.h @@ -1,9 +1,6 @@ #pragma once #include "UIScene.h" -#ifdef _WINDOWS64 -#include "UIScene_EditServerMenu.h" -#endif class UIScene_JoinMenu : public UIScene { @@ -70,13 +67,9 @@ private: bool m_friendInfoUpdatedERROR; #ifdef _WINDOWS64 - int m_serverIndex; // Index in servers.db, -1 if not a saved server - enum eEditServerPhase { eEditServer_Idle, eEditServer_IP, eEditServer_Port, eEditServer_Name }; - eEditServerPhase m_editServerPhase; - wstring m_editServerIP; - wstring m_editServerPort; - int m_editServerButtonIndex; - int m_deleteServerButtonIndex; + bool m_bViewingPlayerList; + void RebuildServerPlayerList(); + void SetPlayerListPage(bool visible); #endif public: @@ -117,16 +110,4 @@ protected: static int StartGame_SignInReturned(void *pParam, bool, int); static void JoinGame(UIScene_JoinMenu* pClass); - -#ifdef _WINDOWS64 - void BeginEditServer(); - void BeginDeleteServer(); - static int EditServerKeyboardCallback(LPVOID lpParam, bool bRes); - EditServerInitData m_editServerData; - bool m_bPendingEditClose; - static int EditServerDoneCallback(LPVOID lpParam, bool confirmed, const wstring &name, const wstring &ip, const wstring &port); - static int DeleteServerDialogReturned(void *pParam, int iPad, C4JStorage::EMessageResult result); - void UpdateServerInFile(const wstring& newIP, const wstring& newPort, const wstring& newName); - void RemoveServerFromFile(); -#endif }; diff --git a/Minecraft.Client/Common/UI/UIScene_LoadCreateJoinMenu.cpp b/Minecraft.Client/Common/UI/UIScene_LoadCreateJoinMenu.cpp index 100a6b84..2044d65d 100644 --- a/Minecraft.Client/Common/UI/UIScene_LoadCreateJoinMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_LoadCreateJoinMenu.cpp @@ -58,6 +58,7 @@ #include "..\..\..\Minecraft.World\compression.h" #include "..\..\Windows64\KeyboardMouseInput.h" +#include "..\Network\ExternalServerList.h" #include "UISplitScreenHelpers.h" #include @@ -1198,6 +1199,13 @@ void UIScene_LoadCreateJoinMenu::updateTooltips() iY = IDS_TOOLTIPS_HIDE; } +#ifdef _WINDOWS64 + else if (GetSelectedSavedServer() != nullptr) + { + iY = IDS_TOOLTIPS_OPTIONS; + } +#endif + #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) if(m_iPad == ProfileManager.GetPrimaryPad()) @@ -1247,6 +1255,7 @@ void UIScene_LoadCreateJoinMenu::Initialise() #ifdef _WINDOWS64 m_addServerPhase = eAddServer_Idle; + m_selectedServerIndex = -1; #endif @@ -3149,6 +3158,18 @@ void UIScene_LoadCreateJoinMenu::handleInput(int iPad, int key, bool repeat, boo return false; }; +#ifdef _WINDOWS64 + auto openServerOptions = [&]() -> bool + { + if (!pressed || repeat || !BeginServerOptions()) + return false; + + ui.PlayUISFX(eSFX_Press); + handled = true; + return true; + }; +#endif + auto hideFocusedMashupWorld = [&]() -> bool { if(!pressed || repeat || !ProfileManager.IsFullVersion() || !DoesMashUpWorldHaveFocus()) @@ -3274,7 +3295,11 @@ void UIScene_LoadCreateJoinMenu::handleInput(int iPad, int key, bool repeat, boo // Right click on a save opens save options. In Create, it hides mash-up worlds. - if(hideFocusedMashupWorld()) + if(openServerOptions()) + { + break; + } + else if(hideFocusedMashupWorld()) { handled = true; } @@ -3291,6 +3316,11 @@ void UIScene_LoadCreateJoinMenu::handleInput(int iPad, int key, bool repeat, boo case ACTION_MENU_Y: #ifdef _WINDOWS64 + if(openServerOptions()) + { + break; + } + if(hideFocusedMashupWorld()) { handled = true; @@ -4317,51 +4347,7 @@ void UIScene_LoadCreateJoinMenu::CheckAndJoinGame(int gameIndex) #ifdef _WINDOWS64 - { - - - - int serverDbCount = 0; - - FILE* dbFile = fopen("servers.db", "rb"); - - if (dbFile) - - { - - char magic[4] = {}; - - if (fread(magic, 1, 4, dbFile) == 4 && memcmp(magic, "MCSV", 4) == 0) - - { - - uint32_t version = 0, count = 0; - - fread(&version, sizeof(uint32_t), 1, dbFile); - - fread(&count, sizeof(uint32_t), 1, dbFile); - - if (version == 1) - - serverDbCount = static_cast(count); - - } - - fclose(dbFile); - - } - - int lanCount = static_cast(m_currentSessions->size()) - serverDbCount; - - if (gameIndex >= lanCount && lanCount >= 0) - - m_initData->serverIndex = gameIndex - lanCount; - - else - - m_initData->serverIndex = -1; - - } + m_initData->serverIndex = m_initData->selectedSession->savedServerIndex; #endif @@ -4790,15 +4776,13 @@ void UIScene_LoadCreateJoinMenu::UpdateGamesList() +#if !defined(_WINDOWS64) // if we're retrieving save info, don't show the list yet as we will be ignoring press events - if(!m_bSavesDisplayed) - { - return; - } +#endif m_controlJoinTimer.setVisible( false ); @@ -5035,6 +5019,15 @@ void UIScene_LoadCreateJoinMenu::handleTimerComplete(int id) { +#ifdef _WINDOWS64 + if (m_currentSessions == nullptr) + { + UpdateGamesList(); + if (m_currentSessions == nullptr) + addTimer(JOIN_LOAD_ONLINE_TIMER_ID, JOIN_LOAD_ONLINE_TIMER_TIME); + } +#endif + #ifdef _XBOX XPARTY_USER_LIST partyList; @@ -8971,6 +8964,122 @@ int UIScene_LoadCreateJoinMenu::AddServerDoneCallback(LPVOID lpParam, bool confi return 0; } +FriendSessionInfo *UIScene_LoadCreateJoinMenu::GetSelectedSavedServer() +{ + if (!DoesGamesListHaveFocus() || m_currentSessions == nullptr) + return nullptr; + + const int selectedItem = m_buttonListGames.getCurrentSelection(); + const int sessionIndex = selectedItem - 1; + if (sessionIndex < 0 || sessionIndex >= static_cast(m_currentSessions->size())) + return nullptr; + + FriendSessionInfo *session = m_currentSessions->at(sessionIndex); + if (session == nullptr || session->savedServerIndex < 0) + return nullptr; + + m_selectedServerIndex = session->savedServerIndex; + return session; +} + +bool UIScene_LoadCreateJoinMenu::BeginServerOptions() +{ + if (GetSelectedSavedServer() == nullptr) + return false; + + m_bIgnoreInput = true; + UINT optionIds[3] = { IDS_CONFIRM_CANCEL, IDS_TITLE_RENAME, IDS_TOOLTIPS_DELETE }; + ui.RequestAlertMessage(IDS_TOOLTIPS_OPTIONS, IDS_TEXT_SAVEOPTIONS, optionIds, 3, m_iPad, + &UIScene_LoadCreateJoinMenu::ServerOptionsDialogReturned, this); + return true; +} + +int UIScene_LoadCreateJoinMenu::ServerOptionsDialogReturned(LPVOID lpParam, int iPad, C4JStorage::EMessageResult result) +{ + UIScene_LoadCreateJoinMenu *scene = static_cast(lpParam); + switch (result) + { + case C4JStorage::EMessage_ResultDecline: + scene->BeginEditServer(); + break; + case C4JStorage::EMessage_ResultThirdOption: + { + UINT confirmIds[2] = { IDS_CONFIRM_CANCEL, IDS_CONFIRM_OK }; + ui.RequestAlertMessage(IDS_TOOLTIPS_DELETE, IDS_TEXT_DELETE_SAVE, confirmIds, 2, iPad, + &UIScene_LoadCreateJoinMenu::DeleteServerDialogReturned, scene); + break; + } + default: + scene->m_bIgnoreInput = false; + scene->updateTooltips(); + break; + } + return 0; +} + +int UIScene_LoadCreateJoinMenu::DeleteServerDialogReturned(LPVOID lpParam, int, C4JStorage::EMessageResult result) +{ + UIScene_LoadCreateJoinMenu *scene = static_cast(lpParam); + if (result == C4JStorage::EMessage_ResultDecline && scene->RemoveServerFromFile()) + g_NetworkManager.ForceFriendsSessionRefresh(); + + scene->m_bIgnoreInput = false; + return 0; +} + +void UIScene_LoadCreateJoinMenu::BeginEditServer() +{ + FriendSessionInfo *session = nullptr; + if (m_currentSessions != nullptr) + { + for (FriendSessionInfo *candidate : *m_currentSessions) + { + if (candidate != nullptr && candidate->savedServerIndex == m_selectedServerIndex) + { + session = candidate; + break; + } + } + } + + if (session == nullptr) + { + m_bIgnoreInput = false; + app.DebugPrintf("The selected external server is no longer available."); + return; + } + + wchar_t address[256] = {}; + if (mbstowcs(address, session->data.hostIP, 255) == static_cast(-1)) + { + m_bIgnoreInput = false; + app.DebugPrintf("Could not decode the external server address."); + return; + } + + wchar_t port[16] = {}; + swprintf(port, 16, L"%d", session->data.hostPort); + + m_editServerData = EditServerInitData(); + m_editServerData.name = session->displayLabel != nullptr ? session->displayLabel : L""; + m_editServerData.address = address; + if (session->data.hostPort != 25565) + m_editServerData.address += L":" + wstring(port); + m_editServerData.callback = &UIScene_LoadCreateJoinMenu::EditServerDoneCallback; + m_editServerData.lpParam = this; + ui.NavigateToScene(m_iPad, eUIScene_EditServerMenu, &m_editServerData); +} + +int UIScene_LoadCreateJoinMenu::EditServerDoneCallback(LPVOID lpParam, bool confirmed, const wstring &name, const wstring &ip, const wstring &port) +{ + UIScene_LoadCreateJoinMenu *scene = static_cast(lpParam); + if (confirmed && scene->UpdateServerInFile(ip, port, name)) + g_NetworkManager.ForceFriendsSessionRefresh(); + + scene->m_bIgnoreInput = false; + return 0; +} + int UIScene_LoadCreateJoinMenu::AddServerKeyboardCallback(LPVOID lpParam, bool bRes) { @@ -9138,137 +9247,99 @@ void UIScene_LoadCreateJoinMenu::RefreshServerListHtmlPatch() { void UIScene_LoadCreateJoinMenu::AppendServerToFile(const wstring& ip, const wstring& port, const wstring& name) { - char narrowIP[256] = {}; - char narrowPort[16] = {}; - char narrowName[256] = {}; - - wcstombs(narrowIP, ip.c_str(), sizeof(narrowIP) - 1); - - wcstombs(narrowPort, port.c_str(), sizeof(narrowPort) - 1); - - wcstombs(narrowName, name.c_str(), sizeof(narrowName) - 1); - - - - uint16_t portNum = static_cast(atoi(narrowPort)); - - - - struct ServerEntry { std::string ip; uint16_t port; std::string name; }; - - std::vector entries; - - - - FILE* file = fopen("servers.db", "rb"); - - if (file) - + if (wcstombs(narrowIP, ip.c_str(), sizeof(narrowIP) - 1) == static_cast(-1) || + wcstombs(narrowPort, port.c_str(), sizeof(narrowPort) - 1) == static_cast(-1) || + wcstombs(narrowName, name.c_str(), sizeof(narrowName) - 1) == static_cast(-1)) { - - char magic[4] = {}; - - if (fread(magic, 1, 4, file) == 4 && memcmp(magic, "MCSV", 4) == 0) - - { - - uint32_t version = 0, count = 0; - - fread(&version, sizeof(uint32_t), 1, file); - - fread(&count, sizeof(uint32_t), 1, file); - - if (version == 1) - - { - - for (uint32_t s = 0; s < count; s++) - - { - - uint16_t ipLen = 0, p = 0, nameLen = 0; - - if (fread(&ipLen, sizeof(uint16_t), 1, file) != 1) break; - - if (ipLen == 0 || ipLen > 256) break; - - char ipBuf[257] = {}; - - if (fread(ipBuf, 1, ipLen, file) != ipLen) break; - - if (fread(&p, sizeof(uint16_t), 1, file) != 1) break; - - if (fread(&nameLen, sizeof(uint16_t), 1, file) != 1) break; - - if (nameLen > 256) break; - - char nameBuf[257] = {}; - - if (nameLen > 0 && fread(nameBuf, 1, nameLen, file) != nameLen) break; - - entries.push_back({std::string(ipBuf), p, std::string(nameBuf)}); - - } - - } - - } - - fclose(file); - + app.DebugPrintf("Could not encode the external server details."); + return; } - - - entries.push_back({std::string(narrowIP), portNum, std::string(narrowName)}); - - - - file = fopen("servers.db", "wb"); - - if (file) - + char* portEnd = nullptr; + unsigned long portNumber = strtoul(narrowPort, &portEnd, 10); + if (narrowIP[0] == '\0' || portEnd == narrowPort || *portEnd != '\0' || portNumber == 0 || portNumber > 65535) { - - fwrite("MCSV", 1, 4, file); - - uint32_t version = 1; - - uint32_t count = static_cast(entries.size()); - - fwrite(&version, sizeof(uint32_t), 1, file); - - fwrite(&count, sizeof(uint32_t), 1, file); - - - - for (size_t i = 0; i < entries.size(); i++) - - { - - uint16_t ipLen = static_cast(entries[i].ip.length()); - - fwrite(&ipLen, sizeof(uint16_t), 1, file); - - fwrite(entries[i].ip.c_str(), 1, ipLen, file); - - fwrite(&entries[i].port, sizeof(uint16_t), 1, file); - - uint16_t nameLen = static_cast(entries[i].name.length()); - - fwrite(&nameLen, sizeof(uint16_t), 1, file); - - fwrite(entries[i].name.c_str(), 1, nameLen, file); - - } - - fclose(file); - + app.DebugPrintf("The external server address or port is invalid."); + return; } + ExternalServerList::Entry entry = { narrowIP, static_cast(portNumber), narrowName }; + if (!ExternalServerList::Append(entry)) + app.DebugPrintf("Failed to save the external server list."); + +} + +bool UIScene_LoadCreateJoinMenu::UpdateServerInFile(const wstring& ip, const wstring& port, const wstring& name) +{ + char narrowIP[256] = {}; + char narrowPort[16] = {}; + char narrowName[256] = {}; + if (wcstombs(narrowIP, ip.c_str(), sizeof(narrowIP) - 1) == static_cast(-1) || + wcstombs(narrowPort, port.c_str(), sizeof(narrowPort) - 1) == static_cast(-1) || + wcstombs(narrowName, name.c_str(), sizeof(narrowName) - 1) == static_cast(-1)) + { + app.DebugPrintf("Could not encode the external server details."); + return false; + } + + char* portEnd = nullptr; + unsigned long portNumber = strtoul(narrowPort, &portEnd, 10); + if (narrowIP[0] == '\0' || portEnd == narrowPort || *portEnd != '\0' || portNumber == 0 || portNumber > 65535) + { + app.DebugPrintf("The external server address or port is invalid."); + return false; + } + + std::vector entries; + if (!ExternalServerList::Read(entries)) + { + app.DebugPrintf("Failed to read the external server list."); + return false; + } + if (m_selectedServerIndex < 0 || static_cast(m_selectedServerIndex) >= entries.size()) + { + app.DebugPrintf("The selected external server no longer exists."); + return false; + } + + ExternalServerList::Entry& entry = entries[m_selectedServerIndex]; + entry.address = narrowIP; + entry.port = static_cast(portNumber); + entry.name = narrowName; + if (!ExternalServerList::Write(entries)) + { + app.DebugPrintf("Failed to update the external server list."); + return false; + } + + return true; +} + +bool UIScene_LoadCreateJoinMenu::RemoveServerFromFile() +{ + std::vector entries; + if (!ExternalServerList::Read(entries)) + { + app.DebugPrintf("Failed to read the external server list."); + return false; + } + if (m_selectedServerIndex < 0 || static_cast(m_selectedServerIndex) >= entries.size()) + { + app.DebugPrintf("The selected external server no longer exists."); + return false; + } + + entries.erase(entries.begin() + m_selectedServerIndex); + if (!ExternalServerList::Write(entries)) + { + app.DebugPrintf("Failed to update the external server list."); + return false; + } + + return true; } #endif // _WINDOWS64 diff --git a/Minecraft.Client/Common/UI/UIScene_LoadCreateJoinMenu.h b/Minecraft.Client/Common/UI/UIScene_LoadCreateJoinMenu.h index c4690206..180e9f14 100644 --- a/Minecraft.Client/Common/UI/UIScene_LoadCreateJoinMenu.h +++ b/Minecraft.Client/Common/UI/UIScene_LoadCreateJoinMenu.h @@ -270,11 +270,20 @@ private: eAddServerPhase m_addServerPhase; wstring m_addServerIP; wstring m_addServerPort; + int m_selectedServerIndex; void BeginAddServer(); + FriendSessionInfo *GetSelectedSavedServer(); + bool BeginServerOptions(); + void BeginEditServer(); + bool UpdateServerInFile(const wstring& ip, const wstring& port, const wstring& name); + bool RemoveServerFromFile(); void AppendServerToFile(const wstring& ip, const wstring& port, const wstring& name); static int AddServerKeyboardCallback(LPVOID lpParam, bool bRes); EditServerInitData m_editServerData; static int AddServerDoneCallback(LPVOID lpParam, bool confirmed, const wstring &name, const wstring &ip, const wstring &port); + static int ServerOptionsDialogReturned(LPVOID lpParam, int iPad, C4JStorage::EMessageResult result); + static int DeleteServerDialogReturned(LPVOID lpParam, int iPad, C4JStorage::EMessageResult result); + static int EditServerDoneCallback(LPVOID lpParam, bool confirmed, const wstring &name, const wstring &ip, const wstring &port); void RefreshServerListHtmlPatch(); #endif diff --git a/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp b/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp index 558f6c3e..4346d371 100644 --- a/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp @@ -28,6 +28,7 @@ #ifdef _WINDOWS64 #include "../../../Minecraft.World/NbtIo.h" #include "../../../Minecraft.World/compression.h" +#include "../Network/ExternalServerList.h" static wstring ReadLevelNameFromSaveFile(const wstring& filePath, bool *outHardcore = nullptr) { @@ -1811,29 +1812,7 @@ void UIScene_LoadOrJoinMenu::CheckAndJoinGame(int gameIndex) m_initData->iPad = 0;; m_initData->selectedSession = m_currentSessions->at( gameIndex ); #ifdef _WINDOWS64 - { - - int serverDbCount = 0; - FILE* dbFile = fopen("servers.db", "rb"); - if (dbFile) - { - char magic[4] = {}; - if (fread(magic, 1, 4, dbFile) == 4 && memcmp(magic, "MCSV", 4) == 0) - { - uint32_t version = 0, count = 0; - fread(&version, sizeof(uint32_t), 1, dbFile); - fread(&count, sizeof(uint32_t), 1, dbFile); - if (version == 1) - serverDbCount = static_cast(count); - } - fclose(dbFile); - } - int lanCount = static_cast(m_currentSessions->size()) - serverDbCount; - if (gameIndex >= lanCount && lanCount >= 0) - m_initData->serverIndex = gameIndex - lanCount; - else - m_initData->serverIndex = -1; - } + m_initData->serverIndex = m_initData->selectedSession->savedServerIndex; #endif if(m_initData->selectedSession->data.texturePackParentId!=0) @@ -1967,11 +1946,13 @@ void UIScene_LoadOrJoinMenu::UpdateGamesList() // If a texture pack is loading, or will be loading, then ignore this ( we are going to be destroyed anyway) if( Minecraft::GetInstance()->skins->getSelected()->isLoadingData() || (Minecraft::GetInstance()->skins->needsUIUpdate() || ui.IsReloadingSkin()) ) return; +#if !defined(_WINDOWS64) // if we're retrieving save info, don't show the list yet as we will be ignoring press events if(!m_bSavesDisplayed) { return; } +#endif FriendSessionInfo *pSelectedSession = nullptr; @@ -2199,6 +2180,15 @@ void UIScene_LoadOrJoinMenu::handleTimerComplete(int id) { case JOIN_LOAD_ONLINE_TIMER_ID: { +#ifdef _WINDOWS64 + if (m_currentSessions == nullptr) + { + UpdateGamesList(); + if (m_currentSessions == nullptr) + addTimer(JOIN_LOAD_ONLINE_TIMER_ID, JOIN_LOAD_ONLINE_TIMER_TIME); + } +#endif + #ifdef _XBOX XPARTY_USER_LIST partyList; @@ -4286,67 +4276,24 @@ void UIScene_LoadOrJoinMenu::AppendServerToFile(const wstring& ip, const wstring char narrowIP[256] = {}; char narrowPort[16] = {}; char narrowName[256] = {}; - wcstombs(narrowIP, ip.c_str(), sizeof(narrowIP) - 1); - wcstombs(narrowPort, port.c_str(), sizeof(narrowPort) - 1); - wcstombs(narrowName, name.c_str(), sizeof(narrowName) - 1); - - uint16_t portNum = static_cast(atoi(narrowPort)); - - struct ServerEntry { std::string ip; uint16_t port; std::string name; }; - std::vector entries; - - FILE* file = fopen("servers.db", "rb"); - if (file) + if (wcstombs(narrowIP, ip.c_str(), sizeof(narrowIP) - 1) == static_cast(-1) || + wcstombs(narrowPort, port.c_str(), sizeof(narrowPort) - 1) == static_cast(-1) || + wcstombs(narrowName, name.c_str(), sizeof(narrowName) - 1) == static_cast(-1)) { - char magic[4] = {}; - if (fread(magic, 1, 4, file) == 4 && memcmp(magic, "MCSV", 4) == 0) - { - uint32_t version = 0, count = 0; - fread(&version, sizeof(uint32_t), 1, file); - fread(&count, sizeof(uint32_t), 1, file); - if (version == 1) - { - for (uint32_t s = 0; s < count; s++) - { - uint16_t ipLen = 0, p = 0, nameLen = 0; - if (fread(&ipLen, sizeof(uint16_t), 1, file) != 1) break; - if (ipLen == 0 || ipLen > 256) break; - char ipBuf[257] = {}; - if (fread(ipBuf, 1, ipLen, file) != ipLen) break; - if (fread(&p, sizeof(uint16_t), 1, file) != 1) break; - if (fread(&nameLen, sizeof(uint16_t), 1, file) != 1) break; - if (nameLen > 256) break; - char nameBuf[257] = {}; - if (nameLen > 0 && fread(nameBuf, 1, nameLen, file) != nameLen) break; - entries.push_back({std::string(ipBuf), p, std::string(nameBuf)}); - } - } - } - fclose(file); + app.DebugPrintf("Could not encode the external server details."); + return; } - entries.push_back({std::string(narrowIP), portNum, std::string(narrowName)}); - - file = fopen("servers.db", "wb"); - if (file) + char* portEnd = nullptr; + unsigned long portNumber = strtoul(narrowPort, &portEnd, 10); + if (narrowIP[0] == '\0' || portEnd == narrowPort || *portEnd != '\0' || portNumber == 0 || portNumber > 65535) { - fwrite("MCSV", 1, 4, file); - uint32_t version = 1; - uint32_t count = static_cast(entries.size()); - fwrite(&version, sizeof(uint32_t), 1, file); - fwrite(&count, sizeof(uint32_t), 1, file); - - for (size_t i = 0; i < entries.size(); i++) - { - uint16_t ipLen = static_cast(entries[i].ip.length()); - fwrite(&ipLen, sizeof(uint16_t), 1, file); - fwrite(entries[i].ip.c_str(), 1, ipLen, file); - fwrite(&entries[i].port, sizeof(uint16_t), 1, file); - uint16_t nameLen = static_cast(entries[i].name.length()); - fwrite(&nameLen, sizeof(uint16_t), 1, file); - fwrite(entries[i].name.c_str(), 1, nameLen, file); - } - fclose(file); + app.DebugPrintf("The external server address or port is invalid."); + return; } + + ExternalServerList::Entry entry = { narrowIP, static_cast(portNumber), narrowName }; + if (!ExternalServerList::Append(entry)) + app.DebugPrintf("Failed to save the external server list."); } #endif // _WINDOWS64 \ No newline at end of file diff --git a/Minecraft.Client/Extrax64Stubs.cpp b/Minecraft.Client/Extrax64Stubs.cpp index 9119129b..188ee961 100644 --- a/Minecraft.Client/Extrax64Stubs.cpp +++ b/Minecraft.Client/Extrax64Stubs.cpp @@ -1,4 +1,5 @@ #include "stdafx.h" +#include "Common/Network/GameNetworkManager.h" #ifndef __PS3__ //#include #endif // __PS3__ @@ -20,7 +21,6 @@ #include "StatsCounter.h" #include "Windows64/Social/SocialManager.h" #include "Windows64/Sentient/DynamicConfigurations.h" -#include "Windows64/Network/WinsockNetLayer.h" #include "Windows64/Windows64_Xuid.h" #elif defined __PSVITA__ #include "PSVita/Sentient/SentientManager.h" @@ -193,30 +193,16 @@ D3DXVECTOR3& D3DXVECTOR3::operator += (CONST D3DXVECTOR3 & add) { x += add.x; y BYTE IQNetPlayer::GetSmallId() { return m_smallId; } void IQNetPlayer::SendData(IQNetPlayer * player, const void* pvData, DWORD dwDataSize, DWORD dwFlags) { - if (WinsockNetLayer::IsActive()) - { - if (!WinsockNetLayer::IsHosting() && !m_isRemote) - { - // Client sending to server via local socket (bypasses SendToSmallId) - SOCKET sock = WinsockNetLayer::GetLocalSocket(m_smallId); - if (sock != INVALID_SOCKET) - { - // Encrypt if client send cipher is active - if (dwDataSize > 0) - { - WinsockNetLayer::SendOnSocket(m_smallId, sock, pvData, dwDataSize); - } - else - { - WinsockNetLayer::SendOnSocket(m_smallId, sock, pvData, dwDataSize); - } - } - } - else - { - WinsockNetLayer::SendToSmallId(player->m_smallId, pvData, dwDataSize); - } - } + if (player == nullptr || pvData == nullptr || dwDataSize == 0) + return; + + INetworkPlayer* source = g_NetworkManager.GetPlayerBySmallId(m_smallId); + INetworkPlayer* target = g_NetworkManager.GetPlayerBySmallId(player->m_smallId); + if (source == nullptr || target == nullptr) + return; + + const bool lowPriority = (dwFlags & QNET_SENDDATA_LOW_PRIORITY) != 0; + source->SendData(target, pvData, static_cast(dwDataSize), lowPriority, false); } bool IQNetPlayer::IsSameSystem(IQNetPlayer * player) { return (this == player) || (!m_isRemote && !player->m_isRemote); } DWORD IQNetPlayer::GetSendQueueSize(IQNetPlayer * player, DWORD dwFlags) { return 0; } @@ -291,31 +277,25 @@ IQNetPlayer* IQNet::GetLocalPlayerByUserIndex(DWORD dwUserIndex) return &m_player[dwUserIndex]; return nullptr; } + INetworkPlayer* localNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(dwUserIndex); + if (localNetworkPlayer != nullptr) + { + DWORD idx = localNetworkPlayer->GetSmallId(); + if (idx < MINECRAFT_NET_MAX_PLAYERS && + !m_player[idx].m_isRemote && + Win64_IsActivePlayer(&m_player[idx], idx)) + return &m_player[idx]; + return nullptr; + } if (dwUserIndex == 0) { - // Primary pad: use direct index when networking is active (smallId may not be 0) - if (WinsockNetLayer::IsActive()) - { - DWORD idx = WinsockNetLayer::GetLocalSmallId(); - if (idx < MINECRAFT_NET_MAX_PLAYERS && - !m_player[idx].m_isRemote && - Win64_IsActivePlayer(&m_player[idx], idx)) - return &m_player[idx]; - return nullptr; - } - // Offline: scan for first local player + // Offline: scan for the first local player. for (DWORD i = 0; i < s_playerCount; i++) { if (!m_player[i].m_isRemote && Win64_IsActivePlayer(&m_player[i], i)) return &m_player[i]; } - return nullptr; } - // Split-screen pads 1-3: the player is at m_player[dwUserIndex] with isRemote=false - if (dwUserIndex < MINECRAFT_NET_MAX_PLAYERS && - !m_player[dwUserIndex].m_isRemote && - Win64_IsActivePlayer(&m_player[dwUserIndex], dwUserIndex)) - return &m_player[dwUserIndex]; return nullptr; } static bool Win64_IsActivePlayer(IQNetPlayer * p, DWORD index) diff --git a/Minecraft.Client/Minecraft.cpp b/Minecraft.Client/Minecraft.cpp index 51b25a5a..4ffc9602 100644 --- a/Minecraft.Client/Minecraft.cpp +++ b/Minecraft.Client/Minecraft.cpp @@ -67,7 +67,6 @@ #include "../Minecraft.World/ChestTileEntity.h" #include "TextureManager.h" #ifdef _XBOX -#include "Xbox/Network/NetworkPlayerXbox.h" #endif #include "Common/UI/IUIScene_CreativeMenu.h" #include "Common/UI/UIFontData.h" @@ -1400,7 +1399,7 @@ void Minecraft::run_middle() INetworkPlayer *pHostPlayer = g_NetworkManager.GetHostPlayer(); #ifdef _XBOX - PlayerUID xuid=((NetworkPlayerXbox *)pHostPlayer)->GetUID(); + PlayerUID xuid = pHostPlayer->GetUID(); #else PlayerUID xuid=pHostPlayer->GetUID(); #endif diff --git a/Minecraft.Client/MinecraftServer.cpp b/Minecraft.Client/MinecraftServer.cpp index 40e9aee6..c8ecbd03 100644 --- a/Minecraft.Client/MinecraftServer.cpp +++ b/Minecraft.Client/MinecraftServer.cpp @@ -32,7 +32,8 @@ #include "../Minecraft.World/net.minecraft.world.item.enchantment.h" #include "../Minecraft.World/net.minecraft.world.damagesource.h" #ifdef _WINDOWS64 -#include "Windows64/Network/WinsockNetLayer.h" +#include "Windows64/Network/PlatformNetworkManagerWindows.h" +#include "Windows64/Network/WindowsNetworkConfig.h" #endif #if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) #include "../Minecraft.Server/ServerLogger.h" @@ -700,7 +701,8 @@ bool MinecraftServer::initServer(int64_t seed, NetworkGameInitData *initData, DW #ifdef _WINDOWS64 { int maxP = getPlayerList()->getMaxPlayers(); - WinsockNetLayer::UpdateAdvertiseMaxPlayers((BYTE)(maxP > 255 ? 255 : maxP)); + if (g_pPlatformNetworkManagerWindows != nullptr) + g_pPlatformNetworkManagerWindows->UpdateMaxPlayers(static_cast(maxP > 255 ? 255 : maxP)); } #endif diff --git a/Minecraft.Client/PendingConnection.cpp b/Minecraft.Client/PendingConnection.cpp index 9a6c3230..86fce3c2 100644 --- a/Minecraft.Client/PendingConnection.cpp +++ b/Minecraft.Client/PendingConnection.cpp @@ -15,12 +15,15 @@ #include "../Minecraft.World/SharedConstants.h" #include "Settings.h" #if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) +#include +#include +#include "Common/Network/GameNetworkManager.h" #include "../Minecraft.Server/ServerLogManager.h" #include "../Minecraft.Server/Access/Access.h" #include "../Minecraft.Server/Security/SecurityConfig.h" #include "../Minecraft.World/Socket.h" +#include "Windows64/Network/NetworkPlayerWindows.h" #include -#include #endif // #ifdef __PS3__ // #include "PS3/Network/NetworkPlayerSony.h" @@ -35,6 +38,12 @@ bool g_bRejectDuplicateNames = true; #if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) namespace { + static SOCKET GetWindowsTransportSocket(unsigned char smallId) + { + NetworkPlayerWindows* player = dynamic_cast(g_NetworkManager.GetPlayerBySmallId(smallId)); + return player != nullptr ? player->GetTransportSocket() : INVALID_SOCKET; + } + static unsigned char GetPendingConnectionSmallId(Connection *connection) { if (connection != nullptr) @@ -125,7 +134,7 @@ void PendingConnection::handlePreLogin(shared_ptr packet) if (smallId != 0) { if (!ServerRuntime::ServerLogManager::TryGetConnectionRemoteIp(smallId, &connectionIp)) { - SOCKET sock = WinsockNetLayer::GetSocketForSmallId(smallId); + SOCKET sock = GetWindowsTransportSocket(smallId); if (sock != INVALID_SOCKET) { sockaddr_in addr; @@ -141,7 +150,7 @@ void PendingConnection::handlePreLogin(shared_ptr packet) } } } else { - SOCKET sock = WinsockNetLayer::GetSocketForSmallId(smallId); + SOCKET sock = GetWindowsTransportSocket(smallId); if (sock != INVALID_SOCKET) { sockaddr_in addr; @@ -269,7 +278,7 @@ void PendingConnection::handleLogin(shared_ptr packet) if (!ServerRuntime::ServerLogManager::TryGetConnectionRemoteIp(smallId, &connectionIp)) { - SOCKET sock = WinsockNetLayer::GetSocketForSmallId(smallId); + SOCKET sock = GetWindowsTransportSocket(smallId); if (sock != INVALID_SOCKET) { sockaddr_in addr; @@ -290,7 +299,7 @@ void PendingConnection::handleLogin(shared_ptr packet) } } else { - SOCKET sock = WinsockNetLayer::GetSocketForSmallId(smallId); + SOCKET sock = GetWindowsTransportSocket(smallId); if (sock != INVALID_SOCKET) { sockaddr_in addr; @@ -519,7 +528,7 @@ void PendingConnection::handleAcceptedLogin(shared_ptr packet) if (!ServerRuntime::ServerLogManager::TryGetConnectionRemoteIp(smallId, &connectionIp)) { - SOCKET sock = WinsockNetLayer::GetSocketForSmallId(smallId); + SOCKET sock = GetWindowsTransportSocket(smallId); if (sock != INVALID_SOCKET) { sockaddr_in addr; @@ -540,7 +549,7 @@ void PendingConnection::handleAcceptedLogin(shared_ptr packet) } } else { - SOCKET sock = WinsockNetLayer::GetSocketForSmallId(smallId); + SOCKET sock = GetWindowsTransportSocket(smallId); if (sock != INVALID_SOCKET) { sockaddr_in addr; diff --git a/Minecraft.Client/PlayerList.cpp b/Minecraft.Client/PlayerList.cpp index fee26c7b..027095ba 100644 --- a/Minecraft.Client/PlayerList.cpp +++ b/Minecraft.Client/PlayerList.cpp @@ -20,7 +20,7 @@ #include "../Minecraft.World/net.minecraft.network.h" #include "Windows64/Windows64_Xuid.h" #ifdef _WINDOWS64 -#include "Windows64/Network/WinsockNetLayer.h" +#include "Windows64/Network/PlatformNetworkManagerWindows.h" #endif #include "../Minecraft.World/Pos.h" #include "../Minecraft.World/ProgressListener.h" @@ -31,8 +31,10 @@ #include "../Minecraft.World/net.minecraft.world.level.saveddata.h" #include "../Minecraft.World/JavaMath.h" #include "../Minecraft.World/EntityIO.h" -#if defined(_XBOX) || defined(_WINDOWS64) +#if defined(_XBOX) #include "Xbox/Network/NetworkPlayerXbox.h" +#elif defined(_WINDOWS64) +#include "Windows64/Network/NetworkPlayerWindows.h" #elif defined(__PS3__) || defined(__ORBIS__) #include "Common/Network/Sony/NetworkPlayerSony.h" #endif @@ -151,15 +153,16 @@ bool PlayerList::placeNewPlayer(Connection *connection, shared_ptr #ifdef _WINDOWS64 if (networkPlayer != nullptr) { - NetworkPlayerXbox* nxp = static_cast(networkPlayer); - IQNetPlayer* qnp = nxp->GetQNetPlayer(); - if (qnp != nullptr) + NetworkPlayerWindows* windowsPlayer = dynamic_cast(networkPlayer); + if (windowsPlayer != nullptr) { if (!networkPlayer->IsLocal()) { - wcsncpy_s(qnp->m_gamertag, 32, player->name.c_str(), _TRUNCATE); + windowsPlayer->SetDisplayName(player->name); } - qnp->m_resolvedXuid = player->getXuid(); + windowsPlayer->SetUID(networkPlayer->IsHost() + ? Win64Xuid::GetLegacyEmbeddedHostXuid() + : player->getXuid()); } } #endif @@ -872,8 +875,6 @@ shared_ptr PlayerList::respawn(shared_ptr serverPlay player->connection->send( std::make_shared( static_cast(player->dimension), player->level->getSeed(), player->level->getMaxBuildHeight(), player->gameMode->getGameModeForPlayer(), level->difficulty, level->getLevelData()->getGenerator(), player->level->useNewSeaLevel(), player->entityId, level->getLevelData()->getXZSize(), level->getLevelData()->getHellScale(), level->getLevelData()->isHardcore(), level->getLevelData()->isModernEnd() ) ); - player->connection->teleport(player->x, player->y, player->z, player->yRot, player->xRot); - player->connection->send( std::make_shared( player->experienceProgress, player->totalExperience, player->experienceLevel) ); if(keepAllPlayerData) { @@ -894,6 +895,10 @@ shared_ptr PlayerList::respawn(shared_ptr serverPlay players.push_back(player); LeaveCriticalSection(&m_playersCS); + player->doTick(true, true, true); + player->connection->teleport(player->x, player->y, player->z, player->yRot, player->xRot); + player->connection->send( std::make_shared( player->experienceProgress, player->totalExperience, player->experienceLevel) ); + player->initMenu(); player->setHealth(player->getHealth()); @@ -1201,8 +1206,8 @@ void PlayerList::tick() // The old Connection's read/write threads are now dead (disconnect waits // for them). Safe to recycle the smallId — no stale write thread can // resolve getPlayer() to a new connection that reuses this slot. - WinsockNetLayer::PushFreeSmallId(smallId); - WinsockNetLayer::ClearSocketForSmallId(smallId); + if (g_pPlatformNetworkManagerWindows != nullptr) + g_pPlatformNetworkManagerWindows->ReleaseSmallId(smallId); #endif } } diff --git a/Minecraft.Client/Windows64/Network/NetworkPlayerWindows.cpp b/Minecraft.Client/Windows64/Network/NetworkPlayerWindows.cpp new file mode 100644 index 00000000..85e7c76a --- /dev/null +++ b/Minecraft.Client/Windows64/Network/NetworkPlayerWindows.cpp @@ -0,0 +1,287 @@ +#include "stdafx.h" + +#ifdef _WINDOWS64 + +#include "NetworkPlayerWindows.h" +#include "..\..\..\Minecraft.World\Socket.h" +#include "..\Windows64_Xuid.h" +#include +#include + +NetworkPlayerWindows::NetworkPlayerWindows(int userIndex, unsigned char smallId, bool isLocal, bool isHost, const std::wstring& name) { + m_name = name; + m_userIndex = userIndex; + m_smallId = smallId; + m_uid = INVALID_XUID; + m_hasResolvedUID = false; + m_lastChunkPacketTick = 0; + + m_isLocal = isLocal; + m_isHost = isHost; + m_isHostTransport = isHost; + m_isFakeHost = false; + + m_sessionIndex = -1; + m_remoteAddress = 0; + m_sendQueueOffset = 0; + m_sendQueueBytes = 0; + m_gameSocket = nullptr; + m_connected = true; + m_transportSocket = INVALID_SOCKET; + RefreshUID(); +} + +NetworkPlayerWindows::~NetworkPlayerWindows() { + CloseTransport(m_isHost); +} + +unsigned char NetworkPlayerWindows::GetSmallId() { return m_smallId; } + +NetworkPlayerWindows* NetworkPlayerWindows::GetTransportPlayer(INetworkPlayer* player) { + if (m_isHostTransport) { + return dynamic_cast(player); + } + return this; +} + +void NetworkPlayerWindows::SendData(INetworkPlayer* player, const void* pvData, int dataSize, bool lowPriority, bool ack) { + (void)ack; + NetworkPlayerWindows* transportPlayer = GetTransportPlayer(player); + if (transportPlayer == nullptr || pvData == nullptr || dataSize <= 0) return; + + if (transportPlayer->m_transportSocket.load() == INVALID_SOCKET || !transportPlayer->m_connected.load()) { + app.DebugPrintf("Windows network send skipped: player has no active TCP connection."); + return; + } + + std::vector message(dataSize); + memcpy(message.data(), pvData, dataSize); + + std::lock_guard lock(transportPlayer->m_sendQueueMutex); + transportPlayer->m_sendQueueBytes += message.size(); + transportPlayer->m_sendQueue.push_back(std::move(message)); +} + +bool NetworkPlayerWindows::IsSameSystem(INetworkPlayer* player) { + NetworkPlayerWindows* other = dynamic_cast(player); + return other != nullptr && (this == other || m_remoteAddress == other->m_remoteAddress); +} + +int NetworkPlayerWindows::GetOutstandingAckCount() { return 0; } + +int NetworkPlayerWindows::GetQueueSizeBytes() { + std::lock_guard lock(m_sendQueueMutex); + return static_cast(std::min(m_sendQueueBytes, INT_MAX)); +} + +int NetworkPlayerWindows::GetQueueSizeMessages() { + std::lock_guard lock(m_sendQueueMutex); + return static_cast(std::min(m_sendQueue.size(), INT_MAX)); +} + +int NetworkPlayerWindows::GetSendQueueSizeBytes(INetworkPlayer* player, bool lowPriority) { + NetworkPlayerWindows* transportPlayer = GetTransportPlayer(player); + if (transportPlayer == nullptr) return 0; + + return transportPlayer->GetQueueSizeBytes(); +} + +int NetworkPlayerWindows::GetSendQueueSizeMessages(INetworkPlayer* player, bool lowPriority) { + NetworkPlayerWindows* transportPlayer = GetTransportPlayer(player); + if (transportPlayer == nullptr) return 0; + + return transportPlayer->GetQueueSizeMessages(); +} + +int NetworkPlayerWindows::GetCurrentRtt() { return 0; } + +bool NetworkPlayerWindows::IsHost() { return m_isHost; } +bool NetworkPlayerWindows::IsFakeHost() { return m_isFakeHost; } +bool NetworkPlayerWindows::IsGuest() { return false; } +bool NetworkPlayerWindows::IsLocal() { return m_isLocal; } +int NetworkPlayerWindows::GetSessionIndex() { return m_sessionIndex; } + +bool NetworkPlayerWindows::IsTalking() { return false; } +bool NetworkPlayerWindows::IsMutedByLocalUser(int userIndex) { return false; } +bool NetworkPlayerWindows::HasVoice() { return false; } +bool NetworkPlayerWindows::HasCamera() { return false; } + +int NetworkPlayerWindows::GetUserIndex() { return m_userIndex; } + +void NetworkPlayerWindows::SetSocket(Socket* pSocket) { m_gameSocket = pSocket; } +Socket* NetworkPlayerWindows::GetSocket() { return m_gameSocket; } + +const wchar_t* NetworkPlayerWindows::GetOnlineName() { return m_name.c_str(); } +std::wstring NetworkPlayerWindows::GetDisplayName() { return m_name; } + +PlayerUID NetworkPlayerWindows::GetUID() { return m_uid; } + +void NetworkPlayerWindows::SentChunkPacket() { m_lastChunkPacketTick = GetTickCount64(); } +int NetworkPlayerWindows::GetTimeSinceLastChunkPacket_ms() { + if (m_lastChunkPacketTick == 0) return INT_MAX; + ULONGLONG elapsed = GetTickCount64() - m_lastChunkPacketTick; + return elapsed > static_cast(INT_MAX) ? INT_MAX : static_cast(elapsed); +} + +void NetworkPlayerWindows::SetHost(bool isHost) { + m_isHost = isHost; + if (!m_hasResolvedUID) RefreshUID(); + if (m_smallId < MINECRAFT_NET_MAX_PLAYERS) { + IQNet::m_player[m_smallId].m_isHostPlayer = isHost; + IQNet::m_player[m_smallId].m_resolvedXuid = m_uid; + } +} +void NetworkPlayerWindows::SetHostTransport(bool isServer) { m_isHostTransport = isServer; } +void NetworkPlayerWindows::SetFakeHost(bool isFakeHost) { m_isFakeHost = isFakeHost; } +void NetworkPlayerWindows::SetSmallId(unsigned char smallId) { + m_smallId = smallId; + if (!m_hasResolvedUID) RefreshUID(); + if (m_smallId < MINECRAFT_NET_MAX_PLAYERS) { + IQNet::m_player[m_smallId].m_smallId = m_smallId; + IQNet::m_player[m_smallId].m_resolvedXuid = m_uid; + } +} +void NetworkPlayerWindows::SetUID(PlayerUID uid) { + m_uid = uid; + m_hasResolvedUID = true; + if (m_smallId < MINECRAFT_NET_MAX_PLAYERS) + IQNet::m_player[m_smallId].m_resolvedXuid = uid; +} +void NetworkPlayerWindows::SetDisplayName(const std::wstring& name) { + m_name = name; + if (m_smallId < MINECRAFT_NET_MAX_PLAYERS) + wcsncpy_s(IQNet::m_player[m_smallId].m_gamertag, 32, name.c_str(), _TRUNCATE); +} + +void NetworkPlayerWindows::SetSessionIndex(int index) { m_sessionIndex = index; } + +void NetworkPlayerWindows::ResetForSession(bool isHost, unsigned char smallId) { + m_isHost = isHost; + m_isHostTransport = isHost; + m_isFakeHost = false; + SetSmallId(smallId); + m_gameSocket = nullptr; + m_remoteAddress = 0; + m_connected.store(true); + std::lock_guard lock(m_sendQueueMutex); + m_sendQueue.clear(); + m_sendQueueOffset = 0; + m_sendQueueBytes = 0; +} + +void NetworkPlayerWindows::SetTransportSocket(SOCKET socket, unsigned long remoteAddress) { + std::lock_guard lock(m_transportMutex); + m_transportSocket.store(socket); + m_remoteAddress = remoteAddress; + m_connected.store(socket != INVALID_SOCKET); +} + +SOCKET NetworkPlayerWindows::GetTransportSocket() const { return m_transportSocket.load(); } + +bool NetworkPlayerWindows::IsConnected() const { return m_connected.load(); } + +bool NetworkPlayerWindows::ReceivePendingData(bool hostIsServer) { + char buffer[8192]; + while (true) { + int bytesReceived; + { + std::lock_guard lock(m_transportMutex); + SOCKET socket = m_transportSocket.load(); + if (socket == INVALID_SOCKET || !m_connected.load()) { + return false; + } + bytesReceived = recv(socket, buffer, sizeof(buffer), 0); + } + + if (bytesReceived > 0) { + if (m_gameSocket == nullptr) { + app.DebugPrintf("Windows network data received before the game socket was created."); + return false; + } + m_gameSocket->pushDataToQueue(reinterpret_cast(buffer), bytesReceived, !hostIsServer); + continue; + } + + if (bytesReceived == 0) return false; + + int error = WSAGetLastError(); + if (error == WSAEWOULDBLOCK) return true; + if (error == WSAEINTR) continue; + + return false; + } +} + +bool NetworkPlayerWindows::FlushSendQueue() +{ + std::lock_guard transportLock(m_transportMutex); + SOCKET socket = m_transportSocket.load(); + if (socket == INVALID_SOCKET || !m_connected.load()) return false; + + std::lock_guard queueLock(m_sendQueueMutex); + while (!m_sendQueue.empty()) { + std::vector& message = m_sendQueue.front(); + int remaining = static_cast(message.size() - m_sendQueueOffset); + int bytesSent = send(socket, message.data() + m_sendQueueOffset, remaining, 0); + if (bytesSent > 0) { + m_sendQueueOffset += bytesSent; + m_sendQueueBytes -= bytesSent; + if (m_sendQueueOffset == message.size()) { + m_sendQueue.pop_front(); + m_sendQueueOffset = 0; + } + continue; + } + + if (bytesSent == 0) return false; + + int error = WSAGetLastError(); + if (error == WSAEWOULDBLOCK) return true; + if (error == WSAEINTR) continue; + + return false; + } + return true; +} + +void NetworkPlayerWindows::CloseTransport(bool isServerConnection) { + FlushSendQueue(); + + Socket* gameSocket = nullptr; + { + std::lock_guard lock(m_transportMutex); + SOCKET socket = m_transportSocket.exchange(INVALID_SOCKET); + bool wasConnected = m_connected.exchange(false); + if (socket != INVALID_SOCKET) { + shutdown(socket, SD_BOTH); + closesocket(socket); + } + + if (wasConnected) { + gameSocket = m_gameSocket; + m_gameSocket = nullptr; + } + } + + if (gameSocket != nullptr) { + InputStream* input = gameSocket->getInputStream(isServerConnection); + Socket::SocketOutputStream* output = gameSocket->getOutputStream(isServerConnection); + if (input != nullptr) input->close(); + if (output != nullptr) output->close(); + gameSocket->close(isServerConnection); + } +} + +void NetworkPlayerWindows::RefreshUID() { + if (m_isHost) { + m_uid = Win64Xuid::GetLegacyEmbeddedHostXuid(); + } else if (m_userIndex >= 0 && m_userIndex < XUSER_MAX_COUNT) { + m_uid = Win64Xuid::DeriveXuidForPad(Win64Xuid::ResolvePersistentXuid(), m_userIndex); + } else { + m_uid = Win64Xuid::GetLegacyEmbeddedBaseXuid() + m_smallId; + } + if (m_smallId < MINECRAFT_NET_MAX_PLAYERS) + IQNet::m_player[m_smallId].m_resolvedXuid = m_uid; +} + +#endif \ No newline at end of file diff --git a/Minecraft.Client/Windows64/Network/NetworkPlayerWindows.h b/Minecraft.Client/Windows64/Network/NetworkPlayerWindows.h new file mode 100644 index 00000000..b497ec98 --- /dev/null +++ b/Minecraft.Client/Windows64/Network/NetworkPlayerWindows.h @@ -0,0 +1,91 @@ +#pragma once + +#ifdef _WINDOWS64 + +#include +#include +#include +#include +#include +#include + +#include "..\..\Common\Network\NetworkPlayerInterface.h" + +class Socket; + +class NetworkPlayerWindows : public INetworkPlayer { +public: + NetworkPlayerWindows(int userIndex, unsigned char smallId, bool isLocal, bool isHost, const std::wstring& name); + virtual ~NetworkPlayerWindows(); + + virtual unsigned char GetSmallId(); + virtual void SendData(INetworkPlayer* player, const void* pvData, int dataSize, bool lowPriority, bool ack); + virtual bool IsSameSystem(INetworkPlayer* player); + virtual int GetOutstandingAckCount(); + virtual int GetSendQueueSizeBytes(INetworkPlayer* player, bool lowPriority); + virtual int GetSendQueueSizeMessages(INetworkPlayer* player, bool lowPriority); + virtual int GetCurrentRtt(); + virtual bool IsHost(); + virtual bool IsFakeHost(); + virtual bool IsGuest(); + virtual bool IsLocal(); + virtual int GetSessionIndex(); + virtual bool IsTalking(); + virtual bool IsMutedByLocalUser(int userIndex); + virtual bool HasVoice(); + virtual bool HasCamera(); + virtual int GetUserIndex(); + virtual void SetSocket(Socket* pSocket); + virtual Socket* GetSocket(); + virtual const wchar_t* GetOnlineName(); + virtual std::wstring GetDisplayName(); + virtual PlayerUID GetUID(); + virtual void SentChunkPacket(); + virtual int GetTimeSinceLastChunkPacket_ms(); + + void SetHost(bool isHost); + void SetHostTransport(bool isServer); + void SetFakeHost(bool isFakeHost); + void SetSmallId(unsigned char smallId); + void SetUID(PlayerUID uid); + void SetDisplayName(const std::wstring& name); + void SetSessionIndex(int index); + void ResetForSession(bool isHost, unsigned char smallId); + void SetTransportSocket(SOCKET socket, unsigned long remoteAddress); + SOCKET GetTransportSocket() const; + bool IsConnected() const; + bool ReceivePendingData(bool hostIsServer); + bool FlushSendQueue(); + void CloseTransport(bool isServerConnection); + + std::vector m_systemFlags; + +private: + void RefreshUID(); + NetworkPlayerWindows* GetTransportPlayer(INetworkPlayer* player); + int GetQueueSizeBytes(); + int GetQueueSizeMessages(); + + int m_userIndex; + unsigned char m_smallId; + bool m_isLocal; + bool m_isHost; + bool m_isHostTransport; + bool m_isFakeHost; + int m_sessionIndex; + std::wstring m_name; + PlayerUID m_uid; + bool m_hasResolvedUID; + ULONGLONG m_lastChunkPacketTick; + Socket* m_gameSocket; + std::atomic m_transportSocket; + std::atomic m_connected; + unsigned long m_remoteAddress; + mutable std::mutex m_transportMutex; + mutable std::mutex m_sendQueueMutex; + std::deque> m_sendQueue; + size_t m_sendQueueOffset; + size_t m_sendQueueBytes; +}; + +#endif \ No newline at end of file diff --git a/Minecraft.Client/Windows64/Network/PlatformNetworkManagerWindows.cpp b/Minecraft.Client/Windows64/Network/PlatformNetworkManagerWindows.cpp new file mode 100644 index 00000000..f014766e --- /dev/null +++ b/Minecraft.Client/Windows64/Network/PlatformNetworkManagerWindows.cpp @@ -0,0 +1,1370 @@ +#include "stdafx.h" + +#ifdef _WINDOWS64 + +#include +#include +#include +#include + +#include "PlatformNetworkManagerWindows.h" +#include "WindowsNetworkConfig.h" +#include "..\..\Common\Network\GameNetworkManager.h" +#include "..\..\Minecraft.h" +#include "..\..\MinecraftServer.h" +#include "..\..\User.h" +#include "..\..\..\Minecraft.World\StringHelpers.h" +#include "..\..\..\Minecraft.World\Socket.h" +#include "..\..\Common\Network\ExternalServerList.h" +#include "..\Windows64_Xuid.h" + +bool g_Win64MultiplayerHost = false; +bool g_Win64MultiplayerJoin = false; +bool g_Win64MultiplayerQuitOnDisconnect = false; +int g_Win64MultiplayerPort = WIN64_NET_DEFAULT_PORT; +char g_Win64MultiplayerIP[256] = "127.0.0.1"; +bool g_Win64DedicatedServer = false; +int g_Win64DedicatedServerPort = WIN64_NET_DEFAULT_PORT; +char g_Win64DedicatedServerBindIP[256] = ""; +bool g_Win64DedicatedServerLanAdvertise = true; + +namespace { + IQNet g_windowsQNet; + + const unsigned short WINDOWS_NETWORK_PORT = 25565; + const unsigned short WINDOWS_DISCOVERY_PORT = 25566; + const SessionID LOCAL_SESSION_ID = 0x4C4F43414C; + const SessionID LAN_SESSION_PREFIX = 0x4C41000000000000ULL; + const SessionID LAN_SESSION_PREFIX_MASK = 0xFFFF000000000000ULL; + const unsigned long LAN_DISCOVERY_MAGIC = 0x4C4D5043; + const unsigned char LAN_DISCOVERY_QUERY = 1; + const unsigned char LAN_DISCOVERY_RESPONSE = 2; + const unsigned char TCP_REQUEST_SERVER_INFO = 1; + const unsigned char TCP_REQUEST_JOIN_GAME = 2; + const DWORD TCP_REQUEST_TIMEOUT_MS = 1000; + const DWORD TCP_JOIN_TIMEOUT_MS = 1500; + const DWORD PENDING_CLIENT_TIMEOUT_MS = 5000; + + bool SetNonBlocking(SOCKET socket) { + u_long enabled = 1; + return ioctlsocket(socket, FIONBIO, &enabled) == 0; + } + + bool ConnectWithTimeout(SOCKET socket, const sockaddr_in& address, DWORD timeoutMs = 5000) { + if (!SetNonBlocking(socket)) return false; + if (connect(socket, reinterpret_cast(&address), sizeof(address)) == 0) return true; + + int error = WSAGetLastError(); + if (error != WSAEWOULDBLOCK && error != WSAEINPROGRESS && error != WSAEALREADY) return false; + + fd_set writableSockets; + FD_ZERO(&writableSockets); + FD_SET(socket, &writableSockets); + timeval timeout; + timeout.tv_sec = timeoutMs / 1000; + timeout.tv_usec = (timeoutMs % 1000) * 1000; + int ready = select(0, nullptr, &writableSockets, nullptr, &timeout); + if (ready == 0) { + WSASetLastError(WSAETIMEDOUT); + return false; + } + + if (ready == SOCKET_ERROR) return false; + + int socketError = 0; + int errorSize = sizeof(socketError); + if (getsockopt(socket, SOL_SOCKET, SO_ERROR, reinterpret_cast(&socketError), &errorSize) == SOCKET_ERROR) return false; + + if (socketError != 0) { + WSASetLastError(socketError); + return false; + } + return true; + } + + bool ResolveIPv4(const char* host, unsigned short port, sockaddr_in* address) { + if (host == nullptr || host[0] == '\0' || address == nullptr || port == 0) return false; + + addrinfo hints = {}; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + char portText[6] = {}; + sprintf_s(portText, "%u", static_cast(port)); + addrinfo* results = nullptr; + if (getaddrinfo(host, portText, &hints, &results) != 0 || results == nullptr) return false; + + *address = *reinterpret_cast(results->ai_addr); + address->sin_port = htons(port); + freeaddrinfo(results); + return true; + } + +#pragma pack(push, 1) + struct LanDiscoveryPacket { + unsigned long magic; + unsigned char type; + }; + + struct ServerDataPacket { + unsigned long magic; + unsigned char type; + unsigned char playerCount; + unsigned char maxPlayers; + unsigned char ready; + unsigned char isDedicated; + unsigned short netVersion; + unsigned short gamePort; + unsigned long hostSettings; + unsigned long texturePackParentId; + unsigned char subTexturePackId; + wchar_t displayName[32]; + wchar_t playerNames[MINECRAFT_NET_MAX_PLAYERS][XUSER_NAME_SIZE]; + }; + + void ApplyServerData(FriendSessionInfo* sessionInfo, const ServerDataPacket& serverData) { + sessionInfo->data.netVersion = serverData.netVersion; + sessionInfo->data.m_uiGameHostSettings = serverData.hostSettings; + sessionInfo->data.texturePackParentId = serverData.texturePackParentId; + sessionInfo->data.subTexturePackId = serverData.subTexturePackId; + sessionInfo->data.isReadyToJoin = serverData.ready != 0; + sessionInfo->data.hostPort = serverData.gamePort; + sessionInfo->data.playerCount = serverData.playerCount > MINECRAFT_NET_MAX_PLAYERS + ? static_cast(MINECRAFT_NET_MAX_PLAYERS) + : serverData.playerCount; + sessionInfo->data.maxPlayers = serverData.maxPlayers == 0 + ? static_cast(MINECRAFT_NET_MAX_PLAYERS) + : (serverData.maxPlayers > MINECRAFT_NET_MAX_PLAYERS + ? static_cast(MINECRAFT_NET_MAX_PLAYERS) + : serverData.maxPlayers); + sessionInfo->data.isJoinable = sessionInfo->data.isReadyToJoin && + (serverData.maxPlayers == 0 || serverData.playerCount < serverData.maxPlayers); + sessionInfo->isDedicatedSession = serverData.isDedicated; + sessionInfo->hasServerInfo = true; + sessionInfo->serverPlayerNames.clear(); + + unsigned int playerCount = serverData.playerCount; + if (playerCount > MINECRAFT_NET_MAX_PLAYERS) playerCount = MINECRAFT_NET_MAX_PLAYERS; + for (unsigned int index = 0; index < playerCount; ++index) { + size_t nameLength = 0; + while (nameLength < XUSER_NAME_SIZE && serverData.playerNames[index][nameLength] != L'\0') { + ++nameLength; + } + if (nameLength > 0) { + sessionInfo->serverPlayerNames.push_back(std::wstring(serverData.playerNames[index], nameLength)); + } + } + } + + bool WaitForSocket(SOCKET socket, bool writable, DWORD startTime, DWORD timeoutMs) { + DWORD elapsed = GetTickCount() - startTime; + if (elapsed >= timeoutMs) return false; + + fd_set sockets; + FD_ZERO(&sockets); + FD_SET(socket, &sockets); + timeval timeout; + timeout.tv_sec = (timeoutMs - elapsed) / 1000; + timeout.tv_usec = ((timeoutMs - elapsed) % 1000) * 1000; + int result = writable + ? select(0, nullptr, &sockets, nullptr, &timeout) + : select(0, &sockets, nullptr, nullptr, &timeout); + return result > 0; + } + + bool SendAllWithTimeout(SOCKET socket, const char* data, int length, DWORD timeoutMs) { + int sentTotal = 0; + DWORD startTime = GetTickCount(); + while (sentTotal < length) { + if (!WaitForSocket(socket, true, startTime, timeoutMs)) return false; + int sent = send(socket, data + sentTotal, length - sentTotal, 0); + if (sent > 0) { + sentTotal += sent; + continue; + } + int error = WSAGetLastError(); + if (sent == SOCKET_ERROR && (error == WSAEWOULDBLOCK || error == WSAEINTR)) continue; + return false; + } + return true; + } + + bool ReceiveAllWithTimeout(SOCKET socket, char* data, int length, DWORD timeoutMs) { + int receivedTotal = 0; + DWORD startTime = GetTickCount(); + while (receivedTotal < length) { + if (!WaitForSocket(socket, false, startTime, timeoutMs)) return false; + int received = recv(socket, data + receivedTotal, length - receivedTotal, 0); + if (received > 0) { + receivedTotal += received; + continue; + } + int error = WSAGetLastError(); + if (received == SOCKET_ERROR && (error == WSAEWOULDBLOCK || error == WSAEINTR)) continue; + return false; + } + return true; + } + + bool QueryServerData(const sockaddr_in& address, ServerDataPacket& serverData) { + SOCKET socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (socket == INVALID_SOCKET) return false; + if (!ConnectWithTimeout(socket, address, TCP_REQUEST_TIMEOUT_MS)) { + closesocket(socket); + return false; + } + + const char request = TCP_REQUEST_SERVER_INFO; + bool success = SendAllWithTimeout(socket, &request, sizeof(request), TCP_REQUEST_TIMEOUT_MS) && + ReceiveAllWithTimeout(socket, reinterpret_cast(&serverData), sizeof(serverData), TCP_REQUEST_TIMEOUT_MS); + closesocket(socket); + if (!success || serverData.magic != LAN_DISCOVERY_MAGIC || serverData.type != TCP_REQUEST_SERVER_INFO) + return false; + + serverData.displayName[_countof(serverData.displayName) - 1] = L'\0'; + return true; + } + +#pragma pack(pop) + + SessionID MakeLanSessionId(unsigned long address, unsigned short port) { + return LAN_SESSION_PREFIX | (static_cast(ntohl(address)) << 16) | static_cast(port); + } + + bool IsLanSessionId(SessionID sessionId) { + return (sessionId & LAN_SESSION_PREFIX_MASK) == LAN_SESSION_PREFIX; + } + + bool GetLanAddress(SessionID sessionId, sockaddr_in* address) { + if (address == nullptr || !IsLanSessionId(sessionId)) return false; + + unsigned long hostAddress = static_cast((sessionId >> 16) & 0xFFFFFFFFULL); + unsigned short port = static_cast(sessionId & 0xFFFF); + if (hostAddress == 0 || port == 0) return false; + + memset(address, 0, sizeof(*address)); + address->sin_family = AF_INET; + address->sin_addr.s_addr = htonl(hostAddress); + address->sin_port = htons(port); + return true; + } +} + +CPlatformNetworkManagerWindows* g_pPlatformNetworkManagerWindows = nullptr; + +CPlatformNetworkManagerWindows::CPlatformNetworkManagerWindows() { + g_pPlatformNetworkManagerWindows = this; + m_gameNetworkManager = nullptr; + m_hostPlayer = nullptr; + m_sessionsUpdatedCallback = nullptr; + m_searchParam = nullptr; + + m_winsockStarted = false; + m_isFakeHost = false; + m_isHost = false; + m_inSession = false; + m_inGameplay = false; + m_isLocalGame = true; + m_isPrivateGame = false; + m_isLeaving = false; + + m_nextSmallId = 0; + m_maxPlayers = static_cast(MINECRAFT_NET_MAX_PLAYERS); + m_flagIndexSize = 0; + + m_listenSocket = INVALID_SOCKET; + m_discoverySocket = INVALID_SOCKET; + m_gamePort = WINDOWS_NETWORK_PORT; + memset(&m_hostAddress, 0, sizeof(m_hostAddress)); + m_hostAddressValid = false; + + + memset(m_localPlayers, 0, sizeof(m_localPlayers)); + memset(m_playerChangedCallback, 0, sizeof(m_playerChangedCallback)); + memset(m_playerChangedCallbackParam, 0, sizeof(m_playerChangedCallbackParam)); +} + +CPlatformNetworkManagerWindows::~CPlatformNetworkManagerWindows() { + Terminate(); + if (g_pPlatformNetworkManagerWindows == this) g_pPlatformNetworkManagerWindows = nullptr; +} + +bool CPlatformNetworkManagerWindows::Initialise(CGameNetworkManager* pGameNetworkManager, int flagIndexSize) { + m_gameNetworkManager = pGameNetworkManager; + m_flagIndexSize = flagIndexSize; + + WSADATA data; + int result = WSAStartup(MAKEWORD(2, 2), &data); + if (result != 0) { + app.DebugPrintf("Winsock startup failed: %d", result); + return false; + } + + m_winsockStarted = true; + return true; +} + +void CPlatformNetworkManagerWindows::Terminate() { + CloseListener(); + + std::vector players; + bool hostIsServer = m_isHost; + { + std::lock_guard lock(m_playersMutex); + players.swap(m_players); + memset(m_localPlayers, 0, sizeof(m_localPlayers)); + m_hostPlayer = nullptr; + m_inSession = false; + m_inGameplay = false; + m_isHost = false; + m_isFakeHost = false; + } + + for (std::vector::iterator it = players.begin(); it != players.end(); ++it) { + (*it)->CloseTransport(hostIsServer); + delete* it; + } + + if (m_winsockStarted) { + WSACleanup(); + m_winsockStarted = false; + } +} + +int CPlatformNetworkManagerWindows::GetJoiningReadyPercentage() { return 100; } +int CPlatformNetworkManagerWindows::CorrectErrorIDS(int IDS) { return IDS; } + +bool CPlatformNetworkManagerWindows::StartListener(unsigned short port, const char* bindIp) { + if (m_listenSocket != INVALID_SOCKET && m_discoverySocket != INVALID_SOCKET) return true; + CloseListener(); + + SOCKET listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listener == INVALID_SOCKET) { + app.DebugPrintf("Creating the Windows game listener failed: %d", WSAGetLastError()); + return false; + } + + sockaddr_in address; + memset(&address, 0, sizeof(address)); + address.sin_family = AF_INET; + address.sin_addr.s_addr = htonl(INADDR_ANY); + if (bindIp != nullptr && bindIp[0] != '\0' && inet_pton(AF_INET, bindIp, &address.sin_addr) != 1) { + app.DebugPrintf("Invalid Windows game bind address: %s", bindIp); + closesocket(listener); + return false; + } + address.sin_port = htons(port); + + if (::bind(listener, reinterpret_cast(&address), sizeof(address)) == SOCKET_ERROR || listen(listener, SOMAXCONN) == SOCKET_ERROR || !SetNonBlocking(listener)) { + app.DebugPrintf("Starting the Windows game listener failed: %d", WSAGetLastError()); + closesocket(listener); + return false; + } + + SOCKET discovery = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (discovery == INVALID_SOCKET) { + app.DebugPrintf("Creating the Windows LAN discovery socket failed: %d", WSAGetLastError()); + closesocket(listener); + return false; + } + + sockaddr_in discoveryAddress; + memset(&discoveryAddress, 0, sizeof(discoveryAddress)); + discoveryAddress.sin_family = AF_INET; + discoveryAddress.sin_addr.s_addr = htonl(INADDR_ANY); + discoveryAddress.sin_port = htons(WINDOWS_DISCOVERY_PORT); + if (::bind(discovery, reinterpret_cast(&discoveryAddress), sizeof(discoveryAddress)) == SOCKET_ERROR || !SetNonBlocking(discovery)) { + app.DebugPrintf("Starting the Windows LAN discovery listener failed: %d", WSAGetLastError()); + closesocket(discovery); + closesocket(listener); + return false; + } + + m_listenSocket = listener; + m_discoverySocket = discovery; + app.DebugPrintf("Windows LAN host listening on TCP %u and UDP %u.", port, WINDOWS_DISCOVERY_PORT); + return true; +} + +void CPlatformNetworkManagerWindows::CloseListener() { + SOCKET listener = m_listenSocket; + SOCKET discovery = m_discoverySocket; + m_listenSocket = INVALID_SOCKET; + m_discoverySocket = INVALID_SOCKET; + + if (listener != INVALID_SOCKET) closesocket(listener); + if (discovery != INVALID_SOCKET) closesocket(discovery); + for (std::vector::iterator it = m_pendingClients.begin(); it != m_pendingClients.end(); ++it) { + closesocket(it->socket); + } + m_pendingClients.clear(); +} + +void CPlatformNetworkManagerWindows::ProcessDiscoveryRequests() { + while (true) { + LanDiscoveryPacket request = {}; + sockaddr_in remoteAddress; + int addressLength = sizeof(remoteAddress); + int received = recvfrom(m_discoverySocket, reinterpret_cast(&request), sizeof(request), 0, reinterpret_cast(&remoteAddress), &addressLength); + if (received == SOCKET_ERROR) { + int error = WSAGetLastError(); + if (error != WSAEWOULDBLOCK && error != WSAEINTR) { + app.DebugPrintf("Receiving a Windows LAN discovery request failed: %d", error); + } + break; + } + + if (received != sizeof(request) || request.magic != LAN_DISCOVERY_MAGIC || request.type != LAN_DISCOVERY_QUERY || !m_isHost || !m_inSession || + (g_Win64DedicatedServer && !g_Win64DedicatedServerLanAdvertise)) continue; + app.DebugPrintf("Received a Windows LAN discovery query."); + + LanDiscoveryPacket response = {}; + response.magic = LAN_DISCOVERY_MAGIC; + response.type = LAN_DISCOVERY_RESPONSE; + + int sent = sendto(m_discoverySocket, reinterpret_cast(&response), sizeof(response), 0, reinterpret_cast(&remoteAddress), addressLength); + if (sent == SOCKET_ERROR) { + app.DebugPrintf("Sending a Windows LAN discovery response failed: %d", WSAGetLastError()); + } + } +} + +void CPlatformNetworkManagerWindows::ProcessPendingClients() { + for (std::vector::iterator it = m_pendingClients.begin(); it != m_pendingClients.end();) { + char request = 0; + int received = recv(it->socket, &request, sizeof(request), 0); + if (received == SOCKET_ERROR) { + int error = WSAGetLastError(); + if ((error == WSAEWOULDBLOCK || error == WSAEINTR) && + GetTickCount() - it->acceptedAt < PENDING_CLIENT_TIMEOUT_MS) { + ++it; + continue; + } + if (error != WSAEWOULDBLOCK && error != WSAEINTR) { + app.DebugPrintf("Receiving a Windows game connection request failed: %d", error); + } + closesocket(it->socket); + it = m_pendingClients.erase(it); + continue; + } + + if (received == 0) { + closesocket(it->socket); + it = m_pendingClients.erase(it); + continue; + } + + PendingClient pending = *it; + it = m_pendingClients.erase(it); + if (request == TCP_REQUEST_SERVER_INFO && received == sizeof(request)) { + ServerDataPacket response = {}; + response.magic = LAN_DISCOVERY_MAGIC; + response.type = TCP_REQUEST_SERVER_INFO; + response.maxPlayers = m_maxPlayers; + response.ready = m_inSession ? 1 : 0; + response.netVersion = MINECRAFT_NET_VERSION; + response.gamePort = m_gamePort; + response.hostSettings = app.GetGameHostOption(eGameHostOption_All); + response.texturePackParentId = m_sessionData.texturePackParentId; + response.subTexturePackId = m_sessionData.subTexturePackId; + response.isDedicated = m_isFakeHost; + + { + std::lock_guard lock(m_playersMutex); + for (std::vector::const_iterator it = m_players.begin(); + it != m_players.end() && response.playerCount < MINECRAFT_NET_MAX_PLAYERS; ++it) { + if (!(*it)->IsConnected() || (*it)->IsFakeHost()) continue; + const wchar_t* playerName = (*it)->GetOnlineName(); + if (playerName != nullptr) { + wcsncpy_s(response.playerNames[response.playerCount], XUSER_NAME_SIZE, playerName, _TRUNCATE); + } + ++response.playerCount; + } + } + + const wchar_t* displayName = m_hostPlayer != nullptr ? m_hostPlayer->GetOnlineName() : nullptr; + if (displayName == nullptr || displayName[0] == L'\0') displayName = L"LAN Game"; + wcsncpy_s(response.displayName, _countof(response.displayName), displayName, _TRUNCATE); + + if (!SendAllWithTimeout(pending.socket, reinterpret_cast(&response), sizeof(response), TCP_REQUEST_TIMEOUT_MS)) { + app.DebugPrintf("Sending Windows server data failed."); + } + closesocket(pending.socket); + } else if (request == TCP_REQUEST_JOIN_GAME && received == sizeof(request)) { + if (SessionHasSpace()) { + AddRemotePlayer(pending.socket, pending.remoteAddress, false); + } else { + closesocket(pending.socket); + } + } else { + closesocket(pending.socket); + } + } +} + +void CPlatformNetworkManagerWindows::DoWork() { + if (!m_winsockStarted) return; + + if (m_isHost && m_listenSocket != INVALID_SOCKET) { + if (m_discoverySocket != INVALID_SOCKET) ProcessDiscoveryRequests(); + ProcessPendingClients(); + + while (true) { + sockaddr_in remoteAddress; + int addressLength = sizeof(remoteAddress); + SOCKET client = accept(m_listenSocket, reinterpret_cast(&remoteAddress), &addressLength); + if (client == INVALID_SOCKET) { + int error = WSAGetLastError(); + if (error != WSAEWOULDBLOCK && error != WSAEINTR) { + app.DebugPrintf("Accepting a local game connection failed: %d", error); + } + break; + } + + if (!SetNonBlocking(client)) { + closesocket(client); + continue; + } + + BOOL noDelay = TRUE; + setsockopt(client, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&noDelay), sizeof(noDelay)); + + if (m_pendingClients.size() >= 32) { + closesocket(client); + continue; + } + PendingClient pending = { client, remoteAddress.sin_addr.s_addr, GetTickCount() }; + m_pendingClients.push_back(pending); + } + ProcessPendingClients(); + } + + std::vector players; + { + std::lock_guard lock(m_playersMutex); + players = m_players; + } + + for (std::vector::iterator it = players.begin(); it != players.end(); ++it) { + NetworkPlayerWindows* player = *it; + if (!player->IsConnected() || player->GetTransportSocket() == INVALID_SOCKET) continue; + + if (!player->ReceivePendingData(m_isHost) || !player->FlushSendQueue()) RemoveRemotePlayer(player); + } +} + +int CPlatformNetworkManagerWindows::GetPlayerCount() { + int count = 0; + std::lock_guard lock(m_playersMutex); + for (std::vector::const_iterator it = m_players.begin(); it != m_players.end(); ++it) { + if ((*it)->IsConnected() && !(*it)->IsFakeHost()) ++count; + } + return count; +} + +int CPlatformNetworkManagerWindows::GetOnlinePlayerCount() { + int count = 0; + std::lock_guard lock(m_playersMutex); + for (std::vector::const_iterator it = m_players.begin(); it != m_players.end(); ++it) { + if ((*it)->IsConnected() && !(*it)->IsFakeHost() && !(*it)->IsLocal()) ++count; + } + return count; +} + +int CPlatformNetworkManagerWindows::GetLocalPlayerMask(int playerIndex) { + if (playerIndex < 0 || playerIndex >= XUSER_MAX_COUNT) return 0; + return 1 << playerIndex; +} + +NetworkPlayerWindows* CPlatformNetworkManagerWindows::CreateLocalPlayer(int userIndex) { + if (userIndex < 0 || userIndex >= XUSER_MAX_COUNT) return nullptr; + if (m_localPlayers[userIndex] != nullptr) { + NetworkPlayerWindows* player = m_localPlayers[userIndex]; + const unsigned char smallId = m_isHost + ? static_cast(userIndex) + : static_cast(userIndex + 1); + const bool isHostPlayer = m_isHost && userIndex == 0; + if (!player->IsConnected()) { + player->ResetForSession(isHostPlayer, smallId); + } else { + player->SetHost(isHostPlayer); + player->SetSmallId(smallId); + } + player->SetHostTransport(m_isHost); + player->SetFakeHost(m_isFakeHost); + SyncIQNetPlayer(player, true); + return player; + } + + std::wstring name = L"Player"; + Minecraft* minecraft = Minecraft::GetInstance(); + if (minecraft != nullptr && minecraft->user != nullptr && !minecraft->user->name.empty()) { + name = minecraft->user->name; + } + + unsigned char smallId = m_isHost + ? static_cast(userIndex) + : static_cast(userIndex + 1); + const bool isHostPlayer = m_isHost && userIndex == 0; + NetworkPlayerWindows* player = new NetworkPlayerWindows(userIndex, smallId, true, isHostPlayer, name); + player->SetHostTransport(m_isHost); + player->SetFakeHost(m_isFakeHost); + m_localPlayers[userIndex] = player; + { + std::lock_guard lock(m_playersMutex); + player->SetSessionIndex(static_cast(m_players.size())); + m_players.push_back(player); + } + if (!player->IsFakeHost()) { + SyncIQNetPlayer(player, true); + m_gameNetworkManager->PlayerJoining(player); + NotifyPlayerChanged(player, false); + } + return player; +} + +bool CPlatformNetworkManagerWindows::AddLocalPlayerByUserIndex(int userIndex) { + return CreateLocalPlayer(userIndex) != nullptr; +} + +bool CPlatformNetworkManagerWindows::RemoveLocalPlayerByUserIndex(int userIndex) { + if (userIndex < 0 || userIndex >= XUSER_MAX_COUNT || m_localPlayers[userIndex] == nullptr) return false; + return RemoveLocalPlayer(m_localPlayers[userIndex]); +} + +INetworkPlayer* CPlatformNetworkManagerWindows::GetLocalPlayerByUserIndex(int userIndex) { + if (userIndex < 0 || userIndex >= XUSER_MAX_COUNT) return nullptr; + return m_localPlayers[userIndex]; +} + +INetworkPlayer* CPlatformNetworkManagerWindows::GetPlayerByIndex(int playerIndex) { + if (playerIndex < 0) return nullptr; + std::lock_guard lock(m_playersMutex); + int activeIndex = 0; + for (std::vector::const_iterator it = m_players.begin(); it != m_players.end(); ++it) { + if (!(*it)->IsConnected() || (*it)->IsFakeHost()) continue; + if (activeIndex++ == playerIndex) return *it; + } + return nullptr; +} + +INetworkPlayer* CPlatformNetworkManagerWindows::GetPlayerByXuid(PlayerUID xuid) { + std::lock_guard lock(m_playersMutex); + for (std::vector::const_iterator it = m_players.begin(); it != m_players.end(); ++it) { + if ((*it)->IsConnected() && !(*it)->IsFakeHost() && (*it)->GetUID() == xuid) return *it; + } + return nullptr; +} + +INetworkPlayer* CPlatformNetworkManagerWindows::GetPlayerBySmallId(unsigned char smallId) { + std::lock_guard lock(m_playersMutex); + for (std::vector::const_iterator it = m_players.begin(); it != m_players.end(); ++it) { + if ((*it)->IsConnected() && (*it)->GetSmallId() == smallId) return *it; + } + return nullptr; +} + +bool CPlatformNetworkManagerWindows::ShouldMessageForFullSession() { return !SessionHasSpace(); } + +INetworkPlayer* CPlatformNetworkManagerWindows::GetHostPlayer() { + return m_hostPlayer != nullptr && m_hostPlayer->IsConnected() ? m_hostPlayer : nullptr; +} + +bool CPlatformNetworkManagerWindows::IsHost() { return m_isHost && !m_isLeaving; } +bool CPlatformNetworkManagerWindows::JoinGameFromInviteInfo(int userIndex, int userMask, const INVITE_INFO* pInviteInfo) { return false; } + +bool CPlatformNetworkManagerWindows::LeaveGame(bool bMigrateHost) { + const bool waitForHostServer = m_isHost && MinecraftServer::serverHalted() && + g_NetworkManager.ServerStoppedValid(); + if (waitForHostServer) { + g_NetworkManager.ServerStoppedWait(); + g_NetworkManager.ServerStoppedDestroy(); + } + + m_isLeaving = true; + CloseListener(); + + std::vector players; + { + std::lock_guard lock(m_playersMutex); + players = m_players; + } + for (std::vector::iterator it = players.begin(); it != players.end(); ++it) { + NetworkPlayerWindows* player = *it; + player->CloseTransport(m_isHost); + } + + m_hostPlayer = nullptr; + m_inSession = false; + m_inGameplay = false; + m_isHost = false; + m_isFakeHost = false; + m_hostAddressValid = false; + g_windowsQNet.EndGame(); + return true; +} + +bool CPlatformNetworkManagerWindows::_LeaveGame(bool bMigrateHost, bool bLeaveRoom) { + return LeaveGame(bMigrateHost); +} + +bool CPlatformNetworkManagerWindows::IsInSession() { return m_inSession; } +bool CPlatformNetworkManagerWindows::IsInGameplay() { return m_inGameplay; } + +bool CPlatformNetworkManagerWindows::IsReadyToPlayOrIdle() { return true; } +bool CPlatformNetworkManagerWindows::IsInStatsEnabledSession() { return false; } + +bool CPlatformNetworkManagerWindows::SessionHasSpace(unsigned int spaceRequired) { + return GetPlayerCount() + spaceRequired <= m_maxPlayers; +} + +void CPlatformNetworkManagerWindows::UpdateMaxPlayers(unsigned char maxPlayers) { + m_maxPlayers = maxPlayers > MINECRAFT_NET_MAX_PLAYERS + ? static_cast(MINECRAFT_NET_MAX_PLAYERS) + : maxPlayers; +} + +void CPlatformNetworkManagerWindows::SendInviteGUI(int quadrant) {} + +bool CPlatformNetworkManagerWindows::IsAddingPlayer() { return false; } + +void CPlatformNetworkManagerWindows::HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, unsigned char publicSlots, unsigned char privateSlots) { + SetLocalGame(true); + SetPrivateGame(bIsPrivate); + + m_isLeaving = false; + m_isFakeHost = false; + m_isHost = true; + m_nextSmallId = XUSER_MAX_COUNT; + m_freeSmallIds.clear(); + int port = WINDOWS_NETWORK_PORT; + const char* bindIp = nullptr; + if (g_Win64DedicatedServer) { + if (g_Win64DedicatedServerPort > 0 && g_Win64DedicatedServerPort <= 65535) + port = g_Win64DedicatedServerPort; + if (g_Win64DedicatedServerBindIP[0] != '\0') + bindIp = g_Win64DedicatedServerBindIP; + } + m_gamePort = static_cast(port); + if (!m_winsockStarted) { + m_isHost = false; + m_inSession = false; + return; + } + if (!StartListener(m_gamePort, bindIp)) { + m_isHost = false; + m_inSession = false; + app.DebugPrintf("Could not open the LAN game ports (TCP %u and UDP %u)", m_gamePort, WINDOWS_DISCOVERY_PORT); + return; + } + + g_windowsQNet.HostGame(); + m_inSession = true; + for (int userIndex = 0; userIndex < XUSER_MAX_COUNT; ++userIndex) { + if ((localUsersMask & (1 << userIndex)) != 0) + CreateLocalPlayer(userIndex); + } + m_hostPlayer = m_localPlayers[0]; + _HostGame(localUsersMask, publicSlots, privateSlots); +} + +void CPlatformNetworkManagerWindows::_HostGame(int usersMask, unsigned char publicSlots, unsigned char privateSlots) {} + +bool CPlatformNetworkManagerWindows::_StartGame() { + m_inGameplay = true; + return m_isHost ? m_listenSocket != INVALID_SOCKET : m_inSession; +} + +int CPlatformNetworkManagerWindows::JoinGame(FriendSessionInfo* searchResult, int localUsersMask, int primaryUserIndex) { + if (searchResult == nullptr || primaryUserIndex < 0 || primaryUserIndex >= XUSER_MAX_COUNT) return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + + sockaddr_in address; + if (searchResult->sessionId == LOCAL_SESSION_ID) { + memset(&address, 0, sizeof(address)); + address.sin_family = AF_INET; + address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + unsigned short port = searchResult->data.hostPort > 0 + ? static_cast(searchResult->data.hostPort) + : WINDOWS_NETWORK_PORT; + address.sin_port = htons(port); + } else if (searchResult->data.hostIP[0] != '\0' && searchResult->data.hostPort > 0) { + if (!ResolveIPv4(searchResult->data.hostIP, static_cast(searchResult->data.hostPort), &address)) + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + } else if (!GetLanAddress(searchResult->sessionId, &address)) { + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + } + + SetLocalGame(true); + if (m_gameNetworkManager == nullptr || !m_winsockStarted || m_inSession) { + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + } + + SOCKET client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (client == INVALID_SOCKET) { + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + } + + if (!ConnectWithTimeout(client, address, TCP_JOIN_TIMEOUT_MS)) { + int error = WSAGetLastError(); + app.DebugPrintf("Connecting to Windows game at %s:%u failed: %d", inet_ntoa(address.sin_addr), ntohs(address.sin_port), error); + closesocket(client); + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + } + const char request = TCP_REQUEST_JOIN_GAME; + if (!SendAllWithTimeout(client, &request, sizeof(request), TCP_REQUEST_TIMEOUT_MS)) { + closesocket(client); + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + } + g_windowsQNet.ClientJoinGame(); + BOOL noDelay = TRUE; + setsockopt(client, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&noDelay), sizeof(noDelay)); + + m_gameNetworkManager->StateChange_AnyToJoining(); + NetworkPlayerWindows* localPlayer = CreateLocalPlayer(primaryUserIndex); + if (localPlayer == nullptr) { + closesocket(client); + m_gameNetworkManager->StateChange_JoiningToIdle(JOIN_FAILED_NONSPECIFIC); + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + } + localPlayer->SetHost(false); + localPlayer->SetTransportSocket(client, address.sin_addr.s_addr); + localPlayer->SetSocket(new Socket(localPlayer, false, false)); + m_hostAddress = address; + m_hostAddressValid = true; + + std::wstring hostName = searchResult->displayLabel != nullptr ? searchResult->displayLabel : L"LAN Game"; + NetworkPlayerWindows* remoteHost = new NetworkPlayerWindows(-1, 0, false, true, hostName); + remoteHost->SetHostTransport(false); + remoteHost->SetSessionIndex(0); + remoteHost->SetFakeHost(searchResult->isDedicatedSession); + { + std::lock_guard lock(m_playersMutex); + m_players.insert(m_players.begin(), remoteHost); + for (unsigned int index = 0; index < m_players.size(); ++index) { + m_players[index]->SetSessionIndex(static_cast(index)); + } + } + + m_hostPlayer = remoteHost; + m_isHost = false; + m_isLeaving = false; + m_inSession = true; + m_inGameplay = false; + SyncIQNetPlayer(remoteHost, true); + m_gameNetworkManager->PlayerJoining(remoteHost); + NotifyPlayerChanged(remoteHost, false); + m_gameNetworkManager->StateChange_AnyToStarting(); + return CGameNetworkManager::JOINGAME_SUCCESS; +} + +bool CPlatformNetworkManagerWindows::JoinSplitScreen(int padIndex, unsigned char* outSmallId) { + if (outSmallId == nullptr || padIndex <= 0 || padIndex >= XUSER_MAX_COUNT || + m_isHost || !m_inSession || !m_hostAddressValid || !m_winsockStarted) return false; + + NetworkPlayerWindows* player = CreateLocalPlayer(padIndex); + if (player == nullptr) return false; + + SOCKET client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (client == INVALID_SOCKET || !ConnectWithTimeout(client, m_hostAddress, TCP_JOIN_TIMEOUT_MS)) { + if (client != INVALID_SOCKET) closesocket(client); + return false; + } + const char request = TCP_REQUEST_JOIN_GAME; + if (!SendAllWithTimeout(client, &request, sizeof(request), TCP_REQUEST_TIMEOUT_MS)) { + closesocket(client); + return false; + } + BOOL noDelay = TRUE; + setsockopt(client, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&noDelay), sizeof(noDelay)); + const unsigned char smallId = static_cast(padIndex + 1); + player->SetHost(false); + player->SetSmallId(smallId); + player->SetTransportSocket(client, m_hostAddress.sin_addr.s_addr); + *outSmallId = smallId; + return true; +} + +bool CPlatformNetworkManagerWindows::SetLocalGame(bool isLocal) { + m_isLocalGame = isLocal; + return true; +} + +bool CPlatformNetworkManagerWindows::IsLocalGame() { return m_isLocalGame; } +void CPlatformNetworkManagerWindows::SetPrivateGame(bool isPrivate) { m_isPrivateGame = isPrivate; } +bool CPlatformNetworkManagerWindows::IsPrivateGame() { return m_isPrivateGame; } + +bool CPlatformNetworkManagerWindows::IsLeavingGame() { return m_isLeaving; } +void CPlatformNetworkManagerWindows::ResetLeavingGame() { m_isLeaving = false; } + +void CPlatformNetworkManagerWindows::RegisterPlayerChangedCallback(int iPad, void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, bool leaving), void* callbackParam) { + if (iPad < 0 || iPad >= XUSER_MAX_COUNT) return; + m_playerChangedCallback[iPad] = callback; + m_playerChangedCallbackParam[iPad] = callbackParam; +} + +void CPlatformNetworkManagerWindows::UnRegisterPlayerChangedCallback(int iPad, void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, bool leaving), void* callbackParam) { + if (iPad < 0 || iPad >= XUSER_MAX_COUNT) return; + if (m_playerChangedCallback[iPad] == callback && m_playerChangedCallbackParam[iPad] == callbackParam) { + m_playerChangedCallback[iPad] = nullptr; + m_playerChangedCallbackParam[iPad] = nullptr; + } +} + +void CPlatformNetworkManagerWindows::NotifyPlayerChanged(NetworkPlayerWindows* player, bool leaving) { + for (int index = 0; index < XUSER_MAX_COUNT; ++index) { + if (m_playerChangedCallback[index] != nullptr) { + m_playerChangedCallback[index](m_playerChangedCallbackParam[index], player, leaving); + } + } +} + +void CPlatformNetworkManagerWindows::SyncIQNetPlayer(NetworkPlayerWindows* player, bool active) { + if (player == nullptr) return; + const unsigned char smallId = player->GetSmallId(); + if (smallId >= MINECRAFT_NET_MAX_PLAYERS) return; + + IQNetPlayer& qnetPlayer = IQNet::m_player[smallId]; + qnetPlayer.m_smallId = smallId; + if (!active) { + qnetPlayer.SetCustomDataValue(0); + qnetPlayer.m_resolvedXuid = INVALID_XUID; + qnetPlayer.m_gamertag[0] = 0; + qnetPlayer.m_isRemote = false; + qnetPlayer.m_isHostPlayer = false; + return; + } + + qnetPlayer.m_isRemote = !player->IsLocal(); + qnetPlayer.m_isHostPlayer = player->IsHost(); + qnetPlayer.m_resolvedXuid = player->GetUID(); + wcsncpy_s(qnetPlayer.m_gamertag, 32, player->GetOnlineName(), _TRUNCATE); + qnetPlayer.SetCustomDataValue(reinterpret_cast(player)); + if (static_cast(smallId) >= IQNet::s_playerCount) + IQNet::s_playerCount = static_cast(smallId + 1); +} + +void CPlatformNetworkManagerWindows::RegisterMirroredPlayer(IQNetPlayer* qnetPlayer) { + if (qnetPlayer == nullptr || qnetPlayer->m_smallId >= MINECRAFT_NET_MAX_PLAYERS) return; + + NetworkPlayerWindows* player = dynamic_cast(GetPlayerBySmallId(qnetPlayer->m_smallId)); + if (player == nullptr) { + std::wstring name = qnetPlayer->m_gamertag[0] != L'\0' ? qnetPlayer->m_gamertag : L"LAN Player"; + player = new NetworkPlayerWindows(-1, qnetPlayer->m_smallId, false, qnetPlayer->m_isHostPlayer, name); + player->SetHostTransport(m_isHost); + player->SetSessionIndex(static_cast(m_players.size())); + { + std::lock_guard lock(m_playersMutex); + m_players.push_back(player); + } + m_gameNetworkManager->PlayerJoining(player); + NotifyPlayerChanged(player, false); + } + player->SetUID(qnetPlayer->GetXuid()); + player->SetDisplayName(qnetPlayer->m_gamertag); + SyncIQNetPlayer(player, true); +} + +void CPlatformNetworkManagerWindows::UnregisterMirroredPlayer(IQNetPlayer* qnetPlayer) { + if (qnetPlayer == nullptr) return; + NetworkPlayerWindows* player = dynamic_cast(GetPlayerBySmallId(qnetPlayer->m_smallId)); + if (player == nullptr || player->IsLocal()) return; + if (player == m_hostPlayer) { + RemoveRemotePlayer(player); + return; + } + if (m_isHost) m_gameNetworkManager->CloseConnection(player); + player->CloseTransport(m_isHost); + SyncIQNetPlayer(player, false); + m_gameNetworkManager->PlayerLeaving(player); + NotifyPlayerChanged(player, true); +} + +void CPlatformNetworkManagerWindows::HandleSignInChange() {} + +bool CPlatformNetworkManagerWindows::_RunNetworkGame() { + if (!m_isHost || m_listenSocket == INVALID_SOCKET) return false; + m_inGameplay = true; + extern QNET_STATE _iQNetStubState; + _iQNetStubState = QNET_STATE_GAME_PLAY; + + std::vector players; + { + std::lock_guard lock(m_playersMutex); + players = m_players; + } + + for (std::vector::iterator it = players.begin(); it != players.end(); ++it) { + Socket* socket = (*it)->GetSocket(); + if (!(*it)->IsLocal() && (*it)->IsConnected() && socket != nullptr) { + Socket::addIncomingSocket(socket); + } + } + return true; +} + +void CPlatformNetworkManagerWindows::UpdateAndSetGameSessionData(INetworkPlayer* pNetworkPlayerLeaving) { + m_sessionData.netVersion = MINECRAFT_NET_VERSION; + m_sessionData.m_uiGameHostSettings = app.GetGameHostOption(eGameHostOption_All); +} + +void CPlatformNetworkManagerWindows::SystemFlagSet(INetworkPlayer* pNetworkPlayer, int index) { + NetworkPlayerWindows* player = dynamic_cast(pNetworkPlayer); + if (player == nullptr || index < 0 || index >= m_flagIndexSize) return; + + size_t required = static_cast(index / 8 + 1); + if (player->m_systemFlags.size() < required) player->m_systemFlags.resize(required, 0); + player->m_systemFlags[index / 8] |= static_cast(128 >> (index % 8)); +} + +bool CPlatformNetworkManagerWindows::SystemFlagGet(INetworkPlayer* pNetworkPlayer, int index) +{ + NetworkPlayerWindows* player = dynamic_cast(pNetworkPlayer); + return player != nullptr && index >= 0 && index < m_flagIndexSize && static_cast(index / 8) < player->m_systemFlags.size() && (player->m_systemFlags[index / 8] & static_cast(128 >> (index % 8))) != 0; +} + +std::wstring CPlatformNetworkManagerWindows::GatherStats() { return L"Winsock TCP players: " + std::to_wstring(GetPlayerCount()); } + +std::wstring CPlatformNetworkManagerWindows::GatherRTTStats() { return L"TCP RTT: unavailable"; } + +void CPlatformNetworkManagerWindows::SetSessionLabel(FriendSessionInfo* sessionInfo, const wchar_t* label, SessionID sessionId) { + if (sessionInfo == nullptr) return; + if (label == nullptr) label = L"LAN Game"; + size_t labelLength = wcslen(label); + delete[] sessionInfo->displayLabel; + sessionInfo->displayLabel = new wchar_t[labelLength + 1]; + wcscpy_s(sessionInfo->displayLabel, labelLength + 1, label); + sessionInfo->displayLabelLength = static_cast(labelLength); + sessionInfo->displayLabelViewableStartIndex = 0; + sessionInfo->sessionId = sessionId; + sessionInfo->data.netVersion = MINECRAFT_NET_VERSION; + sessionInfo->data.isReadyToJoin = true; +} + +std::vector* CPlatformNetworkManagerWindows::GetSessionList(int iPad, int localPlayers, bool partyOnly) { + std::vector* sessions = new std::vector(); + std::vector savedServers; + if (!ExternalServerList::Read(savedServers)) { + app.DebugPrintf("Failed to read external servers from servers.db."); + } else { + for (size_t index = 0; index < savedServers.size(); ++index) { + uint64_t sessionId = 0; + if (!ExternalServerList::MakeSessionId(savedServers[index].address, savedServers[index].port, sessionId)) { + app.DebugPrintf("Ignoring invalid address in servers.db: %s", savedServers[index].address.c_str()); + continue; + } + + int nameLength = MultiByteToWideChar(CP_ACP, 0, savedServers[index].name.c_str(), -1, nullptr, 0); + if (nameLength <= 0) { + app.DebugPrintf("Ignoring server with an invalid name in servers.db."); + continue; + } + std::vector wideName(nameLength); + if (MultiByteToWideChar(CP_ACP, 0, savedServers[index].name.c_str(), -1, &wideName[0], nameLength) == 0) { + app.DebugPrintf("Ignoring server with an invalid name in servers.db."); + continue; + } + + FriendSessionInfo* sessionInfo = new FriendSessionInfo(); + SetSessionLabel(sessionInfo, wideName.data(), sessionId); + strncpy_s(sessionInfo->data.hostIP, sizeof(sessionInfo->data.hostIP), savedServers[index].address.c_str(), _TRUNCATE); + sessionInfo->data.hostPort = savedServers[index].port; + sessionInfo->savedServerIndex = static_cast(index); + sessions->push_back(sessionInfo); + } + } + + if (!m_winsockStarted) return sessions; + + SOCKET querySocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (querySocket == INVALID_SOCKET) { + app.DebugPrintf("Creating a Windows LAN discovery query socket failed: %d", WSAGetLastError()); + return sessions; + } + + BOOL allowBroadcast = TRUE; + if (setsockopt(querySocket, SOL_SOCKET, SO_BROADCAST, reinterpret_cast(&allowBroadcast), sizeof(allowBroadcast)) == SOCKET_ERROR) { + app.DebugPrintf("Enabling LAN discovery broadcasts failed: %d", WSAGetLastError()); + closesocket(querySocket); + return sessions; + } + + sockaddr_in localAddress; + memset(&localAddress, 0, sizeof(localAddress)); + localAddress.sin_family = AF_INET; + localAddress.sin_addr.s_addr = htonl(INADDR_ANY); + localAddress.sin_port = 0; + if (::bind(querySocket, reinterpret_cast(&localAddress), sizeof(localAddress)) == SOCKET_ERROR || !SetNonBlocking(querySocket)) { + app.DebugPrintf("Preparing a Windows LAN discovery query socket failed: %d", WSAGetLastError()); + closesocket(querySocket); + return sessions; + } + + LanDiscoveryPacket query = {}; + query.magic = LAN_DISCOVERY_MAGIC; + query.type = LAN_DISCOVERY_QUERY; + + sockaddr_in broadcastAddress; + memset(&broadcastAddress, 0, sizeof(broadcastAddress)); + broadcastAddress.sin_family = AF_INET; + broadcastAddress.sin_addr.s_addr = htonl(INADDR_BROADCAST); + broadcastAddress.sin_port = htons(WINDOWS_DISCOVERY_PORT); + bool sentQuery = false; + if (sendto(querySocket, reinterpret_cast(&query), sizeof(query), 0, reinterpret_cast(&broadcastAddress), sizeof(broadcastAddress)) != SOCKET_ERROR) { + sentQuery = true; + } else { + app.DebugPrintf("Sending a Windows LAN discovery broadcast failed: %d", WSAGetLastError()); + } + + INTERFACE_INFO interfaces[32] = {}; + DWORD interfaceBytes = 0; + if (WSAIoctl(querySocket, SIO_GET_INTERFACE_LIST, nullptr, 0, interfaces, sizeof(interfaces), &interfaceBytes, nullptr, nullptr) == SOCKET_ERROR) { + app.DebugPrintf("Enumerating Windows LAN interfaces for discovery failed: %d", WSAGetLastError()); + } else { + size_t interfaceCount = interfaceBytes / sizeof(INTERFACE_INFO); + for (size_t index = 0; index < interfaceCount; ++index) { + if ((interfaces[index].iiFlags & (IFF_UP | IFF_BROADCAST)) != (IFF_UP | IFF_BROADCAST)) continue; + + sockaddr_in interfaceBroadcast = *reinterpret_cast(&interfaces[index].iiBroadcastAddress); + if (interfaceBroadcast.sin_family != AF_INET || interfaceBroadcast.sin_addr.s_addr == htonl(INADDR_ANY) || interfaceBroadcast.sin_addr.s_addr == htonl(INADDR_BROADCAST)) continue; + + interfaceBroadcast.sin_port = htons(WINDOWS_DISCOVERY_PORT); + if (sendto(querySocket, reinterpret_cast(&query), sizeof(query), 0, reinterpret_cast(&interfaceBroadcast), sizeof(interfaceBroadcast)) != SOCKET_ERROR) { + sentQuery = true; + } else { + app.DebugPrintf("Sending a directed Windows LAN discovery broadcast failed: %d", WSAGetLastError()); + } + } + } + + if (!sentQuery) { + closesocket(querySocket); + return sessions; + } + + fd_set readableSockets; + FD_ZERO(&readableSockets); + FD_SET(querySocket, &readableSockets); + timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 500000; + int ready = select(0, &readableSockets, nullptr, nullptr, &timeout); + if (ready == SOCKET_ERROR) { + app.DebugPrintf("Waiting for Windows LAN discovery responses failed: %d", WSAGetLastError()); + closesocket(querySocket); + return sessions; + } + if (ready == 0) { + sockaddr_in loopbackAddress; + memset(&loopbackAddress, 0, sizeof(loopbackAddress)); + loopbackAddress.sin_family = AF_INET; + loopbackAddress.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + loopbackAddress.sin_port = htons(WINDOWS_DISCOVERY_PORT); + if (sendto(querySocket, reinterpret_cast(&query), sizeof(query), 0, reinterpret_cast(&loopbackAddress), sizeof(loopbackAddress)) != SOCKET_ERROR) { + FD_ZERO(&readableSockets); + FD_SET(querySocket, &readableSockets); + timeout.tv_sec = 0; + timeout.tv_usec = 200000; + ready = select(0, &readableSockets, nullptr, nullptr, &timeout); + } + } + + if (ready > 0) { + while (true) { + LanDiscoveryPacket response = {}; + sockaddr_in remoteAddress; + int addressLength = sizeof(remoteAddress); + int received = recvfrom(querySocket, reinterpret_cast(&response), sizeof(response), 0, reinterpret_cast(&remoteAddress), &addressLength); + if (received == SOCKET_ERROR) { + int error = WSAGetLastError(); + if (error != WSAEWOULDBLOCK && error != WSAEINTR) { + app.DebugPrintf("Receiving a Windows LAN discovery response failed: %d", error); + } + break; + } + + if (received != sizeof(response) || response.magic != LAN_DISCOVERY_MAGIC || response.type != LAN_DISCOVERY_RESPONSE) continue; + + sockaddr_in serverAddress = remoteAddress; + serverAddress.sin_port = htons(WINDOWS_NETWORK_PORT); + ServerDataPacket serverData = {}; + if (!QueryServerData(serverAddress, serverData) || + serverData.netVersion != MINECRAFT_NET_VERSION || + serverData.ready == 0 || serverData.gamePort == 0 || + (serverData.maxPlayers != 0 && (serverData.playerCount + localPlayers) > serverData.maxPlayers)) { + continue; + } + + SessionID sessionId = MakeLanSessionId(remoteAddress.sin_addr.s_addr, serverData.gamePort); + bool alreadyAdded = false; + for (std::vector::const_iterator it = sessions->begin(); it != sessions->end(); ++it) { + if ((*it)->sessionId == sessionId) { + alreadyAdded = true; + break; + } + } + if (alreadyAdded) continue; + + const wchar_t* label = serverData.displayName[0] != L'\0' ? serverData.displayName : L"LAN Game"; + FriendSessionInfo* sessionInfo = new FriendSessionInfo(); + SetSessionLabel(sessionInfo, label, sessionId); + ApplyServerData(sessionInfo, serverData); + sessions->push_back(sessionInfo); + } + } + + closesocket(querySocket); + app.DebugPrintf("Windows LAN discovery found %u session(s).", static_cast(sessions->size())); + return sessions; +} + +bool CPlatformNetworkManagerWindows::GetGameSessionInfo(int iPad, SessionID sessionId, FriendSessionInfo* foundSession) { + if (foundSession == nullptr) return false; + if (sessionId == LOCAL_SESSION_ID) { + SetSessionLabel(foundSession, L"Localhost", LOCAL_SESSION_ID); + return true; + } + if (!IsLanSessionId(sessionId) && + (foundSession->data.hostIP[0] == '\0' || foundSession->data.hostPort <= 0)) return false; + + foundSession->data.netVersion = MINECRAFT_NET_VERSION; + foundSession->data.isReadyToJoin = true; + return true; +} + +void CPlatformNetworkManagerWindows::SetSessionsUpdatedCallback(void (*SessionsUpdatedCallback)(LPVOID pParam), LPVOID pSearchParam) { + m_sessionsUpdatedCallback = SessionsUpdatedCallback; + m_searchParam = pSearchParam; +} + +void CPlatformNetworkManagerWindows::GetFullFriendSessionInfo(FriendSessionInfo* foundSession, void (*FriendSessionUpdatedFn)(bool success, void* pParam), void* pParam) { + bool hasSavedAddress = foundSession != nullptr && foundSession->data.hostIP[0] != '\0' && foundSession->data.hostPort > 0; + bool success = foundSession != nullptr && + (foundSession->sessionId == LOCAL_SESSION_ID || IsLanSessionId(foundSession->sessionId) || hasSavedAddress); + if (success && foundSession->sessionId != LOCAL_SESSION_ID) { + sockaddr_in address; + ServerDataPacket serverData = {}; + bool addressResolved = hasSavedAddress + ? ResolveIPv4(foundSession->data.hostIP, static_cast(foundSession->data.hostPort), &address) + : GetLanAddress(foundSession->sessionId, &address); + if (addressResolved && QueryServerData(address, serverData) && + serverData.netVersion == MINECRAFT_NET_VERSION && serverData.ready != 0 && serverData.gamePort != 0) { + ApplyServerData(foundSession, serverData); + if (serverData.displayName[0] != L'\0') { + SetSessionLabel(foundSession, serverData.displayName, foundSession->sessionId); + } + } + } + if (FriendSessionUpdatedFn != nullptr) FriendSessionUpdatedFn(success, pParam); +} + +void CPlatformNetworkManagerWindows::ForceFriendsSessionRefresh() { + if (m_sessionsUpdatedCallback != nullptr) m_sessionsUpdatedCallback(m_searchParam); +} + +void CPlatformNetworkManagerWindows::FakeLocalPlayerJoined() { + FakeLocalPlayerJoined(false); +} + +void CPlatformNetworkManagerWindows::FakeLocalPlayerJoined(bool fakeHost) { + m_isFakeHost = m_isHost && fakeHost; + NetworkPlayerWindows* localPlayer = CreateLocalPlayer(0); + if (localPlayer != nullptr && m_isHost) { + localPlayer->SetFakeHost(m_isFakeHost); + m_hostPlayer = localPlayer; + } +} + +NetworkPlayerWindows* CPlatformNetworkManagerWindows::AddRemotePlayer(SOCKET socket, unsigned long remoteAddress, bool isHost) { + unsigned char smallId = 0; + { + std::lock_guard lock(m_playersMutex); + if (!m_freeSmallIds.empty()) { + smallId = m_freeSmallIds.back(); + m_freeSmallIds.pop_back(); + } else if (m_nextSmallId < MINECRAFT_NET_MAX_PLAYERS) { + smallId = m_nextSmallId++; + } + } + if (!isHost && smallId == 0) { + closesocket(socket); + return nullptr; + } + + std::wstring name = isHost ? L"Local Host" : L"LAN Player"; + NetworkPlayerWindows* player = new NetworkPlayerWindows(-1, isHost ? 0 : smallId, false, isHost, name); + player->SetHostTransport(m_isHost); + player->SetTransportSocket(socket, remoteAddress); + { + std::lock_guard lock(m_playersMutex); + player->SetSessionIndex(static_cast(m_players.size())); + m_players.push_back(player); + } + + if (!isHost) { + SyncIQNetPlayer(player, true); + m_gameNetworkManager->PlayerJoining(player); + m_gameNetworkManager->CreateSocket(player, false); + } else { + SyncIQNetPlayer(player, true); + m_hostPlayer = player; + m_gameNetworkManager->PlayerJoining(player); + } + NotifyPlayerChanged(player, false); + return player; +} + +void CPlatformNetworkManagerWindows::ReleaseSmallId(unsigned char smallId) { + if (smallId < XUSER_MAX_COUNT || smallId >= MINECRAFT_NET_MAX_PLAYERS) return; + std::lock_guard lock(m_playersMutex); + if (std::find(m_freeSmallIds.begin(), m_freeSmallIds.end(), smallId) == m_freeSmallIds.end()) + m_freeSmallIds.push_back(smallId); +} + +void CPlatformNetworkManagerWindows::RemoveRemotePlayer(NetworkPlayerWindows* player) { + if (player == nullptr || !player->IsConnected()) return; + + if (m_isHost) { + m_gameNetworkManager->CloseConnection(player); + } + player->CloseTransport(m_isHost); + SyncIQNetPlayer(player, false); + m_gameNetworkManager->PlayerLeaving(player); + NotifyPlayerChanged(player, true); + + if (!m_isHost) { + if (m_hostPlayer != nullptr && m_hostPlayer != player) { + m_hostPlayer->CloseTransport(false); + } + m_hostPlayer = nullptr; + m_inSession = false; + m_inGameplay = false; + m_isLeaving = true; + } +} + +bool CPlatformNetworkManagerWindows::RemoveLocalPlayer(INetworkPlayer* pNetworkPlayer) { + NetworkPlayerWindows* player = dynamic_cast(pNetworkPlayer); + if (player == nullptr || !player->IsLocal()) return false; + + int userIndex = player->GetUserIndex(); + if (userIndex < 0 || userIndex >= XUSER_MAX_COUNT) return false; + + player->CloseTransport(m_isHost); + SyncIQNetPlayer(player, false); + m_gameNetworkManager->PlayerLeaving(player); + NotifyPlayerChanged(player, true); + m_localPlayers[userIndex] = nullptr; + if (player == m_hostPlayer) m_hostPlayer = nullptr; + return true; +} + +void CPlatformNetworkManagerWindows::SetSessionTexturePackParentId(int id) { + m_sessionData.texturePackParentId = id; +} + +void CPlatformNetworkManagerWindows::SetSessionSubTexturePackId(int id) { + m_sessionData.subTexturePackId = static_cast(id); +} + +void CPlatformNetworkManagerWindows::Notify(int ID, ULONG_PTR Param) {} + +#endif \ No newline at end of file diff --git a/Minecraft.Client/Windows64/Network/PlatformNetworkManagerWindows.h b/Minecraft.Client/Windows64/Network/PlatformNetworkManagerWindows.h new file mode 100644 index 00000000..ffd95ea2 --- /dev/null +++ b/Minecraft.Client/Windows64/Network/PlatformNetworkManagerWindows.h @@ -0,0 +1,133 @@ +#pragma once + +#ifdef _WINDOWS64 + +#include +#include +#include + +#include "..\..\Common\Network\PlatformNetworkManagerInterface.h" +#include "..\..\Common\Network\SessionInfo.h" +#include "NetworkPlayerWindows.h" + +class CPlatformNetworkManagerWindows : public CPlatformNetworkManager { + friend class CGameNetworkManager; +public: + CPlatformNetworkManagerWindows(); + virtual ~CPlatformNetworkManagerWindows(); + + virtual bool Initialise(CGameNetworkManager* pGameNetworkManager, int flagIndexSize); + virtual void Terminate(); + virtual int GetJoiningReadyPercentage(); + virtual int CorrectErrorIDS(int IDS); + virtual void DoWork(); + virtual int GetPlayerCount(); + virtual int GetOnlinePlayerCount(); + virtual int GetLocalPlayerMask(int playerIndex); + virtual bool AddLocalPlayerByUserIndex(int userIndex); + virtual bool RemoveLocalPlayerByUserIndex(int userIndex); + virtual INetworkPlayer* GetLocalPlayerByUserIndex(int userIndex); + virtual INetworkPlayer* GetPlayerByIndex(int playerIndex); + virtual INetworkPlayer* GetPlayerByXuid(PlayerUID xuid); + virtual INetworkPlayer* GetPlayerBySmallId(unsigned char smallId); + virtual bool ShouldMessageForFullSession(); + virtual INetworkPlayer* GetHostPlayer(); + virtual bool IsHost(); + virtual bool JoinGameFromInviteInfo(int userIndex, int userMask, const INVITE_INFO* pInviteInfo); + virtual bool LeaveGame(bool bMigrateHost); + virtual bool IsInSession(); + virtual bool IsInGameplay(); + virtual bool IsReadyToPlayOrIdle(); + virtual bool IsInStatsEnabledSession(); + virtual bool SessionHasSpace(unsigned int spaceRequired = 1); + virtual void SendInviteGUI(int quadrant); + virtual bool IsAddingPlayer(); + virtual void HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, unsigned char privateSlots = 0); + virtual int JoinGame(FriendSessionInfo* searchResult, int localUsersMask, int primaryUserIndex); + virtual bool SetLocalGame(bool isLocal); + virtual bool IsLocalGame(); + virtual void SetPrivateGame(bool isPrivate); + virtual bool IsPrivateGame(); + virtual bool IsLeavingGame(); + virtual void ResetLeavingGame(); + virtual void RegisterPlayerChangedCallback(int iPad, void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, bool leaving), void* callbackParam); + virtual void UnRegisterPlayerChangedCallback(int iPad, void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, bool leaving), void* callbackParam); + virtual void HandleSignInChange(); + virtual bool _RunNetworkGame(); + virtual void UpdateAndSetGameSessionData(INetworkPlayer* pNetworkPlayerLeaving = NULL); + virtual void SystemFlagSet(INetworkPlayer* pNetworkPlayer, int index); + virtual bool SystemFlagGet(INetworkPlayer* pNetworkPlayer, int index); + virtual std::wstring GatherStats(); + virtual std::wstring GatherRTTStats(); + virtual std::vector* GetSessionList(int iPad, int localPlayers, bool partyOnly); + virtual bool GetGameSessionInfo(int iPad, SessionID sessionId, FriendSessionInfo* foundSession); + virtual void SetSessionsUpdatedCallback(void (*SessionsUpdatedCallback)(LPVOID pParam), LPVOID pSearchParam); + virtual void GetFullFriendSessionInfo(FriendSessionInfo* foundSession, void (*FriendSessionUpdatedFn)(bool success, void* pParam), void* pParam); + virtual void ForceFriendsSessionRefresh(); + virtual void FakeLocalPlayerJoined(); + void FakeLocalPlayerJoined(bool fakeHost) override; + void RegisterMirroredPlayer(IQNetPlayer* qnetPlayer); + void UnregisterMirroredPlayer(IQNetPlayer* qnetPlayer); + void ReleaseSmallId(unsigned char smallId); + bool JoinSplitScreen(int padIndex, unsigned char* outSmallId); + void UpdateMaxPlayers(unsigned char maxPlayers); + +private: + struct PendingClient { + SOCKET socket; + unsigned long remoteAddress; + DWORD acceptedAt; + }; + + virtual bool _LeaveGame(bool bMigrateHost, bool bLeaveRoom); + virtual void _HostGame(int usersMask, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, unsigned char privateSlots = 0); + virtual bool _StartGame(); + virtual bool RemoveLocalPlayer(INetworkPlayer* pNetworkPlayer); + virtual void SetSessionTexturePackParentId(int id); + virtual void SetSessionSubTexturePackId(int id); + virtual void Notify(int ID, ULONG_PTR Param); + + bool StartListener(unsigned short port, const char* bindIp); + void CloseListener(); + void ProcessDiscoveryRequests(); + void ProcessPendingClients(); + NetworkPlayerWindows* CreateLocalPlayer(int userIndex); + NetworkPlayerWindows* AddRemotePlayer(SOCKET socket, unsigned long remoteAddress, bool isHost); + void RemoveRemotePlayer(NetworkPlayerWindows* player); + void NotifyPlayerChanged(NetworkPlayerWindows* player, bool leaving); + void SyncIQNetPlayer(NetworkPlayerWindows* player, bool active); + void SetSessionLabel(FriendSessionInfo* sessionInfo, const wchar_t* label, SessionID sessionId); + + CGameNetworkManager* m_gameNetworkManager; + SOCKET m_listenSocket; + SOCKET m_discoverySocket; + unsigned short m_gamePort; + sockaddr_in m_hostAddress; + bool m_hostAddressValid; + bool m_winsockStarted; + bool m_isHost; + bool m_isFakeHost; + bool m_inSession; + bool m_inGameplay; + bool m_isLocalGame; + bool m_isPrivateGame; + bool m_isLeaving; + unsigned char m_nextSmallId; + unsigned char m_maxPlayers; + int m_flagIndexSize; + GameSessionData m_sessionData; + NetworkPlayerWindows* m_localPlayers[XUSER_MAX_COUNT]; + NetworkPlayerWindows* m_hostPlayer; + std::vector m_players; + std::vector m_freeSmallIds; + std::vector m_pendingClients; + std::mutex m_playersMutex; + void (*m_playerChangedCallback[XUSER_MAX_COUNT])(void* callbackParam, INetworkPlayer* pPlayer, bool leaving); + void* m_playerChangedCallbackParam[XUSER_MAX_COUNT]; + void (*m_sessionsUpdatedCallback)(LPVOID pParam); + LPVOID m_searchParam; +}; + +extern CPlatformNetworkManagerWindows* g_pPlatformNetworkManagerWindows; + +#endif \ No newline at end of file diff --git a/Minecraft.Client/Windows64/Network/WindowsNetworkConfig.h b/Minecraft.Client/Windows64/Network/WindowsNetworkConfig.h new file mode 100644 index 00000000..6c2a267e --- /dev/null +++ b/Minecraft.Client/Windows64/Network/WindowsNetworkConfig.h @@ -0,0 +1,17 @@ +#pragma once + +#ifdef _WINDOWS64 + +#define WIN64_NET_DEFAULT_PORT 25565 + +extern bool g_Win64MultiplayerHost; +extern bool g_Win64MultiplayerJoin; +extern bool g_Win64MultiplayerQuitOnDisconnect; +extern int g_Win64MultiplayerPort; +extern char g_Win64MultiplayerIP[256]; +extern bool g_Win64DedicatedServer; +extern int g_Win64DedicatedServerPort; +extern char g_Win64DedicatedServerBindIP[256]; +extern bool g_Win64DedicatedServerLanAdvertise; + +#endif diff --git a/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp b/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp deleted file mode 100644 index 6172bd0b..00000000 --- a/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp +++ /dev/null @@ -1,1860 +0,0 @@ -// Code implemented by LCEMP, credit if used on other repos -// https://github.com/LCEMP/LCEMP - -#include "stdafx.h" - -#ifdef _WINDOWS64 - -#include "WinsockNetLayer.h" -#include "../../Common/Network/PlatformNetworkManagerStub.h" -#include "../../../Minecraft.World/Socket.h" - -#if defined(MINECRAFT_SERVER_BUILD) -#include "../../../Minecraft.Server/Access/Access.h" -#include "../../../Minecraft.Server/ServerLogManager.h" -#include "../../../Minecraft.Server/ServerLogger.h" -#include "../../../Minecraft.Server/Security/SecurityConfig.h" -#include "../../../Minecraft.Server/Security/RateLimiter.h" -#endif - -#include "../../../Minecraft.World/DisconnectPacket.h" -#include "../../Minecraft.h" - -#include -#pragma comment(lib, "dnsapi.lib") -#include "../4JLibs/inc/4J_Profile.h" - -#include - -static bool RecvExact(SOCKET sock, BYTE* buf, int len); -#if defined(MINECRAFT_SERVER_BUILD) -static bool TryGetNumericRemoteIp(const sockaddr_in &remoteAddress, std::string *outIp); -#endif - -SOCKET WinsockNetLayer::s_listenSocket = INVALID_SOCKET; -SOCKET WinsockNetLayer::s_hostConnectionSocket = INVALID_SOCKET; -HANDLE WinsockNetLayer::s_acceptThread = nullptr; -HANDLE WinsockNetLayer::s_clientRecvThread = nullptr; - -bool WinsockNetLayer::s_isHost = false; -bool WinsockNetLayer::s_connected = false; -bool WinsockNetLayer::s_active = false; -bool WinsockNetLayer::s_initialized = false; - -BYTE WinsockNetLayer::s_localSmallId = 0; -BYTE WinsockNetLayer::s_hostSmallId = 0; -unsigned int WinsockNetLayer::s_nextSmallId = XUSER_MAX_COUNT; - -CRITICAL_SECTION WinsockNetLayer::s_sendLock[MINECRAFT_NET_MAX_PLAYERS]; -CRITICAL_SECTION WinsockNetLayer::s_connectionsLock; - -std::vector WinsockNetLayer::s_connections; - -SOCKET WinsockNetLayer::s_advertiseSock = INVALID_SOCKET; -HANDLE WinsockNetLayer::s_advertiseThread = nullptr; -volatile bool WinsockNetLayer::s_advertising = false; -Win64LANBroadcast WinsockNetLayer::s_advertiseData = {}; -CRITICAL_SECTION WinsockNetLayer::s_advertiseLock; -int WinsockNetLayer::s_hostGamePort = WIN64_NET_DEFAULT_PORT; - -SOCKET WinsockNetLayer::s_discoverySock = INVALID_SOCKET; -HANDLE WinsockNetLayer::s_discoveryThread = nullptr; -volatile bool WinsockNetLayer::s_discovering = false; -CRITICAL_SECTION WinsockNetLayer::s_discoveryLock; -std::vector WinsockNetLayer::s_discoveredSessions; - -CRITICAL_SECTION WinsockNetLayer::s_disconnectLock; -std::vector WinsockNetLayer::s_disconnectedSmallIds; - -CRITICAL_SECTION WinsockNetLayer::s_freeSmallIdLock; -std::vector WinsockNetLayer::s_freeSmallIds; -SOCKET WinsockNetLayer::s_smallIdToSocket[256]; -CRITICAL_SECTION WinsockNetLayer::s_smallIdToSocketLock; - -SOCKET WinsockNetLayer::s_splitScreenSocket[XUSER_MAX_COUNT] = { INVALID_SOCKET, INVALID_SOCKET, INVALID_SOCKET, INVALID_SOCKET }; -BYTE WinsockNetLayer::s_splitScreenSmallId[XUSER_MAX_COUNT] = { 0xFF, 0xFF, 0xFF, 0xFF }; -HANDLE WinsockNetLayer::s_splitScreenRecvThread[XUSER_MAX_COUNT] = {nullptr, nullptr, nullptr, nullptr}; - -HANDLE WinsockNetLayer::s_joinThread = nullptr; -volatile WinsockNetLayer::eJoinState WinsockNetLayer::s_joinState = WinsockNetLayer::eJoinState_Idle; -volatile int WinsockNetLayer::s_joinAttempt = 0; -volatile bool WinsockNetLayer::s_joinCancel = false; -char WinsockNetLayer::s_joinIP[256] = {}; -int WinsockNetLayer::s_joinPort = 0; -BYTE WinsockNetLayer::s_joinAssignedSmallId = 0; -DisconnectPacket::eDisconnectReason WinsockNetLayer::s_joinRejectReason = DisconnectPacket::eDisconnect_Quitting; - -bool g_Win64MultiplayerHost = false; -bool g_Win64MultiplayerJoin = false; -bool g_Win64MultiplayerQuitOnDisconnect = false; -int g_Win64MultiplayerPort = WIN64_NET_DEFAULT_PORT; -char g_Win64MultiplayerIP[256] = "127.0.0.1"; -bool g_Win64DedicatedServer = false; -int g_Win64DedicatedServerPort = WIN64_NET_DEFAULT_PORT; -char g_Win64DedicatedServerBindIP[256] = ""; -bool g_Win64DedicatedServerLanAdvertise = true; - -bool WinsockNetLayer::Initialize() -{ - if (s_initialized) return true; - - WSADATA wsaData; - int result = WSAStartup(MAKEWORD(2, 2), &wsaData); - if (result != 0) - { - app.DebugPrintf("WSAStartup failed: %d\n", result); - return false; - } - - for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++) { - InitializeCriticalSection(&s_sendLock[i]); - } - - InitializeCriticalSection(&s_connectionsLock); - InitializeCriticalSection(&s_advertiseLock); - InitializeCriticalSection(&s_discoveryLock); - InitializeCriticalSection(&s_disconnectLock); - InitializeCriticalSection(&s_freeSmallIdLock); - InitializeCriticalSection(&s_smallIdToSocketLock); - for (int i = 0; i < 256; i++) - s_smallIdToSocket[i] = INVALID_SOCKET; - - s_initialized = true; - - // Dedicated Server does not use LAN session discovery and therefore does not initiate discovery. - if (!g_Win64DedicatedServer) - { - StartDiscovery(); - } - - return true; -} - -void WinsockNetLayer::Shutdown() -{ - StopAdvertising(); - StopDiscovery(); - - s_joinCancel = true; - if (s_joinThread != nullptr) - { - WaitForSingleObject(s_joinThread, 5000); - CloseHandle(s_joinThread); - s_joinThread = nullptr; - } - s_joinState = eJoinState_Idle; - - s_active = false; - s_connected = false; - - if (s_listenSocket != INVALID_SOCKET) - { - closesocket(s_listenSocket); - s_listenSocket = INVALID_SOCKET; - } - - if (s_hostConnectionSocket != INVALID_SOCKET) - { - closesocket(s_hostConnectionSocket); - s_hostConnectionSocket = INVALID_SOCKET; - } - - // Stop accept loop first so no new RecvThread can be created while shutting down. - if (s_acceptThread != nullptr) - { - WaitForSingleObject(s_acceptThread, 2000); - CloseHandle(s_acceptThread); - s_acceptThread = nullptr; - } - - std::vector recvThreads; - EnterCriticalSection(&s_connectionsLock); - for (size_t i = 0; i < s_connections.size(); i++) - { - s_connections[i].active = false; - if (s_connections[i].tcpSocket != INVALID_SOCKET) - { - closesocket(s_connections[i].tcpSocket); - s_connections[i].tcpSocket = INVALID_SOCKET; - } - if (s_connections[i].recvThread != nullptr) - { - recvThreads.push_back(s_connections[i].recvThread); - s_connections[i].recvThread = nullptr; - } - } - LeaveCriticalSection(&s_connectionsLock); - - // Wait for all host-side receive threads to exit before destroying state. - for (size_t i = 0; i < recvThreads.size(); i++) - { - WaitForSingleObject(recvThreads[i], 2000); - CloseHandle(recvThreads[i]); - } - - EnterCriticalSection(&s_connectionsLock); - s_connections.clear(); - LeaveCriticalSection(&s_connectionsLock); - - if (s_clientRecvThread != nullptr) - { - WaitForSingleObject(s_clientRecvThread, 2000); - CloseHandle(s_clientRecvThread); - s_clientRecvThread = nullptr; - } - - for (int i = 0; i < XUSER_MAX_COUNT; i++) - { - if (s_splitScreenSocket[i] != INVALID_SOCKET) - { - closesocket(s_splitScreenSocket[i]); - s_splitScreenSocket[i] = INVALID_SOCKET; - } - if (s_splitScreenRecvThread[i] != nullptr) - { - WaitForSingleObject(s_splitScreenRecvThread[i], 2000); - CloseHandle(s_splitScreenRecvThread[i]); - s_splitScreenRecvThread[i] = nullptr; - } - s_splitScreenSmallId[i] = 0xFF; - } - - if (s_initialized) - { - EnterCriticalSection(&s_disconnectLock); - s_disconnectedSmallIds.clear(); - LeaveCriticalSection(&s_disconnectLock); - - EnterCriticalSection(&s_freeSmallIdLock); - s_freeSmallIds.clear(); - LeaveCriticalSection(&s_freeSmallIdLock); - - for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++) { - InitializeCriticalSection(&s_sendLock[i]); - } - DeleteCriticalSection(&s_connectionsLock); - DeleteCriticalSection(&s_advertiseLock); - DeleteCriticalSection(&s_discoveryLock); - DeleteCriticalSection(&s_disconnectLock); - DeleteCriticalSection(&s_freeSmallIdLock); - DeleteCriticalSection(&s_smallIdToSocketLock); - WSACleanup(); - s_initialized = false; - } -} - -bool WinsockNetLayer::HostGame(int port, const char* bindIp) -{ - if (!s_initialized && !Initialize()) return false; - - s_isHost = true; - s_localSmallId = 0; - s_hostSmallId = 0; - s_nextSmallId = XUSER_MAX_COUNT; - s_hostGamePort = port; - - EnterCriticalSection(&s_freeSmallIdLock); - s_freeSmallIds.clear(); - LeaveCriticalSection(&s_freeSmallIdLock); - EnterCriticalSection(&s_smallIdToSocketLock); - for (int i = 0; i < 256; i++) - s_smallIdToSocket[i] = INVALID_SOCKET; - LeaveCriticalSection(&s_smallIdToSocketLock); - - struct addrinfo hints = {}; - struct addrinfo* result = nullptr; - - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - hints.ai_flags = (bindIp == nullptr || bindIp[0] == 0) ? AI_PASSIVE : 0; - - char portStr[16]; - sprintf_s(portStr, "%d", port); - - const char* resolvedBindIp = (bindIp != nullptr && bindIp[0] != 0) ? bindIp : nullptr; - int iResult = getaddrinfo(resolvedBindIp, portStr, &hints, &result); - if (iResult != 0) - { - app.DebugPrintf("getaddrinfo failed for %s:%d - %d\n", - resolvedBindIp != nullptr ? resolvedBindIp : "*", - port, - iResult); - return false; - } - - s_listenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); - if (s_listenSocket == INVALID_SOCKET) - { - app.DebugPrintf("socket() failed: %d\n", WSAGetLastError()); - freeaddrinfo(result); - return false; - } - - int opt = 1; - setsockopt(s_listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt)); - - iResult = ::bind(s_listenSocket, result->ai_addr, static_cast(result->ai_addrlen)); - freeaddrinfo(result); - if (iResult == SOCKET_ERROR) - { - app.DebugPrintf("bind() failed: %d\n", WSAGetLastError()); - closesocket(s_listenSocket); - s_listenSocket = INVALID_SOCKET; - return false; - } - - iResult = listen(s_listenSocket, SOMAXCONN); - if (iResult == SOCKET_ERROR) - { - app.DebugPrintf("listen() failed: %d\n", WSAGetLastError()); - closesocket(s_listenSocket); - s_listenSocket = INVALID_SOCKET; - return false; - } - - s_active = true; - s_connected = true; - - s_acceptThread = CreateThread(nullptr, 0, AcceptThreadProc, nullptr, 0, nullptr); - - app.DebugPrintf("Win64 LAN: Hosting on %s:%d\n", - resolvedBindIp != nullptr ? resolvedBindIp : "*", - port); - return true; -} - -// Resolve a Minecraft SRV record (_minecraft._tcp.) to get the actual host and port. -// Returns true if an SRV record was found and outHost/outPort were updated. -// Returns false (no changes) for numeric IPs, missing records, or DNS errors. -static bool ResolveSRV(const char* hostname, char* outHost, size_t outHostSize, int* outPort) -{ - // Skip numeric IPs (starts with digit, contains no letters) - if (hostname[0] >= '0' && hostname[0] <= '9') - { - bool hasLetter = false; - for (const char* p = hostname; *p; ++p) - if ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z')) { hasLetter = true; break; } - if (!hasLetter) return false; - } - - char srvName[300]; - sprintf_s(srvName, "_minecraft._tcp.%s", hostname); - - DNS_RECORD* records = nullptr; - DNS_STATUS status = DnsQuery_A(srvName, DNS_TYPE_SRV, DNS_QUERY_STANDARD, nullptr, &records, nullptr); - if (status != 0 || records == nullptr) - return false; - - // Find the first SRV record - for (DNS_RECORD* r = records; r != nullptr; r = r->pNext) - { - if (r->wType == DNS_TYPE_SRV) - { - strncpy_s(outHost, outHostSize, r->Data.SRV.pNameTarget, _TRUNCATE); - *outPort = r->Data.SRV.wPort; - DnsRecordListFree(records, DnsFreeRecordList); - return true; - } - } - - DnsRecordListFree(records, DnsFreeRecordList); - return false; -} - -bool WinsockNetLayer::JoinGame(const char* ip, int port) -{ - if (!s_initialized && !Initialize()) return false; - - s_isHost = false; - s_hostSmallId = 0; - s_connected = false; - s_active = false; - - if (s_hostConnectionSocket != INVALID_SOCKET) - { - closesocket(s_hostConnectionSocket); - s_hostConnectionSocket = INVALID_SOCKET; - } - - // Wait for old client recv thread to fully exit before starting a new connection. - // Without this, the old thread can read from the new socket (s_hostConnectionSocket - // is a global) and steal bytes from the new connection's TCP stream, causing - // packet stream misalignment on reconnect. - if (s_clientRecvThread != nullptr) - { - WaitForSingleObject(s_clientRecvThread, 5000); - CloseHandle(s_clientRecvThread); - s_clientRecvThread = nullptr; - } - - // Try SRV record resolution for hostnames - char resolvedHost[256]; - int resolvedPort = port; - strncpy_s(resolvedHost, sizeof(resolvedHost), ip, _TRUNCATE); - if (ResolveSRV(ip, resolvedHost, sizeof(resolvedHost), &resolvedPort)) - app.DebugPrintf("SRV resolved %s -> %s:%d\n", ip, resolvedHost, resolvedPort); - - struct addrinfo hints = {}; - struct addrinfo* result = nullptr; - - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - - char portStr[16]; - sprintf_s(portStr, "%d", resolvedPort); - - int iResult = getaddrinfo(resolvedHost, portStr, &hints, &result); - if (iResult != 0) - { - app.DebugPrintf("getaddrinfo failed for %s:%d - %d\n", ip, port, iResult); - return false; - } - - bool connected = false; - BYTE assignedSmallId = 0; - const int maxAttempts = 3; - const int connectTimeoutSec = 5; - - for (int attempt = 0; attempt < maxAttempts; ++attempt) - { - if (s_joinCancel) - { - app.DebugPrintf("JoinGame cancelled by user\n"); - break; - } - - s_hostConnectionSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); - if (s_hostConnectionSocket == INVALID_SOCKET) - { - app.DebugPrintf("socket() failed: %d\n", WSAGetLastError()); - break; - } - - int noDelay = 1; - setsockopt(s_hostConnectionSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&noDelay, sizeof(noDelay)); - - // Use non-blocking connect with select() timeout so we don't freeze - // the game for the full OS TCP timeout when the server is unreachable. - u_long nonBlocking = 1; - ioctlsocket(s_hostConnectionSocket, FIONBIO, &nonBlocking); - - iResult = connect(s_hostConnectionSocket, result->ai_addr, static_cast(result->ai_addrlen)); - if (iResult == SOCKET_ERROR) - { - int err = WSAGetLastError(); - if (err == WSAEWOULDBLOCK) - { - fd_set writeSet, errorSet; - FD_ZERO(&writeSet); - FD_SET(s_hostConnectionSocket, &writeSet); - FD_ZERO(&errorSet); - FD_SET(s_hostConnectionSocket, &errorSet); - - struct timeval tv; - tv.tv_sec = connectTimeoutSec; - tv.tv_usec = 0; - - int selectResult = select(0, nullptr, &writeSet, &errorSet, &tv); - if (selectResult <= 0 || FD_ISSET(s_hostConnectionSocket, &errorSet)) - { - app.DebugPrintf("connect() to %s:%d timed out or failed (attempt %d/%d)\n", ip, port, attempt + 1, maxAttempts); - closesocket(s_hostConnectionSocket); - s_hostConnectionSocket = INVALID_SOCKET; - continue; - } - // Connection succeeded via non-blocking path - } - else - { - app.DebugPrintf("connect() to %s:%d failed (attempt %d/%d): %d\n", ip, port, attempt + 1, maxAttempts, err); - closesocket(s_hostConnectionSocket); - s_hostConnectionSocket = INVALID_SOCKET; - Sleep(200); - continue; - } - } - - // Restore blocking mode for normal socket I/O - u_long blocking = 0; - ioctlsocket(s_hostConnectionSocket, FIONBIO, &blocking); - - // Set a recv timeout so we don't block forever waiting for the small ID - DWORD recvTimeout = connectTimeoutSec * 1000; - setsockopt(s_hostConnectionSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&recvTimeout, sizeof(recvTimeout)); - - BYTE assignBuf[1]; - int bytesRecv = recv(s_hostConnectionSocket, (char*)assignBuf, 1, 0); - if (bytesRecv != 1) - { - app.DebugPrintf("Failed to receive small ID assignment from host (attempt %d/%d)\n", attempt + 1, maxAttempts); - closesocket(s_hostConnectionSocket); - s_hostConnectionSocket = INVALID_SOCKET; - continue; - } - - if (assignBuf[0] == WIN64_SMALLID_REJECT) - { - BYTE rejectBuf[5]; - if (!RecvExact(s_hostConnectionSocket, rejectBuf, 5)) - { - app.DebugPrintf("Failed to receive reject reason from host\n"); - closesocket(s_hostConnectionSocket); - s_hostConnectionSocket = INVALID_SOCKET; - Sleep(200); - continue; - } - // rejectBuf[0] = packet id (255), rejectBuf[1..4] = 4-byte big-endian reason - int reason = ((rejectBuf[1] & 0xff) << 24) | ((rejectBuf[2] & 0xff) << 16) | - ((rejectBuf[3] & 0xff) << 8) | (rejectBuf[4] & 0xff); - Minecraft::GetInstance()->connectionDisconnected(ProfileManager.GetPrimaryPad(), (DisconnectPacket::eDisconnectReason)reason); - closesocket(s_hostConnectionSocket); - s_hostConnectionSocket = INVALID_SOCKET; - freeaddrinfo(result); - return false; - } - - assignedSmallId = assignBuf[0]; - connected = true; - break; - } - freeaddrinfo(result); - - if (!connected) - { - return false; - } - - // Clear the recv timeout now that the handshake is complete. - // The recv thread should block indefinitely waiting for data. - DWORD noTimeout = 0; - setsockopt(s_hostConnectionSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&noTimeout, sizeof(noTimeout)); - - s_localSmallId = assignedSmallId; - - // Save the host IP and port so JoinSplitScreen can connect to the same host - // regardless of how the connection was initiated (UI vs command line). - strncpy_s(g_Win64MultiplayerIP, sizeof(g_Win64MultiplayerIP), ip, _TRUNCATE); - g_Win64MultiplayerPort = port; - - app.DebugPrintf("Win64 LAN: Connected to %s:%d, assigned smallId=%d\n", ip, port, s_localSmallId); - - s_active = true; - s_connected = true; - - s_clientRecvThread = CreateThread(nullptr, 0, ClientRecvThreadProc, nullptr, 0, nullptr); - - return true; -} - -bool WinsockNetLayer::BeginJoinGame(const char* ip, int port) -{ - if (!s_initialized && !Initialize()) return false; - - // Clean up any prior join attempt - CancelJoinGame(); - if (s_joinThread != nullptr) - { - WaitForSingleObject(s_joinThread, 5000); - CloseHandle(s_joinThread); - s_joinThread = nullptr; - } - - s_isHost = false; - s_hostSmallId = 0; - s_connected = false; - s_active = false; - - if (s_hostConnectionSocket != INVALID_SOCKET) - { - closesocket(s_hostConnectionSocket); - s_hostConnectionSocket = INVALID_SOCKET; - } - - if (s_clientRecvThread != nullptr) - { - WaitForSingleObject(s_clientRecvThread, 5000); - CloseHandle(s_clientRecvThread); - s_clientRecvThread = nullptr; - } - - strncpy_s(s_joinIP, sizeof(s_joinIP), ip, _TRUNCATE); - s_joinPort = port; - s_joinAttempt = 0; - s_joinCancel = false; - s_joinAssignedSmallId = 0; - s_joinRejectReason = DisconnectPacket::eDisconnect_Quitting; - s_joinState = eJoinState_Connecting; - - s_joinThread = CreateThread(nullptr, 0, JoinThreadProc, nullptr, 0, nullptr); - if (s_joinThread == nullptr) - { - s_joinState = eJoinState_Failed; - return false; - } - return true; -} - -DWORD WINAPI WinsockNetLayer::JoinThreadProc(LPVOID param) -{ - // Try SRV record resolution for hostnames - char resolvedHost[256]; - int resolvedPort = s_joinPort; - strncpy_s(resolvedHost, sizeof(resolvedHost), s_joinIP, _TRUNCATE); - if (ResolveSRV(s_joinIP, resolvedHost, sizeof(resolvedHost), &resolvedPort)) - app.DebugPrintf("SRV resolved %s -> %s:%d\n", s_joinIP, resolvedHost, resolvedPort); - - struct addrinfo hints = {}, *result = nullptr; - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - - char portStr[16]; - sprintf_s(portStr, "%d", resolvedPort); - - if (getaddrinfo(resolvedHost, portStr, &hints, &result) != 0) - { - app.DebugPrintf("getaddrinfo failed for %s:%d\n", resolvedHost, resolvedPort); - s_joinState = eJoinState_Failed; - return 0; - } - - bool connected = false; - BYTE assignedSmallId = 0; - SOCKET sock = INVALID_SOCKET; - const int connectTimeoutSec = 5; - - for (int attempt = 0; attempt < JOIN_MAX_ATTEMPTS; ++attempt) - { - if (s_joinCancel) { freeaddrinfo(result); s_joinState = eJoinState_Cancelled; return 0; } - - s_joinAttempt = attempt + 1; - - sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol); - if (sock == INVALID_SOCKET) break; - - int noDelay = 1; - setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char*)&noDelay, sizeof(noDelay)); - - // Non-blocking connect with select() timeout - u_long nonBlocking = 1; - ioctlsocket(sock, FIONBIO, &nonBlocking); - - int iResult = connect(sock, result->ai_addr, static_cast(result->ai_addrlen)); - if (iResult == SOCKET_ERROR) - { - int err = WSAGetLastError(); - if (err == WSAEWOULDBLOCK) - { - fd_set writeSet, errorSet; - FD_ZERO(&writeSet); FD_SET(sock, &writeSet); - FD_ZERO(&errorSet); FD_SET(sock, &errorSet); - struct timeval tv = { connectTimeoutSec, 0 }; - - int selectResult = select(0, nullptr, &writeSet, &errorSet, &tv); - if (selectResult <= 0 || FD_ISSET(sock, &errorSet)) - { - app.DebugPrintf("connect() to %s:%d timed out (attempt %d/%d)\n", s_joinIP, s_joinPort, attempt + 1, JOIN_MAX_ATTEMPTS); - closesocket(sock); sock = INVALID_SOCKET; - continue; - } - } - else - { - app.DebugPrintf("connect() to %s:%d failed (attempt %d/%d): %d\n", s_joinIP, s_joinPort, attempt + 1, JOIN_MAX_ATTEMPTS, err); - closesocket(sock); sock = INVALID_SOCKET; - for (int w = 0; w < 4 && !s_joinCancel; w++) Sleep(50); - continue; - } - } - - // Restore blocking mode - u_long blocking = 0; - ioctlsocket(sock, FIONBIO, &blocking); - - // Temporary recv timeout for the handshake only - DWORD recvTimeout = connectTimeoutSec * 1000; - setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&recvTimeout, sizeof(recvTimeout)); - - BYTE assignBuf[1]; - if (recv(sock, (char*)assignBuf, 1, 0) != 1) - { - app.DebugPrintf("Failed to receive small ID assignment from host (attempt %d/%d)\n", attempt + 1, JOIN_MAX_ATTEMPTS); - closesocket(sock); sock = INVALID_SOCKET; - continue; - } - - if (assignBuf[0] == WIN64_SMALLID_REJECT) - { - BYTE rejectBuf[5]; - if (!RecvExact(sock, rejectBuf, 5)) - { - app.DebugPrintf("Failed to receive reject reason from host\n"); - closesocket(sock); sock = INVALID_SOCKET; - continue; - } - int reason = ((rejectBuf[1] & 0xff) << 24) | ((rejectBuf[2] & 0xff) << 16) | - ((rejectBuf[3] & 0xff) << 8) | (rejectBuf[4] & 0xff); - s_joinRejectReason = (DisconnectPacket::eDisconnectReason)reason; - closesocket(sock); - freeaddrinfo(result); - s_joinState = eJoinState_Rejected; - return 0; - } - - assignedSmallId = assignBuf[0]; - connected = true; - break; - } - freeaddrinfo(result); - - if (s_joinCancel) - { - if (sock != INVALID_SOCKET) closesocket(sock); - s_joinState = eJoinState_Cancelled; - return 0; - } - - if (!connected) - { - s_joinState = eJoinState_Failed; - return 0; - } - - // Clear recv timeout before handing socket to recv thread - DWORD noTimeout = 0; - setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&noTimeout, sizeof(noTimeout)); - - s_hostConnectionSocket = sock; - s_joinAssignedSmallId = assignedSmallId; - s_joinState = eJoinState_Success; - return 0; -} - -void WinsockNetLayer::CancelJoinGame() -{ - s_joinCancel = true; - - // Close socket to immediately unblock any in-progress connect/select/recv - SOCKET sock = s_hostConnectionSocket; - if (sock != INVALID_SOCKET) - { - s_hostConnectionSocket = INVALID_SOCKET; - closesocket(sock); - } - - if (s_joinState == eJoinState_Success || s_joinState == eJoinState_Connecting) - { - s_joinState = eJoinState_Cancelled; - } -} - -bool WinsockNetLayer::FinalizeJoin() -{ - if (s_joinState != eJoinState_Success) - return false; - - s_localSmallId = s_joinAssignedSmallId; - - strncpy_s(g_Win64MultiplayerIP, sizeof(g_Win64MultiplayerIP), s_joinIP, _TRUNCATE); - g_Win64MultiplayerPort = s_joinPort; - - app.DebugPrintf("Win64 LAN: Connected to %s:%d, assigned smallId=%d\n", - s_joinIP, s_joinPort, s_localSmallId); - - s_active = true; - s_connected = true; - - s_clientRecvThread = CreateThread(nullptr, 0, ClientRecvThreadProc, nullptr, 0, nullptr); - - if (s_joinThread != nullptr) - { - WaitForSingleObject(s_joinThread, 2000); - CloseHandle(s_joinThread); - s_joinThread = nullptr; - } - - s_joinState = eJoinState_Idle; - return true; -} - -WinsockNetLayer::eJoinState WinsockNetLayer::GetJoinState() { return s_joinState; } -int WinsockNetLayer::GetJoinAttempt() { return s_joinAttempt; } -int WinsockNetLayer::GetJoinMaxAttempts() { return JOIN_MAX_ATTEMPTS; } -DisconnectPacket::eDisconnectReason WinsockNetLayer::GetJoinRejectReason() { return s_joinRejectReason; } - -bool WinsockNetLayer::SendOnSocket(BYTE targetSmallId, SOCKET sock, const void* data, int dataSize) -{ - if (sock == INVALID_SOCKET || dataSize <= 0 || dataSize > WIN64_NET_MAX_PACKET_SIZE) return false; - - EnterCriticalSection(&s_sendLock[targetSmallId]); - - BYTE header[4]; - header[0] = static_cast((dataSize >> 24) & 0xFF); - header[1] = static_cast((dataSize >> 16) & 0xFF); - header[2] = static_cast((dataSize >> 8) & 0xFF); - header[3] = static_cast(dataSize & 0xFF); - - int totalSent = 0; - int toSend = 4; - while (totalSent < toSend) - { - int sent = send(sock, (const char*)header + totalSent, toSend - totalSent, 0); - if (sent == SOCKET_ERROR || sent == 0) - { - LeaveCriticalSection(&s_sendLock[targetSmallId]); - return false; - } - totalSent += sent; - } - - totalSent = 0; - while (totalSent < dataSize) - { - int sent = send(sock, static_cast(data) + totalSent, dataSize - totalSent, 0); - if (sent == SOCKET_ERROR || sent == 0) - { - LeaveCriticalSection(&s_sendLock[targetSmallId]); - return false; - } - totalSent += sent; - } - - LeaveCriticalSection(&s_sendLock[targetSmallId]); - return true; -} - -bool WinsockNetLayer::SendToSmallId(BYTE targetSmallId, const void* data, int dataSize) -{ - if (!s_active) return false; - - if (s_isHost) - { - SOCKET sock = GetSocketForSmallId(targetSmallId); - if (sock == INVALID_SOCKET) return false; - - return SendOnSocket(targetSmallId, sock, data, dataSize); - } else { - return SendOnSocket(targetSmallId, s_hostConnectionSocket, data, dataSize); - } -} - -SOCKET WinsockNetLayer::GetSocketForSmallId(BYTE smallId) -{ - EnterCriticalSection(&s_smallIdToSocketLock); - SOCKET sock = s_smallIdToSocket[smallId]; - LeaveCriticalSection(&s_smallIdToSocketLock); - return sock; -} - -void WinsockNetLayer::ClearSocketForSmallId(BYTE smallId) -{ - EnterCriticalSection(&s_smallIdToSocketLock); - s_smallIdToSocket[smallId] = INVALID_SOCKET; - LeaveCriticalSection(&s_smallIdToSocketLock); -} - -// Send reject handshake: sentinel 0xFF + DisconnectPacket wire format (1 byte id 255 + 4 byte big-endian reason). Then caller closes socket. -static void SendRejectWithReason(SOCKET clientSocket, DisconnectPacket::eDisconnectReason reason) -{ - BYTE buf[6]; - buf[0] = WIN64_SMALLID_REJECT; - buf[1] = (BYTE)255; // DisconnectPacket packet id - int r = (int)reason; - buf[2] = (BYTE)((r >> 24) & 0xff); - buf[3] = (BYTE)((r >> 16) & 0xff); - buf[4] = (BYTE)((r >> 8) & 0xff); - buf[5] = (BYTE)(r & 0xff); - send(clientSocket, (const char*)buf, sizeof(buf), 0); -} - -static bool RecvExact(SOCKET sock, BYTE* buf, int len) -{ - int totalRecv = 0; - while (totalRecv < len) - { - int r = recv(sock, (char*)buf + totalRecv, len - totalRecv, 0); - if (r <= 0) return false; - totalRecv += r; - } - return true; -} - -#if defined(MINECRAFT_SERVER_BUILD) -static bool TryGetNumericRemoteIp(const sockaddr_in &remoteAddress, std::string *outIp) -{ - if (outIp == nullptr) - { - return false; - } - - outIp->clear(); - char ipBuffer[64] = {}; - const char *ip = inet_ntop(AF_INET, (void *)&remoteAddress.sin_addr, ipBuffer, sizeof(ipBuffer)); - if (ip == nullptr || ip[0] == 0) - { - return false; - } - - *outIp = ip; - return true; -} - -enum EProxyParseResult -{ - eProxyParse_Success, // Valid PROXY TCP4 header, IP extracted - eProxyParse_Unknown, // Valid PROXY UNKNOWN header, no IP available - eProxyParse_Malformed, // Invalid header format - eProxyParse_Timeout, // Recv timed out - eProxyParse_SocketError // Socket error during read -}; - -/** - * Parse a PROXY protocol v1 header from the socket. - * Must be called immediately after accept(), before any game data is read. - * Sets a 5-second recv timeout, reads the header, restores timeout on all paths. - */ -static EProxyParseResult TryReadProxyProtocolHeader(SOCKET sock, std::string *outSrcIp) -{ - if (outSrcIp != nullptr) - outSrcIp->clear(); - - // Set 5-second recv timeout for the header read - DWORD timeout = 5000; - setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof(timeout)); - - auto restoreTimeout = [sock]() { - DWORD noTimeout = 0; - setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&noTimeout, sizeof(noTimeout)); - }; - - // Peek at first 6 bytes to check for "PROXY " prefix - char peekBuf[6]; - int peekResult = recv(sock, peekBuf, 6, MSG_PEEK); - if (peekResult == 0) - { - restoreTimeout(); - return eProxyParse_SocketError; - } - if (peekResult == SOCKET_ERROR) - { - restoreTimeout(); - int err = WSAGetLastError(); - return (err == WSAETIMEDOUT) ? eProxyParse_Timeout : eProxyParse_SocketError; - } - if (peekResult < 6 || memcmp(peekBuf, "PROXY ", 6) != 0) - { - restoreTimeout(); - return eProxyParse_Malformed; - } - - // Consume header byte-by-byte until \r\n (max 107 bytes per PROXY v1 spec) - char lineBuf[108] = {}; - int lineLen = 0; - bool foundEnd = false; - - while (lineLen < 107) - { - char ch; - int r = recv(sock, &ch, 1, 0); - if (r != 1) - { - restoreTimeout(); - int err = WSAGetLastError(); - return (r == SOCKET_ERROR && err == WSAETIMEDOUT) ? eProxyParse_Timeout : eProxyParse_SocketError; - } - lineBuf[lineLen++] = ch; - - if (lineLen >= 2 && lineBuf[lineLen - 2] == '\r' && lineBuf[lineLen - 1] == '\n') - { - foundEnd = true; - lineBuf[lineLen - 2] = '\0'; // null-terminate, strip \r\n - break; - } - } - - restoreTimeout(); - - if (!foundEnd) - { - return eProxyParse_Malformed; - } - - // Parse: "PROXY TCP4 " - // or: "PROXY UNKNOWN" - char *tokens[6] = {}; - int tokenCount = 0; - char *ctx = nullptr; - char *tok = strtok_s(lineBuf, " ", &ctx); - while (tok != nullptr && tokenCount < 6) - { - tokens[tokenCount++] = tok; - tok = strtok_s(nullptr, " ", &ctx); - } - - if (tokenCount < 2 || strcmp(tokens[0], "PROXY") != 0) - { - return eProxyParse_Malformed; - } - - if (strcmp(tokens[1], "UNKNOWN") == 0) - { - return eProxyParse_Unknown; - } - - if (strcmp(tokens[1], "TCP4") != 0 || tokenCount < 6) - { - return eProxyParse_Malformed; - } - - // Validate src_ip with inet_pton - struct in_addr addr; - if (inet_pton(AF_INET, tokens[2], &addr) != 1) - { - return eProxyParse_Malformed; - } - - if (outSrcIp != nullptr) - { - *outSrcIp = tokens[2]; - } - - return eProxyParse_Success; -} -#endif - -void WinsockNetLayer::HandleDataReceived(BYTE fromSmallId, BYTE toSmallId, unsigned char* data, unsigned int dataSize) -{ - INetworkPlayer* pPlayerFrom = g_NetworkManager.GetPlayerBySmallId(fromSmallId); - INetworkPlayer* pPlayerTo = g_NetworkManager.GetPlayerBySmallId(toSmallId); - - if (pPlayerFrom == nullptr || pPlayerTo == nullptr) - { - app.DebugPrintf("NET RECV: DROPPED %u bytes from=%d to=%d (player NULL: from=%p to=%p)\n", - dataSize, fromSmallId, toSmallId, pPlayerFrom, pPlayerTo); - return; - } - - if (s_isHost) - { - ::Socket* pSocket = pPlayerFrom->GetSocket(); - if (pSocket != nullptr) - pSocket->pushDataToQueue(data, dataSize, false); - else - app.DebugPrintf("NET RECV: DROPPED %u bytes, host pSocket NULL for from=%d\n", dataSize, fromSmallId); - } - else - { - ::Socket* pSocket = pPlayerTo->GetSocket(); - if (pSocket != nullptr) - pSocket->pushDataToQueue(data, dataSize, true); - else - app.DebugPrintf("NET RECV: DROPPED %u bytes, client pSocket NULL for to=%d\n", dataSize, toSmallId); - } -} - -DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param) -{ - while (s_active) - { - sockaddr_in remoteAddress; - ZeroMemory(&remoteAddress, sizeof(remoteAddress)); - int remoteAddressLength = sizeof(remoteAddress); - SOCKET clientSocket = accept(s_listenSocket, (sockaddr*)&remoteAddress, &remoteAddressLength); - if (clientSocket == INVALID_SOCKET) - { - if (s_active) - app.DebugPrintf("accept() failed: %d\n", WSAGetLastError()); - break; - } - - int noDelay = 1; - setsockopt(clientSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&noDelay, sizeof(noDelay)); - -#if defined(MINECRAFT_SERVER_BUILD) - std::string remoteIp; - bool hasRemoteIp = TryGetNumericRemoteIp(remoteAddress, &remoteIp); - - // PROXY protocol v1: parse real client IP from tunnel header - if (g_Win64DedicatedServer && ServerRuntime::Security::GetSettings().proxyProtocol) - { - std::string proxiedIp; - EProxyParseResult proxyResult = TryReadProxyProtocolHeader(clientSocket, &proxiedIp); - if (proxyResult == eProxyParse_Success) - { - ServerRuntime::LogInfof("network", "PROXY: real client IP %s (tunnel: %s)", - proxiedIp.c_str(), hasRemoteIp ? remoteIp.c_str() : "unknown"); - remoteIp = proxiedIp; - hasRemoteIp = true; - } - else if (proxyResult == eProxyParse_Unknown) - { - ServerRuntime::LogInfof("network", "PROXY: UNKNOWN header, keeping tunnel IP"); - } - else - { - ServerRuntime::LogWarnf("network", "PROXY: header parse failed (result=%d) from %s", - (int)proxyResult, hasRemoteIp ? remoteIp.c_str() : "unknown"); - const char *rejectIp = hasRemoteIp ? remoteIp.c_str() : "unknown"; - ServerRuntime::ServerLogManager::OnRejectedTcpConnection(rejectIp, - ServerRuntime::ServerLogManager::eTcpRejectReason_InvalidProxyHeader); - closesocket(clientSocket); - continue; - } - } - - const char *remoteIpForLog = hasRemoteIp ? remoteIp.c_str() : "unknown"; - if (g_Win64DedicatedServer) - { - ServerRuntime::ServerLogManager::OnIncomingTcpConnection(remoteIpForLog); - if (hasRemoteIp && ServerRuntime::Access::IsIpBanned(remoteIp)) - { - ServerRuntime::ServerLogManager::OnRejectedTcpConnection(remoteIpForLog, ServerRuntime::ServerLogManager::eTcpRejectReason_BannedIp); - SendRejectWithReason(clientSocket, DisconnectPacket::eDisconnect_Banned); - closesocket(clientSocket); - continue; - } - - // Rate limiting: reject connections that exceed the per-IP sliding window - if (hasRemoteIp) - { - const auto &secSettings = ServerRuntime::Security::GetSettings(); - bool allowed = ServerRuntime::Security::GetGlobalRateLimiter().AllowConnection( - remoteIp, - secSettings.rateLimitConnectionsPerWindow, - secSettings.rateLimitWindowSeconds * 1000); - if (!allowed) - { - ServerRuntime::ServerLogManager::OnRejectedTcpConnection(remoteIpForLog, ServerRuntime::ServerLogManager::eTcpRejectReason_RateLimited); - closesocket(clientSocket); - continue; - } - } - } -#endif - - extern QNET_STATE _iQNetStubState; - if (_iQNetStubState != QNET_STATE_GAME_PLAY) - { -#if defined(MINECRAFT_SERVER_BUILD) - if (g_Win64DedicatedServer) - { - ServerRuntime::ServerLogManager::OnRejectedTcpConnection(remoteIpForLog, ServerRuntime::ServerLogManager::eTcpRejectReason_GameNotReady); - } - else -#endif - { - app.DebugPrintf("Win64 LAN: Rejecting connection, game not ready\n"); - } - closesocket(clientSocket); - continue; - } - - extern CPlatformNetworkManagerStub* g_pPlatformNetworkManager; - if (g_pPlatformNetworkManager != nullptr && !g_pPlatformNetworkManager->CanAcceptMoreConnections()) - { -#if defined(MINECRAFT_SERVER_BUILD) - if (g_Win64DedicatedServer) - { - ServerRuntime::ServerLogManager::OnRejectedTcpConnection(remoteIpForLog, ServerRuntime::ServerLogManager::eTcpRejectReason_ServerFull); - } - else -#endif - { - app.DebugPrintf("Win64 LAN: Rejecting connection, server at max players\n"); - } - SendRejectWithReason(clientSocket, DisconnectPacket::eDisconnect_ServerFull); - closesocket(clientSocket); - continue; - } - - BYTE assignedSmallId; - EnterCriticalSection(&s_freeSmallIdLock); - if (!s_freeSmallIds.empty()) - { - assignedSmallId = s_freeSmallIds.back(); - s_freeSmallIds.pop_back(); - } - else if (s_nextSmallId < (unsigned int)MINECRAFT_NET_MAX_PLAYERS) - { - assignedSmallId = (BYTE)s_nextSmallId++; - } - else - { - LeaveCriticalSection(&s_freeSmallIdLock); -#if defined(MINECRAFT_SERVER_BUILD) - if (g_Win64DedicatedServer) - { - ServerRuntime::ServerLogManager::OnRejectedTcpConnection(remoteIpForLog, ServerRuntime::ServerLogManager::eTcpRejectReason_ServerFull); - } - else -#endif - { - app.DebugPrintf("Win64 LAN: Server full, rejecting connection\n"); - } - SendRejectWithReason(clientSocket, DisconnectPacket::eDisconnect_ServerFull); - closesocket(clientSocket); - continue; - } - LeaveCriticalSection(&s_freeSmallIdLock); - - BYTE assignBuf[1] = { assignedSmallId }; - int sent = send(clientSocket, (const char*)assignBuf, 1, 0); - if (sent != 1) - { - app.DebugPrintf("Failed to send small ID to client\n"); - closesocket(clientSocket); - PushFreeSmallId(assignedSmallId); - continue; - } - - Win64RemoteConnection conn; - conn.tcpSocket = clientSocket; - conn.smallId = assignedSmallId; - conn.active = true; - conn.recvThread = nullptr; - - EnterCriticalSection(&s_connectionsLock); - s_connections.push_back(conn); - int connIdx = static_cast(s_connections.size()) - 1; - LeaveCriticalSection(&s_connectionsLock); - -#if defined(MINECRAFT_SERVER_BUILD) - if (g_Win64DedicatedServer) - { - ServerRuntime::ServerLogManager::OnAcceptedTcpConnection(assignedSmallId, remoteIpForLog); - } - else -#endif - { - app.DebugPrintf("Win64 LAN: Client connected, assigned smallId=%d\n", assignedSmallId); - } - - EnterCriticalSection(&s_smallIdToSocketLock); - s_smallIdToSocket[assignedSmallId] = clientSocket; - LeaveCriticalSection(&s_smallIdToSocketLock); - - IQNetPlayer* qnetPlayer = &IQNet::m_player[assignedSmallId]; - - extern void Win64_SetupRemoteQNetPlayer(IQNetPlayer * player, BYTE smallId, bool isHost, bool isLocal); - Win64_SetupRemoteQNetPlayer(qnetPlayer, assignedSmallId, false, false); - - extern CPlatformNetworkManagerStub* g_pPlatformNetworkManager; - g_pPlatformNetworkManager->NotifyPlayerJoined(qnetPlayer); - - DWORD* threadParam = new DWORD; - *threadParam = connIdx; - HANDLE hThread = CreateThread(nullptr, 0, RecvThreadProc, threadParam, 0, nullptr); - - EnterCriticalSection(&s_connectionsLock); - if (connIdx < static_cast(s_connections.size())) - s_connections[connIdx].recvThread = hThread; - LeaveCriticalSection(&s_connectionsLock); - } - return 0; -} - -DWORD WINAPI WinsockNetLayer::RecvThreadProc(LPVOID param) -{ - DWORD connIdx = *static_cast(param); - delete static_cast(param); - - EnterCriticalSection(&s_connectionsLock); - if (connIdx >= static_cast(s_connections.size())) - { - LeaveCriticalSection(&s_connectionsLock); - return 0; - } - SOCKET sock = s_connections[connIdx].tcpSocket; - BYTE clientSmallId = s_connections[connIdx].smallId; - LeaveCriticalSection(&s_connectionsLock); - - std::vector recvBuf; - recvBuf.resize(WIN64_NET_RECV_BUFFER_SIZE); - - while (s_active) - { - BYTE header[4]; - if (!RecvExact(sock, header, 4)) - { - app.DebugPrintf("Win64 LAN: Client smallId=%d disconnected (header)\n", clientSmallId); - break; - } - - int packetSize = - (static_cast(header[0]) << 24) | - (static_cast(header[1]) << 16) | - (static_cast(header[2]) << 8) | - static_cast(header[3]); - - if (packetSize <= 0 || packetSize > WIN64_NET_MAX_PACKET_SIZE) - { - app.DebugPrintf("Win64 LAN: Invalid packet size %d from client smallId=%d (max=%d)\n", - packetSize, - clientSmallId, - (int)WIN64_NET_MAX_PACKET_SIZE); - break; - } - - if (static_cast(recvBuf.size()) < packetSize) - { - recvBuf.resize(packetSize); - app.DebugPrintf("Win64 LAN: Resized host recv buffer to %d bytes for client smallId=%d\n", packetSize, clientSmallId); - } - - if (!RecvExact(sock, &recvBuf[0], packetSize)) - { - app.DebugPrintf("Win64 LAN: Client smallId=%d disconnected (body)\n", clientSmallId); - break; - } - - HandleDataReceived(clientSmallId, s_hostSmallId, &recvBuf[0], packetSize); - } - - EnterCriticalSection(&s_connectionsLock); - for (size_t i = 0; i < s_connections.size(); i++) - { - if (s_connections[i].smallId == clientSmallId) - { - s_connections[i].active = false; - if (s_connections[i].tcpSocket != INVALID_SOCKET) - { - closesocket(s_connections[i].tcpSocket); - s_connections[i].tcpSocket = INVALID_SOCKET; - } - break; - } - } - LeaveCriticalSection(&s_connectionsLock); - - EnterCriticalSection(&s_disconnectLock); - s_disconnectedSmallIds.push_back(clientSmallId); - LeaveCriticalSection(&s_disconnectLock); - - return 0; -} - -bool WinsockNetLayer::PopDisconnectedSmallId(BYTE* outSmallId) -{ - bool found = false; - EnterCriticalSection(&s_disconnectLock); - if (!s_disconnectedSmallIds.empty()) - { - *outSmallId = s_disconnectedSmallIds.back(); - s_disconnectedSmallIds.pop_back(); - found = true; - } - LeaveCriticalSection(&s_disconnectLock); - return found; -} - -void WinsockNetLayer::PushFreeSmallId(BYTE smallId) -{ - - // SmallIds 0..(XUSER_MAX_COUNT-1) are permanently reserved for the host's - // local pads and must never be recycled to remote clients. - if (smallId < (BYTE)XUSER_MAX_COUNT) - return; - - EnterCriticalSection(&s_freeSmallIdLock); - // Guard against double-recycle: the reconnect path (queueSmallIdForRecycle) and - // the DoWork disconnect path can both push the same smallId. If we allow duplicates, - // AcceptThread will hand out the same smallId to two different connections. - bool alreadyFree = false; - for (size_t i = 0; i < s_freeSmallIds.size(); i++) - { - if (s_freeSmallIds[i] == smallId) { alreadyFree = true; break; } - } - if (!alreadyFree) - s_freeSmallIds.push_back(smallId); - LeaveCriticalSection(&s_freeSmallIdLock); -} - -void WinsockNetLayer::CloseConnectionBySmallId(BYTE smallId) -{ - EnterCriticalSection(&s_connectionsLock); - for (size_t i = 0; i < s_connections.size(); i++) - { - if (s_connections[i].smallId == smallId && s_connections[i].active && s_connections[i].tcpSocket != INVALID_SOCKET) - { - closesocket(s_connections[i].tcpSocket); - s_connections[i].tcpSocket = INVALID_SOCKET; - app.DebugPrintf("Win64 LAN: Force-closed TCP connection for smallId=%d\n", smallId); - break; - } - } - LeaveCriticalSection(&s_connectionsLock); -} - -BYTE WinsockNetLayer::GetSplitScreenSmallId(int padIndex) -{ - if (padIndex <= 0 || padIndex >= XUSER_MAX_COUNT) return 0xFF; - return s_splitScreenSmallId[padIndex]; -} - -SOCKET WinsockNetLayer::GetLocalSocket(BYTE senderSmallId) -{ - if (senderSmallId == s_localSmallId) - return s_hostConnectionSocket; - for (int i = 1; i < XUSER_MAX_COUNT; i++) - { - if (s_splitScreenSmallId[i] == senderSmallId && s_splitScreenSocket[i] != INVALID_SOCKET) - return s_splitScreenSocket[i]; - } - return INVALID_SOCKET; -} - -bool WinsockNetLayer::JoinSplitScreen(int padIndex, BYTE* outSmallId) -{ - if (!s_active || s_isHost || padIndex <= 0 || padIndex >= XUSER_MAX_COUNT) - return false; - - if (s_splitScreenSocket[padIndex] != INVALID_SOCKET) - { - return false; - } - - struct addrinfo hints = {}; - struct addrinfo* result = nullptr; - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - - char portStr[16]; - sprintf_s(portStr, "%d", g_Win64MultiplayerPort); - if (getaddrinfo(g_Win64MultiplayerIP, portStr, &hints, &result) != 0 || result == nullptr) - { - app.DebugPrintf("Win64 LAN: Split-screen getaddrinfo failed for %s:%d\n", g_Win64MultiplayerIP, g_Win64MultiplayerPort); - return false; - } - - SOCKET sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol); - if (sock == INVALID_SOCKET) - { - freeaddrinfo(result); - return false; - } - - int noDelay = 1; - setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char*)&noDelay, sizeof(noDelay)); - - if (connect(sock, result->ai_addr, (int)result->ai_addrlen) == SOCKET_ERROR) - { - app.DebugPrintf("Win64 LAN: Split-screen connect() failed: %d\n", WSAGetLastError()); - closesocket(sock); - freeaddrinfo(result); - return false; - } - freeaddrinfo(result); - - BYTE assignBuf[1]; - if (!RecvExact(sock, assignBuf, 1)) - { - app.DebugPrintf("Win64 LAN: Split-screen failed to receive smallId\n"); - closesocket(sock); - return false; - } - - if (assignBuf[0] == WIN64_SMALLID_REJECT) - { - BYTE rejectBuf[5]; - RecvExact(sock, rejectBuf, 5); - app.DebugPrintf("Win64 LAN: Split-screen connection rejected\n"); - closesocket(sock); - return false; - } - - BYTE assignedSmallId = assignBuf[0]; - s_splitScreenSocket[padIndex] = sock; - s_splitScreenSmallId[padIndex] = assignedSmallId; - *outSmallId = assignedSmallId; - - app.DebugPrintf("Win64 LAN: Split-screen pad %d connected, assigned smallId=%d\n", padIndex, assignedSmallId); - - int* threadParam = new int; - *threadParam = padIndex; - s_splitScreenRecvThread[padIndex] = CreateThread(nullptr, 0, SplitScreenRecvThreadProc, threadParam, 0, nullptr); - if (s_splitScreenRecvThread[padIndex] == nullptr) - { - delete threadParam; - closesocket(sock); - s_splitScreenSocket[padIndex] = INVALID_SOCKET; - s_splitScreenSmallId[padIndex] = 0xFF; - app.DebugPrintf("Win64 LAN: CreateThread failed for split-screen pad %d\n", padIndex); - return false; - } - - return true; -} - -void WinsockNetLayer::CloseSplitScreenConnection(int padIndex) -{ - if (padIndex <= 0 || padIndex >= XUSER_MAX_COUNT) return; - - if (s_splitScreenSocket[padIndex] != INVALID_SOCKET) - { - closesocket(s_splitScreenSocket[padIndex]); - s_splitScreenSocket[padIndex] = INVALID_SOCKET; - } - s_splitScreenSmallId[padIndex] = 0xFF; - if (s_splitScreenRecvThread[padIndex] != nullptr) - { - WaitForSingleObject(s_splitScreenRecvThread[padIndex], 2000); - CloseHandle(s_splitScreenRecvThread[padIndex]); - s_splitScreenRecvThread[padIndex] = nullptr; - } -} - -DWORD WINAPI WinsockNetLayer::SplitScreenRecvThreadProc(LPVOID param) -{ - int padIndex = *(int*)param; - delete (int*)param; - - SOCKET sock = s_splitScreenSocket[padIndex]; - BYTE localSmallId = s_splitScreenSmallId[padIndex]; - std::vector recvBuf; - recvBuf.resize(WIN64_NET_RECV_BUFFER_SIZE); - - while (s_active && s_splitScreenSocket[padIndex] != INVALID_SOCKET) - { - BYTE header[4]; - if (!RecvExact(sock, header, 4)) - { - app.DebugPrintf("Win64 LAN: Split-screen pad %d disconnected from host\n", padIndex); - break; - } - - int packetSize = ((uint32_t)header[0] << 24) | ((uint32_t)header[1] << 16) | - ((uint32_t)header[2] << 8) | ((uint32_t)header[3]); - if (packetSize <= 0 || packetSize > WIN64_NET_MAX_PACKET_SIZE) - { - app.DebugPrintf("Win64 LAN: Split-screen pad %d invalid packet size %d\n", padIndex, packetSize); - break; - } - - if ((int)recvBuf.size() < packetSize) - recvBuf.resize(packetSize); - - if (!RecvExact(sock, &recvBuf[0], packetSize)) - { - app.DebugPrintf("Win64 LAN: Split-screen pad %d disconnected from host (body)\n", padIndex); - break; - } - - HandleDataReceived(s_hostSmallId, localSmallId, &recvBuf[0], packetSize); - } - - EnterCriticalSection(&s_disconnectLock); - s_disconnectedSmallIds.push_back(localSmallId); - LeaveCriticalSection(&s_disconnectLock); - - return 0; -} - -DWORD WINAPI WinsockNetLayer::ClientRecvThreadProc(LPVOID param) -{ - std::vector recvBuf; - recvBuf.resize(WIN64_NET_RECV_BUFFER_SIZE); - - while (s_active && s_hostConnectionSocket != INVALID_SOCKET) - { - BYTE header[4]; - if (!RecvExact(s_hostConnectionSocket, header, 4)) - { - app.DebugPrintf("Win64 LAN: Disconnected from host (header)\n"); - break; - } - - int packetSize = (header[0] << 24) | (header[1] << 16) | (header[2] << 8) | header[3]; - - if (packetSize <= 0 || packetSize > WIN64_NET_MAX_PACKET_SIZE) - { - app.DebugPrintf("Win64 LAN: Invalid packet size %d from host (max=%d)\n", - packetSize, - (int)WIN64_NET_MAX_PACKET_SIZE); - break; - } - - if (static_cast(recvBuf.size()) < packetSize) - { - recvBuf.resize(packetSize); - app.DebugPrintf("Win64 LAN: Resized client recv buffer to %d bytes\n", packetSize); - } - - if (!RecvExact(s_hostConnectionSocket, &recvBuf[0], packetSize)) - { - app.DebugPrintf("Win64 LAN: Disconnected from host (body)\n"); - break; - } - - HandleDataReceived(s_hostSmallId, s_localSmallId, &recvBuf[0], packetSize); - } - - s_connected = false; - return 0; -} - -bool WinsockNetLayer::StartAdvertising(int gamePort, const wchar_t* hostName, unsigned int gameSettings, unsigned int texPackId, unsigned char subTexId, unsigned short netVer) -{ - if (s_advertising) return true; - if (!s_initialized) return false; - - EnterCriticalSection(&s_advertiseLock); - memset(&s_advertiseData, 0, sizeof(s_advertiseData)); - s_advertiseData.magic = WIN64_LAN_BROADCAST_MAGIC; - s_advertiseData.netVersion = netVer; - s_advertiseData.gamePort = static_cast(gamePort); - wcsncpy_s(s_advertiseData.hostName, 32, hostName, _TRUNCATE); - s_advertiseData.playerCount = 1; - s_advertiseData.maxPlayers = MINECRAFT_NET_MAX_PLAYERS; - s_advertiseData.gameHostSettings = gameSettings; - s_advertiseData.texturePackParentId = texPackId; - s_advertiseData.subTexturePackId = subTexId; - s_advertiseData.isJoinable = 0; - s_hostGamePort = gamePort; - LeaveCriticalSection(&s_advertiseLock); - - s_advertiseSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (s_advertiseSock == INVALID_SOCKET) - { - app.DebugPrintf("Win64 LAN: Failed to create advertise socket: %d\n", WSAGetLastError()); - return false; - } - - BOOL broadcast = TRUE; - setsockopt(s_advertiseSock, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)); - - s_advertising = true; - s_advertiseThread = CreateThread(nullptr, 0, AdvertiseThreadProc, nullptr, 0, nullptr); - - app.DebugPrintf("Win64 LAN: Started advertising on UDP port %d\n", WIN64_LAN_DISCOVERY_PORT); - return true; -} - -void WinsockNetLayer::StopAdvertising() -{ - s_advertising = false; - - if (s_advertiseSock != INVALID_SOCKET) - { - closesocket(s_advertiseSock); - s_advertiseSock = INVALID_SOCKET; - } - - if (s_advertiseThread != nullptr) - { - WaitForSingleObject(s_advertiseThread, 2000); - CloseHandle(s_advertiseThread); - s_advertiseThread = nullptr; - } -} - -void WinsockNetLayer::UpdateAdvertisePlayerCount(BYTE count) -{ - EnterCriticalSection(&s_advertiseLock); - s_advertiseData.playerCount = count; - LeaveCriticalSection(&s_advertiseLock); -} - -void WinsockNetLayer::UpdateAdvertiseMaxPlayers(BYTE maxPlayers) -{ - EnterCriticalSection(&s_advertiseLock); - s_advertiseData.maxPlayers = maxPlayers; - LeaveCriticalSection(&s_advertiseLock); -} - -void WinsockNetLayer::UpdateAdvertiseJoinable(bool joinable) -{ - EnterCriticalSection(&s_advertiseLock); - s_advertiseData.isJoinable = joinable ? 1 : 0; - LeaveCriticalSection(&s_advertiseLock); -} - -DWORD WINAPI WinsockNetLayer::AdvertiseThreadProc(LPVOID param) -{ - struct sockaddr_in broadcastAddr; - memset(&broadcastAddr, 0, sizeof(broadcastAddr)); - broadcastAddr.sin_family = AF_INET; - broadcastAddr.sin_port = htons(WIN64_LAN_DISCOVERY_PORT); - broadcastAddr.sin_addr.s_addr = INADDR_BROADCAST; - - while (s_advertising) - { - EnterCriticalSection(&s_advertiseLock); - Win64LANBroadcast data = s_advertiseData; - LeaveCriticalSection(&s_advertiseLock); - - int sent = sendto(s_advertiseSock, (const char*)&data, sizeof(data), 0, - (struct sockaddr*)&broadcastAddr, sizeof(broadcastAddr)); - - if (sent == SOCKET_ERROR && s_advertising) - { - app.DebugPrintf("Win64 LAN: Broadcast sendto failed: %d\n", WSAGetLastError()); - } - - Sleep(1000); - } - - return 0; -} - -bool WinsockNetLayer::StartDiscovery() -{ - if (s_discovering) return true; - if (!s_initialized) return false; - - s_discoverySock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (s_discoverySock == INVALID_SOCKET) - { - app.DebugPrintf("Win64 LAN: Failed to create discovery socket: %d\n", WSAGetLastError()); - return false; - } - - BOOL reuseAddr = TRUE; - setsockopt(s_discoverySock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuseAddr, sizeof(reuseAddr)); - - struct sockaddr_in bindAddr; - memset(&bindAddr, 0, sizeof(bindAddr)); - bindAddr.sin_family = AF_INET; - bindAddr.sin_port = htons(WIN64_LAN_DISCOVERY_PORT); - bindAddr.sin_addr.s_addr = INADDR_ANY; - - if (::bind(s_discoverySock, (struct sockaddr*)&bindAddr, sizeof(bindAddr)) == SOCKET_ERROR) - { - app.DebugPrintf("Win64 LAN: Discovery bind failed: %d\n", WSAGetLastError()); - closesocket(s_discoverySock); - s_discoverySock = INVALID_SOCKET; - return false; - } - - DWORD timeout = 500; - setsockopt(s_discoverySock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); - - s_discovering = true; - s_discoveryThread = CreateThread(nullptr, 0, DiscoveryThreadProc, nullptr, 0, nullptr); - - app.DebugPrintf("Win64 LAN: Listening for LAN games on UDP port %d\n", WIN64_LAN_DISCOVERY_PORT); - return true; -} - -void WinsockNetLayer::StopDiscovery() -{ - s_discovering = false; - - if (s_discoverySock != INVALID_SOCKET) - { - closesocket(s_discoverySock); - s_discoverySock = INVALID_SOCKET; - } - - if (s_discoveryThread != nullptr) - { - WaitForSingleObject(s_discoveryThread, 2000); - CloseHandle(s_discoveryThread); - s_discoveryThread = nullptr; - } - - EnterCriticalSection(&s_discoveryLock); - s_discoveredSessions.clear(); - LeaveCriticalSection(&s_discoveryLock); -} - -std::vector WinsockNetLayer::GetDiscoveredSessions() -{ - std::vector result; - EnterCriticalSection(&s_discoveryLock); - result = s_discoveredSessions; - LeaveCriticalSection(&s_discoveryLock); - return result; -} - -DWORD WINAPI WinsockNetLayer::DiscoveryThreadProc(LPVOID param) -{ - char recvBuf[512]; - - while (s_discovering) - { - struct sockaddr_in senderAddr; - int senderLen = sizeof(senderAddr); - - int recvLen = recvfrom(s_discoverySock, recvBuf, sizeof(recvBuf), 0, - (struct sockaddr*)&senderAddr, &senderLen); - - if (recvLen == SOCKET_ERROR) - { - continue; - } - - if (recvLen < static_cast(sizeof(Win64LANBroadcast))) - continue; - - Win64LANBroadcast* broadcast = (Win64LANBroadcast*)recvBuf; - if (broadcast->magic != WIN64_LAN_BROADCAST_MAGIC) - continue; - - char senderIP[64]; - inet_ntop(AF_INET, &senderAddr.sin_addr, senderIP, sizeof(senderIP)); - - DWORD now = GetTickCount(); - - EnterCriticalSection(&s_discoveryLock); - - bool found = false; - for (size_t i = 0; i < s_discoveredSessions.size(); i++) - { - if (strcmp(s_discoveredSessions[i].hostIP, senderIP) == 0 && - s_discoveredSessions[i].hostPort == static_cast(broadcast->gamePort)) - { - s_discoveredSessions[i].netVersion = broadcast->netVersion; - wcsncpy_s(s_discoveredSessions[i].hostName, 32, broadcast->hostName, _TRUNCATE); - s_discoveredSessions[i].playerCount = broadcast->playerCount; - s_discoveredSessions[i].maxPlayers = broadcast->maxPlayers; - s_discoveredSessions[i].gameHostSettings = broadcast->gameHostSettings; - s_discoveredSessions[i].texturePackParentId = broadcast->texturePackParentId; - s_discoveredSessions[i].subTexturePackId = broadcast->subTexturePackId; - s_discoveredSessions[i].isJoinable = (broadcast->isJoinable != 0); - s_discoveredSessions[i].lastSeenTick = now; - found = true; - break; - } - } - - if (!found) - { - Win64LANSession session; - memset(&session, 0, sizeof(session)); - strncpy_s(session.hostIP, sizeof(session.hostIP), senderIP, _TRUNCATE); - session.hostPort = static_cast(broadcast->gamePort); - session.netVersion = broadcast->netVersion; - wcsncpy_s(session.hostName, 32, broadcast->hostName, _TRUNCATE); - session.playerCount = broadcast->playerCount; - session.maxPlayers = broadcast->maxPlayers; - session.gameHostSettings = broadcast->gameHostSettings; - session.texturePackParentId = broadcast->texturePackParentId; - session.subTexturePackId = broadcast->subTexturePackId; - session.isJoinable = (broadcast->isJoinable != 0); - session.lastSeenTick = now; - s_discoveredSessions.push_back(session); - - app.DebugPrintf("Win64 LAN: Discovered game \"%ls\" at %s:%d\n", - session.hostName, session.hostIP, session.hostPort); - } - - for (size_t i = s_discoveredSessions.size(); i > 0; i--) - { - if (now - s_discoveredSessions[i - 1].lastSeenTick > 5000) - { - app.DebugPrintf("Win64 LAN: Session \"%ls\" at %s timed out\n", - s_discoveredSessions[i - 1].hostName, s_discoveredSessions[i - 1].hostIP); - s_discoveredSessions.erase(s_discoveredSessions.begin() + (i - 1)); - } - } - - LeaveCriticalSection(&s_discoveryLock); - } - - return 0; -} - -#endif diff --git a/Minecraft.Client/Windows64/Network/WinsockNetLayer.h b/Minecraft.Client/Windows64/Network/WinsockNetLayer.h deleted file mode 100644 index 34cc7389..00000000 --- a/Minecraft.Client/Windows64/Network/WinsockNetLayer.h +++ /dev/null @@ -1,207 +0,0 @@ -// Code implemented by LCEMP, credit if used on other repos -// https://github.com/LCEMP/LCEMP -#pragma once - -#ifdef _WINDOWS64 - -#include -#include -#include -#include "../../Common/Network/NetworkPlayerInterface.h" -#include "../../..\Minecraft.World\DisconnectPacket.h" - -#pragma comment(lib, "Ws2_32.lib") - -#define WIN64_NET_DEFAULT_PORT 25565 -#define WIN64_NET_MAX_CLIENTS 255 -#define WIN64_SMALLID_REJECT 0xFF -#define WIN64_NET_RECV_BUFFER_SIZE 65536 -#define WIN64_NET_MAX_PACKET_SIZE (4 * 1024 * 1024) -#define WIN64_LAN_DISCOVERY_PORT 25566 -#define WIN64_LAN_BROADCAST_MAGIC 0x4D434C4E - -class Socket; - -#pragma pack(push, 1) -struct Win64LANBroadcast -{ - DWORD magic; - WORD netVersion; - WORD gamePort; - wchar_t hostName[32]; - BYTE playerCount; - BYTE maxPlayers; - DWORD gameHostSettings; - DWORD texturePackParentId; - BYTE subTexturePackId; - BYTE isJoinable; -}; -#pragma pack(pop) - -struct Win64LANSession -{ - char hostIP[64]; - int hostPort; - wchar_t hostName[32]; - unsigned short netVersion; - unsigned char playerCount; - unsigned char maxPlayers; - unsigned int gameHostSettings; - unsigned int texturePackParentId; - unsigned char subTexturePackId; - bool isJoinable; - DWORD lastSeenTick; -}; - -struct Win64RemoteConnection -{ - SOCKET tcpSocket; - BYTE smallId; - HANDLE recvThread; - volatile bool active; -}; - -class WinsockNetLayer -{ -public: - static bool Initialize(); - static void Shutdown(); - - static bool HostGame(int port, const char* bindIp = nullptr); - static bool JoinGame(const char* ip, int port); - - // Async join: runs connection on a background thread so the UI stays responsive - enum eJoinState - { - eJoinState_Idle, - eJoinState_Connecting, - eJoinState_Success, - eJoinState_Failed, - eJoinState_Rejected, - eJoinState_Cancelled - }; - static bool BeginJoinGame(const char* ip, int port); - static void CancelJoinGame(); - static bool FinalizeJoin(); - static eJoinState GetJoinState(); - static int GetJoinAttempt(); - static int GetJoinMaxAttempts(); - static DisconnectPacket::eDisconnectReason GetJoinRejectReason(); - - static bool SendToSmallId(BYTE targetSmallId, const void* data, int dataSize); - static bool SendOnSocket(BYTE targetSmallId, SOCKET sock, const void* data, int dataSize); - - // Non-host split-screen: additional TCP connections to host, one per pad - static bool JoinSplitScreen(int padIndex, BYTE* outSmallId); - static void CloseSplitScreenConnection(int padIndex); - static SOCKET GetLocalSocket(BYTE senderSmallId); - static BYTE GetSplitScreenSmallId(int padIndex); - - static bool IsHosting() { return s_isHost; } - static bool IsConnected() { return s_connected; } - static bool IsActive() { return s_active; } - - static BYTE GetLocalSmallId() { return s_localSmallId; } - static BYTE GetHostSmallId() { return s_hostSmallId; } - - static SOCKET GetSocketForSmallId(BYTE smallId); - - static void HandleDataReceived(BYTE fromSmallId, BYTE toSmallId, unsigned char* data, unsigned int dataSize); - - static bool PopDisconnectedSmallId(BYTE* outSmallId); - static void PushFreeSmallId(BYTE smallId); - static void CloseConnectionBySmallId(BYTE smallId); - - static bool StartAdvertising(int gamePort, const wchar_t* hostName, unsigned int gameSettings, unsigned int texPackId, unsigned char subTexId, unsigned short netVer); - static void StopAdvertising(); - static void UpdateAdvertisePlayerCount(BYTE count); - static void UpdateAdvertiseMaxPlayers(BYTE maxPlayers); - static void UpdateAdvertiseJoinable(bool joinable); - - static bool StartDiscovery(); - static void StopDiscovery(); - static std::vector GetDiscoveredSessions(); - - static int GetHostPort() { return s_hostGamePort; } - -private: - static DWORD WINAPI AcceptThreadProc(LPVOID param); - static DWORD WINAPI RecvThreadProc(LPVOID param); - static DWORD WINAPI ClientRecvThreadProc(LPVOID param); - static DWORD WINAPI SplitScreenRecvThreadProc(LPVOID param); - static DWORD WINAPI AdvertiseThreadProc(LPVOID param); - static DWORD WINAPI DiscoveryThreadProc(LPVOID param); - static DWORD WINAPI JoinThreadProc(LPVOID param); - - static SOCKET s_listenSocket; - static SOCKET s_hostConnectionSocket; - static HANDLE s_acceptThread; - static HANDLE s_clientRecvThread; - - static bool s_isHost; - static bool s_connected; - static bool s_active; - static bool s_initialized; - - static BYTE s_localSmallId; - static BYTE s_hostSmallId; - static unsigned int s_nextSmallId; - - static CRITICAL_SECTION s_sendLock[MINECRAFT_NET_MAX_PLAYERS]; - static CRITICAL_SECTION s_connectionsLock; - - static std::vector s_connections; - - static SOCKET s_advertiseSock; - static HANDLE s_advertiseThread; - static volatile bool s_advertising; - static Win64LANBroadcast s_advertiseData; - static CRITICAL_SECTION s_advertiseLock; - static int s_hostGamePort; - - static SOCKET s_discoverySock; - static HANDLE s_discoveryThread; - static volatile bool s_discovering; - static CRITICAL_SECTION s_discoveryLock; - static std::vector s_discoveredSessions; - - static CRITICAL_SECTION s_disconnectLock; - static std::vector s_disconnectedSmallIds; - - static CRITICAL_SECTION s_freeSmallIdLock; - static std::vector s_freeSmallIds; - // O(1) smallId -> socket lookup so we don't scan s_connections (which never shrinks) on every send - static SOCKET s_smallIdToSocket[256]; - static CRITICAL_SECTION s_smallIdToSocketLock; - - // Async join state - static const int JOIN_MAX_ATTEMPTS = 3; - static HANDLE s_joinThread; - static volatile eJoinState s_joinState; - static volatile int s_joinAttempt; - static volatile bool s_joinCancel; - static char s_joinIP[256]; - static int s_joinPort; - static BYTE s_joinAssignedSmallId; - static DisconnectPacket::eDisconnectReason s_joinRejectReason; - - // Per-pad split-screen TCP connections (client-side, non-host only) - static SOCKET s_splitScreenSocket[XUSER_MAX_COUNT]; - static BYTE s_splitScreenSmallId[XUSER_MAX_COUNT]; - static HANDLE s_splitScreenRecvThread[XUSER_MAX_COUNT]; - -public: - static void ClearSocketForSmallId(BYTE smallId); -}; - -extern bool g_Win64MultiplayerHost; -extern bool g_Win64MultiplayerJoin; -extern bool g_Win64MultiplayerQuitOnDisconnect; -extern int g_Win64MultiplayerPort; -extern char g_Win64MultiplayerIP[256]; -extern bool g_Win64DedicatedServer; -extern int g_Win64DedicatedServerPort; -extern char g_Win64DedicatedServerBindIP[256]; -extern bool g_Win64DedicatedServerLanAdvertise; - -#endif diff --git a/Minecraft.Client/Windows64/Windows64_Minecraft.cpp b/Minecraft.Client/Windows64/Windows64_Minecraft.cpp index 942b7de2..38e970d1 100644 --- a/Minecraft.Client/Windows64/Windows64_Minecraft.cpp +++ b/Minecraft.Client/Windows64/Windows64_Minecraft.cpp @@ -28,6 +28,7 @@ #include "../ChatScreen.h" #include "KeyboardMouseInput.h" #include "ControllerBinds.h" +#include "../Common/Network/ExternalServerList.h" #include "../User.h" #include "../../Minecraft.World/Socket.h" #include "../../Minecraft.World/ThreadName.h" @@ -49,7 +50,7 @@ #include "../../Minecraft.World/OldChunkStorage.h" #include "Common/PostProcesser.h" #include "../GameRenderer.h" -#include "Network/WinsockNetLayer.h" +#include "Network/WindowsNetworkConfig.h" #include "Windows64_Xuid.h" #include "Common/UI/UI.h" #include "stb_image_write.h" @@ -1567,8 +1568,6 @@ static Minecraft* InitialiseMinecraftRuntime() } wcscpy_s(IQNet::m_player[0].m_gamertag, 32, g_Win64UsernameW); - WinsockNetLayer::Initialize(); - ProfileManager.SetDebugFullOverride(true); Tesselator::CreateNewThreadStorage(1024 * 1024); @@ -1735,26 +1734,11 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, if (!migEntries.empty()) { - FILE* dbFile = nullptr; - if (fopen_s(&dbFile, "servers.db", "wb") == 0 && dbFile) - { - fwrite("MCSV", 1, 4, dbFile); - uint32_t ver = 1; - uint32_t cnt = (uint32_t)migEntries.size(); - fwrite(&ver, sizeof(uint32_t), 1, dbFile); - fwrite(&cnt, sizeof(uint32_t), 1, dbFile); - for (size_t i = 0; i < migEntries.size(); i++) - { - uint16_t ipLen = (uint16_t)migEntries[i].ip.length(); - fwrite(&ipLen, sizeof(uint16_t), 1, dbFile); - fwrite(migEntries[i].ip.c_str(), 1, ipLen, dbFile); - fwrite(&migEntries[i].port, sizeof(uint16_t), 1, dbFile); - uint16_t nameLen = (uint16_t)migEntries[i].name.length(); - fwrite(&nameLen, sizeof(uint16_t), 1, dbFile); - fwrite(migEntries[i].name.c_str(), 1, nameLen, dbFile); - } - fclose(dbFile); - } + std::vector entries; + for (const MigEntry& entry : migEntries) + entries.push_back({ entry.ip, entry.port, entry.name }); + if (!ExternalServerList::Write(entries)) + app.DebugPrintf("Failed to migrate the existing external server list."); } } } diff --git a/Minecraft.Client/cmake/sources/Common.cmake b/Minecraft.Client/cmake/sources/Common.cmake index 32f8ca0f..302e8bc3 100644 --- a/Minecraft.Client/cmake/sources/Common.cmake +++ b/Minecraft.Client/cmake/sources/Common.cmake @@ -422,8 +422,11 @@ set(_MINECRAFT_CLIENT_COMMON_WINDOWS64_IGGY_GDRAW source_group("Windows64/Iggy/gdraw" FILES ${_MINECRAFT_CLIENT_COMMON_WINDOWS64_IGGY_GDRAW}) set(_MINECRAFT_CLIENT_COMMON_WINDOWS64_NETWORK - "${CMAKE_CURRENT_SOURCE_DIR}/Windows64/Network/WinsockNetLayer.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/Windows64/Network/WinsockNetLayer.h" + "${CMAKE_CURRENT_SOURCE_DIR}/Windows64/Network/WindowsNetworkConfig.h" + "${CMAKE_CURRENT_SOURCE_DIR}/Windows64/Network/PlatformNetworkManagerWindows.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Windows64/Network/PlatformNetworkManagerWindows.h" + "${CMAKE_CURRENT_SOURCE_DIR}/Windows64/Network/NetworkPlayerWindows.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Windows64/Network/NetworkPlayerWindows.h" ) source_group("Windows64/Network" FILES ${_MINECRAFT_CLIENT_COMMON_WINDOWS64_NETWORK}) diff --git a/Minecraft.Client/cmake/sources/Windows.cmake b/Minecraft.Client/cmake/sources/Windows.cmake index f0411bb0..e4d1155e 100644 --- a/Minecraft.Client/cmake/sources/Windows.cmake +++ b/Minecraft.Client/cmake/sources/Windows.cmake @@ -12,12 +12,6 @@ set(_MINECRAFT_CLIENT_WINDOWS_COMMON_AUDIO ) source_group("Common/Audio" FILES ${_MINECRAFT_CLIENT_WINDOWS_COMMON_AUDIO}) -set(_MINECRAFT_CLIENT_WINDOWS_COMMON_NETWORK - "${CMAKE_CURRENT_SOURCE_DIR}/Common/Network/PlatformNetworkManagerStub.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/Common/Network/PlatformNetworkManagerStub.h" -) -source_group("Common/Network" FILES ${_MINECRAFT_CLIENT_WINDOWS_COMMON_NETWORK}) - set(_MINECRAFT_CLIENT_WINDOWS_COMMON_UI "${CMAKE_CURRENT_SOURCE_DIR}/Common/UI/UI.h" "${CMAKE_CURRENT_SOURCE_DIR}/Common/UI/UIBitmapFont.cpp" diff --git a/Minecraft.Server/FourKitNatives.cpp b/Minecraft.Server/FourKitNatives.cpp index 57993fec..cc8255f4 100644 --- a/Minecraft.Server/FourKitNatives.cpp +++ b/Minecraft.Server/FourKitNatives.cpp @@ -8,6 +8,8 @@ #include #include "../Minecraft.Client/MinecraftServer.h" +#include "../Minecraft.Client/Common/Network/GameNetworkManager.h" +#include "../Minecraft.Client/Windows64/Network/NetworkPlayerWindows.h" #include "../Minecraft.Client/PlayerConnection.h" #include "../Minecraft.Client/PlayerList.h" #include "../Minecraft.Client/ServerConnection.h" @@ -18,7 +20,6 @@ #include "../Minecraft.World/LevelChunk.h" #include "../Minecraft.World/Biome.h" #include "../Minecraft.World/LightLayer.h" -#include "../Minecraft.Client/Windows64/Network/WinsockNetLayer.h" #include "../Minecraft.World/AbstractContainerMenu.h" #include "../Minecraft.World/AddGlobalEntityPacket.h" #include "../Minecraft.World/ArrayWithLength.h" @@ -596,7 +597,8 @@ int __cdecl NativeGetPlayerAddress(int entityId, char *outIpBuf, int outIpBufSiz std::string playerIp; if (!ServerRuntime::ServerLogManager::TryGetConnectionRemoteIp(smallId, &playerIp)) { - SOCKET sock = WinsockNetLayer::GetSocketForSmallId(smallId); + NetworkPlayerWindows* nativePlayer = dynamic_cast(g_NetworkManager.GetPlayerBySmallId(smallId)); + SOCKET sock = nativePlayer != nullptr ? nativePlayer->GetTransportSocket() : INVALID_SOCKET; if (sock != INVALID_SOCKET) { sockaddr_in addr; @@ -617,7 +619,8 @@ int __cdecl NativeGetPlayerAddress(int entityId, char *outIpBuf, int outIpBufSiz } else { - SOCKET sock = WinsockNetLayer::GetSocketForSmallId(smallId); + NetworkPlayerWindows* nativePlayer = dynamic_cast(g_NetworkManager.GetPlayerBySmallId(smallId)); + SOCKET sock = nativePlayer != nullptr ? nativePlayer->GetTransportSocket() : INVALID_SOCKET; if (sock != INVALID_SOCKET && outPort) { sockaddr_in addr; diff --git a/Minecraft.Server/Windows64/ServerMain.cpp b/Minecraft.Server/Windows64/ServerMain.cpp index 8fa6e83a..3102864d 100644 --- a/Minecraft.Server/Windows64/ServerMain.cpp +++ b/Minecraft.Server/Windows64/ServerMain.cpp @@ -2,6 +2,7 @@ #include "Common/App_Defines.h" #include "Common/Network/GameNetworkManager.h" +#include "Windows64/Network/WindowsNetworkConfig.h" #include "Input.h" #include "Minecraft.h" #include "MinecraftServer.h" @@ -20,7 +21,6 @@ #include "Windows64/4JLibs/inc/4J_Render.h" #include "Windows64/GameConfig/Minecraft.spa.h" #include "Windows64/KeyboardMouseInput.h" -#include "Windows64/Network/WinsockNetLayer.h" #include "Windows64/Windows64_UIController.h" #include "Common/UI/UI.h" @@ -501,7 +501,6 @@ int main(int argc, char **argv) swprintf_s(IQNet::m_player[i].m_gamertag, 32, L"Player%d", i); } wcscpy_s(IQNet::m_player[0].m_gamertag, 32, g_Win64UsernameW); - WinsockNetLayer::Initialize(); Tesselator::CreateNewThreadStorage(1024 * 1024); AABB::CreateNewThreadStorage(); @@ -604,7 +603,6 @@ int main(int argc, char **argv) else if (worldBootstrap.status == eWorldBootstrap_Failed) { LogErrorf("world-io", "Failed to load configured world \"%s\".", WideToUtf8(targetWorldName).c_str()); - WinsockNetLayer::Shutdown(); g_NetworkManager.Terminate(); CleanupDevice(); @@ -640,7 +638,7 @@ int main(int argc, char **argv) LogStartupStep("starting hosted network game thread"); g_NetworkManager.HostGame(0, true, false, (unsigned char)config.maxPlayers, 0); - g_NetworkManager.FakeLocalPlayerJoined(); + g_NetworkManager.FakeLocalPlayerJoined(true); C4JThread *startThread = new C4JThread(&CGameNetworkManager::RunNetworkGameThreadProc, (LPVOID)param, "RunNetworkGame"); startThread->Run(); @@ -658,7 +656,6 @@ int main(int argc, char **argv) if (startupResult != 0) { LogErrorf("startup", "Failed to start dedicated server (code %d).", startupResult); - WinsockNetLayer::Shutdown(); g_NetworkManager.Terminate(); CleanupDevice(); @@ -787,8 +784,6 @@ int main(int argc, char **argv) } LogInfof("shutdown", "Cleaning up and exiting."); - WinsockNetLayer::Shutdown(); - LogDebugf("shutdown", "Network layer shutdown complete."); g_NetworkManager.Terminate(); LogDebugf("shutdown", "Network manager terminated."); ServerRuntime::ServerLogManager::Shutdown(); diff --git a/Minecraft.Server/cmake/sources/Common.cmake b/Minecraft.Server/cmake/sources/Common.cmake index 39238f16..49d8c0aa 100644 --- a/Minecraft.Server/cmake/sources/Common.cmake +++ b/Minecraft.Server/cmake/sources/Common.cmake @@ -87,7 +87,6 @@ set(_MINECRAFT_SERVER_COMMON_ROOT "${_MS_SRC}/../Minecraft.Client/Common/Leaderboards/LeaderboardInterface.cpp" "${_MS_SRC}/../Minecraft.Client/Common/Leaderboards/LeaderboardManager.cpp" "${_MS_SRC}/../Minecraft.Client/Common/Network/GameNetworkManager.cpp" - "${_MS_SRC}/../Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp" "${_MS_SRC}/../Minecraft.Client/Common/Telemetry/TelemetryManager.cpp" "${_MS_SRC}/../Minecraft.Client/Common/Trial/TrialMode.cpp" "${_MS_SRC}/../Minecraft.Client/Common/Tutorial/AreaConstraint.cpp" @@ -129,6 +128,7 @@ set(_MINECRAFT_SERVER_COMMON_ROOT "${_MS_SRC}/../Minecraft.Client/Common/UI/IUIScene_CommandBlockMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/IUIScene_ContainerMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/IUIScene_CraftingMenu.cpp" + "${_MS_SRC}/../Minecraft.Client/Common/UI/IUIScene_CraftingMenuTabs.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/IUIScene_CreativeMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/IUIScene_DispenserMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/IUIScene_EnchantingMenu.cpp" @@ -179,6 +179,7 @@ set(_MINECRAFT_SERVER_COMMON_ROOT "${_MS_SRC}/../Minecraft.Client/Common/UI/UIControl_SaveList.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIControl_Slider.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIControl_SlotList.cpp" + "${_MS_SRC}/../Minecraft.Client/Common/UI/UIControl_SuperflatLists.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIControl_SpaceIndicatorBar.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIControl_TextInput.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIControl_TexturePackList.cpp" @@ -196,10 +197,12 @@ set(_MINECRAFT_SERVER_COMMON_ROOT "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_ControlsMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_CraftingMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_CreateWorldMenu.cpp" + "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_BindingsTypeMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_CreativeMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_Credits.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_DLCMainMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_DLCOffersMenu.cpp" + "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_EditServerMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_DeathMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_DebugCreateSchematic.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_DebugOptions.cpp" @@ -225,6 +228,7 @@ set(_MINECRAFT_SERVER_COMMON_ROOT "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_InventoryMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_JoinMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_Keyboard.cpp" + "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_KeybindsMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_LanguageSelector.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_LaunchMoreOptionsMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_LeaderboardsMenu.cpp" @@ -246,6 +250,9 @@ set(_MINECRAFT_SERVER_COMMON_ROOT "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_SettingsUIMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_SignEntryMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_SkinSelectMenu.cpp" + "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_SuperflatEditLayerMenu.cpp" + "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_SuperflatMenu.cpp" + "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_SuperflatPresetsMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_TeleportMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_Timer.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_TradingMenu.cpp" @@ -260,6 +267,8 @@ set(_MINECRAFT_SERVER_COMMON_ROOT "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_ClassicCraftingMenu.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIScene_ClassicCraftingMenu.h" "${_MS_SRC}/../Minecraft.Client/Common/UI/UIString.cpp" + "${_MS_SRC}/../Minecraft.Client/Common/UI/UICustomStrings.cpp" + "${_MS_SRC}/../Minecraft.Client/Common/UI/SuperflatData.cpp" "${_MS_SRC}/../Minecraft.Client/Common/UI/UITTFFont.cpp" "${_MS_SRC}/../Minecraft.Client/Common/zlib/adler32.c" "${_MS_SRC}/../Minecraft.Client/Common/zlib/compress.c" @@ -306,6 +315,7 @@ set(_MINECRAFT_SERVER_COMMON_ROOT "${_MS_SRC}/../Minecraft.Client/EditBox.cpp" "${_MS_SRC}/../Minecraft.Client/EnchantTableRenderer.cpp" "${_MS_SRC}/../Minecraft.Client/EnderChestRenderer.cpp" + "${_MS_SRC}/../Minecraft.Client/ShulkerBoxRenderer.cpp" "${_MS_SRC}/../Minecraft.Client/EnderCrystalModel.cpp" "${_MS_SRC}/../Minecraft.Client/EnderCrystalRenderer.cpp" "${_MS_SRC}/../Minecraft.Client/EnderDragonRenderer.cpp" @@ -516,8 +526,11 @@ set(_MINECRAFT_SERVER_COMMON_ROOT "${_MS_SRC}/../Minecraft.Client/WaterDropParticle.cpp" "${_MS_SRC}/../Minecraft.Client/Windows64/Iggy/gdraw/gdraw_d3d11.cpp" "${_MS_SRC}/../Minecraft.Client/Windows64/KeyboardMouseInput.cpp" + "${_MS_SRC}/../Minecraft.Client/Windows64/ControllerBinds.cpp" "${_MS_SRC}/../Minecraft.Client/Windows64/Leaderboards/WindowsLeaderboardManager.cpp" - "${_MS_SRC}/../Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp" + "${_MS_SRC}/../Minecraft.Client/Windows64/Network/PlatformNetworkManagerWindows.cpp" + "${_MS_SRC}/../Minecraft.Client/Windows64/Network/NetworkPlayerWindows.cpp" + "${_MS_SRC}/../Minecraft.Client/Windows64/Network/WindowsNetworkConfig.h" "${_MS_SRC}/../Minecraft.Client/Windows64/PostProcesser.cpp" "${_MS_SRC}/../Minecraft.Client/DynamicLighting.cpp" "${_MS_SRC}/../Minecraft.Client/Windows64/Windows64_App.cpp" diff --git a/Minecraft.World/ByteBuffer.cpp b/Minecraft.World/ByteBuffer.cpp index 57b30dbd..12229b15 100644 --- a/Minecraft.World/ByteBuffer.cpp +++ b/Minecraft.World/ByteBuffer.cpp @@ -9,7 +9,7 @@ ByteBuffer::ByteBuffer( unsigned int capacity ) : Buffer( capacity ) hasBackingArray = false; buffer = new byte[capacity]; memset( buffer,0,sizeof(byte)*capacity); - byteOrder = BIGENDIAN; + byteOrder = BYTE_ORDER_BIG_ENDIAN; } //Allocates a new direct byte buffer. @@ -66,7 +66,7 @@ ByteBuffer *ByteBuffer::allocate(unsigned int capacity) //Modifies this buffer's byte order. //Parameters: -//bo - The new byte order, either BIGENDIAN or LITTLEENDIAN +//bo - The new byte order, either BYTE_ORDER_BIG_ENDIAN or BYTE_ORDER_LITTLE_ENDIAN void ByteBuffer::order(ByteOrder bo) { byteOrder = bo; @@ -131,11 +131,11 @@ int ByteBuffer::getInt() m_position += 4; - if( byteOrder == BIGENDIAN ) + if( byteOrder == BYTE_ORDER_BIG_ENDIAN ) { value = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; } - else if( byteOrder == LITTLEENDIAN ) + else if( byteOrder == BYTE_ORDER_LITTLE_ENDIAN ) { value = b1 | (b2 << 8) | (b3 << 16) | (b4 << 24); } @@ -159,11 +159,11 @@ int ByteBuffer::getInt(unsigned int index) int b3 = buffer[ index+2 ]; int b4 = buffer[ index+3 ]; - if( byteOrder == BIGENDIAN ) + if( byteOrder == BYTE_ORDER_BIG_ENDIAN ) { value = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; } - else if( byteOrder == LITTLEENDIAN ) + else if( byteOrder == BYTE_ORDER_LITTLE_ENDIAN ) { value = b1 | (b2 << 8) | (b3 << 16) | (b4 << 24); } @@ -193,11 +193,11 @@ int64_t ByteBuffer::getLong() m_position += 8; - if( byteOrder == BIGENDIAN ) + if( byteOrder == BYTE_ORDER_BIG_ENDIAN ) { value = (b1 << 56) | (b2 << 48) | (b3 << 40) | (b4 << 32) | (b5 << 24) | (b6 << 16) | (b7 << 8) | b8; } - else if( byteOrder == LITTLEENDIAN ) + else if( byteOrder == BYTE_ORDER_LITTLE_ENDIAN ) { value = b1 | (b2 << 8) | (b3 << 16) | (b4 << 24) | (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56); } @@ -221,11 +221,11 @@ short ByteBuffer::getShort() m_position += 2; - if( byteOrder == BIGENDIAN ) + if( byteOrder == BYTE_ORDER_BIG_ENDIAN ) { value = (b1 << 8) | b2; } - else if( byteOrder == LITTLEENDIAN ) + else if( byteOrder == BYTE_ORDER_LITTLE_ENDIAN ) { value = b1 | (b2 << 8); } @@ -275,14 +275,14 @@ ByteBuffer *ByteBuffer::putInt(int value) { assert( m_position+3 < m_limit ); - if( byteOrder == BIGENDIAN ) + if( byteOrder == BYTE_ORDER_BIG_ENDIAN ) { buffer[m_position] = (value >> 24) & 0xFF; buffer[m_position+1] = (value >> 16) & 0xFF; buffer[m_position+2] = (value >> 8) & 0xFF; buffer[m_position+3] = value & 0xFF; } - else if( byteOrder == LITTLEENDIAN ) + else if( byteOrder == BYTE_ORDER_LITTLE_ENDIAN ) { buffer[m_position] = value & 0xFF; buffer[m_position+1] = (value >> 8) & 0xFF; @@ -307,14 +307,14 @@ ByteBuffer *ByteBuffer::putInt(unsigned int index, int value) { assert( index+3 < m_limit ); - if( byteOrder == BIGENDIAN ) + if( byteOrder == BYTE_ORDER_BIG_ENDIAN ) { buffer[index] = (value >> 24) & 0xFF; buffer[index+1] = (value >> 16) & 0xFF; buffer[index+2] = (value >> 8) & 0xFF; buffer[index+3] = value & 0xFF; } - else if( byteOrder == LITTLEENDIAN ) + else if( byteOrder == BYTE_ORDER_LITTLE_ENDIAN ) { buffer[index] = value & 0xFF; buffer[index+1] = (value >> 8) & 0xFF; @@ -337,12 +337,12 @@ ByteBuffer *ByteBuffer::putShort(short value) { assert( m_position+1 < m_limit ); - if( byteOrder == BIGENDIAN ) + if( byteOrder == BYTE_ORDER_BIG_ENDIAN ) { buffer[m_position] = (value >> 8) & 0xFF; buffer[m_position+1] = value & 0xFF; } - else if( byteOrder == LITTLEENDIAN ) + else if( byteOrder == BYTE_ORDER_LITTLE_ENDIAN ) { buffer[m_position] = value & 0xFF; buffer[m_position+1] = (value >> 8) & 0xFF; @@ -377,7 +377,7 @@ ByteBuffer *ByteBuffer::putLong(int64_t value) { assert( m_position+7 < m_limit ); - if( byteOrder == BIGENDIAN ) + if( byteOrder == BYTE_ORDER_BIG_ENDIAN ) { buffer[m_position] = (value >> 56) & 0xFF; buffer[m_position+1] = (value >> 48) & 0xFF; @@ -388,7 +388,7 @@ ByteBuffer *ByteBuffer::putLong(int64_t value) buffer[m_position+6] = (value >> 8) & 0xFF; buffer[m_position+7] = value & 0xFF; } - else if( byteOrder == LITTLEENDIAN ) + else if( byteOrder == BYTE_ORDER_LITTLE_ENDIAN ) { buffer[m_position] = value & 0xFF; buffer[m_position+1] = (value >> 8) & 0xFF; @@ -467,7 +467,7 @@ ByteBuffer_IO::ByteBuffer_IO( unsigned int capacity ) : ByteBuffer(capacity, (byte*)RenderManager.allocIOMem(capacity, 64)) { memset( buffer,0,sizeof(byte)*capacity); - byteOrder = BIGENDIAN; + byteOrder = BYTE_ORDER_BIG_ENDIAN; } ByteBuffer_IO::~ByteBuffer_IO() diff --git a/Minecraft.World/CompressedTileStorage.cpp b/Minecraft.World/CompressedTileStorage.cpp index 53b401eb..ec92456a 100644 --- a/Minecraft.World/CompressedTileStorage.cpp +++ b/Minecraft.World/CompressedTileStorage.cpp @@ -1327,7 +1327,7 @@ void CompressedTileStorage::write(DataOutputStream *dos) unsigned char *localIndicesAndData = *(unsigned char *volatile *)&indicesAndData; if(localIndicesAndData) { - if(LOCALSYTEM_ENDIAN == BIGENDIAN) + if(LOCALSYTEM_ENDIAN == BYTE_ORDER_BIG_ENDIAN) { // The first 1024 bytes are an array of shorts, so we need to reverse the endianness byteArray indicesCopy(1024); @@ -1365,7 +1365,7 @@ void CompressedTileStorage::read(DataInputStream *dis) byteArray wrapper(indicesAndData, allocatedSize); dis->readFully(wrapper); - if(LOCALSYTEM_ENDIAN == BIGENDIAN) + if(LOCALSYTEM_ENDIAN == BYTE_ORDER_BIG_ENDIAN) { reverseIndices(indicesAndData); } diff --git a/Minecraft.World/Definitions.h b/Minecraft.World/Definitions.h index f45252f5..64fc31a8 100644 --- a/Minecraft.World/Definitions.h +++ b/Minecraft.World/Definitions.h @@ -15,13 +15,13 @@ typedef std::vector ObjectList; enum ByteOrder { - BIGENDIAN, - LITTLEENDIAN, + BYTE_ORDER_BIG_ENDIAN, + BYTE_ORDER_LITTLE_ENDIAN, #if defined(__PS3__) || defined(_XBOX) - LOCALSYTEM_ENDIAN = BIGENDIAN, + LOCALSYTEM_ENDIAN = BYTE_ORDER_BIG_ENDIAN, #else - LOCALSYTEM_ENDIAN = LITTLEENDIAN, + LOCALSYTEM_ENDIAN = BYTE_ORDER_LITTLE_ENDIAN, #endif }; enum EDefaultSkins diff --git a/Minecraft.World/FileHeader.cpp b/Minecraft.World/FileHeader.cpp index b2ebe083..cf7df48e 100644 --- a/Minecraft.World/FileHeader.cpp +++ b/Minecraft.World/FileHeader.cpp @@ -146,13 +146,13 @@ void FileHeader::ReadHeader( LPVOID saveMem, ESavePlatform plat /*= SAVE_FILE_PL { case SAVE_FILE_PLATFORM_X360: case SAVE_FILE_PLATFORM_PS3: - m_saveEndian = BIGENDIAN; + m_saveEndian = BYTE_ORDER_BIG_ENDIAN; break; case SAVE_FILE_PLATFORM_XBONE: case SAVE_FILE_PLATFORM_WIN64: case SAVE_FILE_PLATFORM_PS4: case SAVE_FILE_PLATFORM_PSVITA: - m_saveEndian = LITTLEENDIAN; + m_saveEndian = BYTE_ORDER_LITTLE_ENDIAN; break; default: assert(0); @@ -664,7 +664,7 @@ ByteOrder FileHeader::getEndian( ESavePlatform plat ) { case SAVE_FILE_PLATFORM_X360: case SAVE_FILE_PLATFORM_PS3: - return BIGENDIAN; + return BYTE_ORDER_BIG_ENDIAN; break; case SAVE_FILE_PLATFORM_NONE: @@ -672,11 +672,11 @@ ByteOrder FileHeader::getEndian( ESavePlatform plat ) case SAVE_FILE_PLATFORM_PS4: case SAVE_FILE_PLATFORM_PSVITA: case SAVE_FILE_PLATFORM_WIN64: - return LITTLEENDIAN; + return BYTE_ORDER_LITTLE_ENDIAN; break; default: assert(0); break; } - return LITTLEENDIAN; + return BYTE_ORDER_LITTLE_ENDIAN; } \ No newline at end of file diff --git a/Minecraft.World/FileHeader.h b/Minecraft.World/FileHeader.h index bfc6ff01..60f5d903 100644 --- a/Minecraft.World/FileHeader.h +++ b/Minecraft.World/FileHeader.h @@ -151,9 +151,9 @@ private: ESavePlatform m_savePlatform; ByteOrder m_saveEndian; #if defined(__PS3__) || defined(_XBOX) - static const ByteOrder m_localEndian = BIGENDIAN; + static const ByteOrder m_localEndian = BYTE_ORDER_BIG_ENDIAN; #else - static const ByteOrder m_localEndian = LITTLEENDIAN; + static const ByteOrder m_localEndian = BYTE_ORDER_LITTLE_ENDIAN; #endif short m_saveVersion; diff --git a/Minecraft.World/ZonedChunkStorage.cpp b/Minecraft.World/ZonedChunkStorage.cpp index 75df6a0c..01474afd 100644 --- a/Minecraft.World/ZonedChunkStorage.cpp +++ b/Minecraft.World/ZonedChunkStorage.cpp @@ -22,7 +22,7 @@ const int ZonedChunkStorage::CHUNK_SIZE = ZonedChunkStorage::CHUNK_WIDTH * Zoned const int ZonedChunkStorage::CHUNK_LAYERS = 3; const int ZonedChunkStorage::CHUNK_SIZE_BYTES = ZonedChunkStorage::CHUNK_SIZE * ZonedChunkStorage::CHUNK_LAYERS + ZonedChunkStorage::CHUNK_HEADER_SIZE; -const ByteOrder ZonedChunkStorage::BYTEORDER = BIGENDIAN; +const ByteOrder ZonedChunkStorage::BYTEORDER = BYTE_ORDER_BIG_ENDIAN; ZonedChunkStorage::ZonedChunkStorage(File dir) { diff --git a/cmake/ServerTarget.cmake b/cmake/ServerTarget.cmake index 2cb364a9..9ea44f67 100644 --- a/cmake/ServerTarget.cmake +++ b/cmake/ServerTarget.cmake @@ -77,6 +77,7 @@ function(configure_lce_server_target target) d3dcompiler XInput9_1_0 wsock32 + ws2_32 dbghelp legacy_stdio_definitions 4JLibs.${PLATFORM_NAME}.Input