aboutsummaryrefslogtreecommitdiff
path: root/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp')
-rw-r--r--Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp215
1 files changed, 141 insertions, 74 deletions
diff --git a/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp b/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp
index 19fc2598..d3ea1c3a 100644
--- a/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp
+++ b/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp
@@ -1,3 +1,6 @@
+// Code implemented by LCEMP, credit if used on other repos
+// https://github.com/LCEMP/LCEMP
+
#include "stdafx.h"
#ifdef _WINDOWS64
@@ -151,7 +154,7 @@ bool WinsockNetLayer::HostGame(int port)
LeaveCriticalSection(&s_freeSmallIdLock);
struct addrinfo hints = {};
- struct addrinfo *result = NULL;
+ struct addrinfo* result = NULL;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
@@ -177,7 +180,7 @@ bool WinsockNetLayer::HostGame(int port)
}
int opt = 1;
- setsockopt(s_listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt));
+ setsockopt(s_listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
iResult = ::bind(s_listenSocket, result->ai_addr, (int)result->ai_addrlen);
freeaddrinfo(result);
@@ -207,15 +210,23 @@ bool WinsockNetLayer::HostGame(int port)
return true;
}
-bool WinsockNetLayer::JoinGame(const char *ip, int port)
+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;
+ }
struct addrinfo hints = {};
- struct addrinfo *result = NULL;
+ struct addrinfo* result = NULL;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
@@ -231,37 +242,55 @@ bool WinsockNetLayer::JoinGame(const char *ip, int port)
return false;
}
- s_hostConnectionSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
- if (s_hostConnectionSocket == INVALID_SOCKET)
+ bool connected = false;
+ BYTE assignedSmallId = 0;
+ const int maxAttempts = 12;
+
+ for (int attempt = 0; attempt < maxAttempts; ++attempt)
{
- app.DebugPrintf("socket() failed: %d\n", WSAGetLastError());
- freeaddrinfo(result);
- return false;
- }
+ 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));
+ int noDelay = 1;
+ setsockopt(s_hostConnectionSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&noDelay, sizeof(noDelay));
- iResult = connect(s_hostConnectionSocket, result->ai_addr, (int)result->ai_addrlen);
- freeaddrinfo(result);
- if (iResult == SOCKET_ERROR)
- {
- app.DebugPrintf("connect() to %s:%d failed: %d\n", ip, port, WSAGetLastError());
- closesocket(s_hostConnectionSocket);
- s_hostConnectionSocket = INVALID_SOCKET;
- return false;
+ iResult = connect(s_hostConnectionSocket, result->ai_addr, (int)result->ai_addrlen);
+ if (iResult == SOCKET_ERROR)
+ {
+ int err = WSAGetLastError();
+ 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;
+ }
+
+ 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;
+ Sleep(200);
+ continue;
+ }
+
+ assignedSmallId = assignBuf[0];
+ connected = true;
+ break;
}
+ freeaddrinfo(result);
- BYTE assignBuf[1];
- int bytesRecv = recv(s_hostConnectionSocket, (char *)assignBuf, 1, 0);
- if (bytesRecv != 1)
+ if (!connected)
{
- app.DebugPrintf("Failed to receive small ID assignment from host\n");
- closesocket(s_hostConnectionSocket);
- s_hostConnectionSocket = INVALID_SOCKET;
return false;
}
- s_localSmallId = assignBuf[0];
+ s_localSmallId = assignedSmallId;
app.DebugPrintf("Win64 LAN: Connected to %s:%d, assigned smallId=%d\n", ip, port, s_localSmallId);
@@ -273,7 +302,7 @@ bool WinsockNetLayer::JoinGame(const char *ip, int port)
return true;
}
-bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void *data, int dataSize)
+bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void* data, int dataSize)
{
if (sock == INVALID_SOCKET || dataSize <= 0) return false;
@@ -289,7 +318,7 @@ bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void *data, int dataSize)
int toSend = 4;
while (totalSent < toSend)
{
- int sent = send(sock, (const char *)header + totalSent, toSend - totalSent, 0);
+ int sent = send(sock, (const char*)header + totalSent, toSend - totalSent, 0);
if (sent == SOCKET_ERROR || sent == 0)
{
LeaveCriticalSection(&s_sendLock);
@@ -301,7 +330,7 @@ bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void *data, int dataSize)
totalSent = 0;
while (totalSent < dataSize)
{
- int sent = send(sock, (const char *)data + totalSent, dataSize - totalSent, 0);
+ int sent = send(sock, (const char*)data + totalSent, dataSize - totalSent, 0);
if (sent == SOCKET_ERROR || sent == 0)
{
LeaveCriticalSection(&s_sendLock);
@@ -314,7 +343,7 @@ bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void *data, int dataSize)
return true;
}
-bool WinsockNetLayer::SendToSmallId(BYTE targetSmallId, const void *data, int dataSize)
+bool WinsockNetLayer::SendToSmallId(BYTE targetSmallId, const void* data, int dataSize)
{
if (!s_active) return false;
@@ -346,34 +375,34 @@ SOCKET WinsockNetLayer::GetSocketForSmallId(BYTE smallId)
return INVALID_SOCKET;
}
-static bool RecvExact(SOCKET sock, BYTE *buf, int len)
+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);
+ int r = recv(sock, (char*)buf + totalRecv, len - totalRecv, 0);
if (r <= 0) return false;
totalRecv += r;
}
return true;
}
-void WinsockNetLayer::HandleDataReceived(BYTE fromSmallId, BYTE toSmallId, unsigned char *data, unsigned int dataSize)
+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);
+ INetworkPlayer* pPlayerFrom = g_NetworkManager.GetPlayerBySmallId(fromSmallId);
+ INetworkPlayer* pPlayerTo = g_NetworkManager.GetPlayerBySmallId(toSmallId);
if (pPlayerFrom == NULL || pPlayerTo == NULL) return;
if (s_isHost)
{
- ::Socket *pSocket = pPlayerFrom->GetSocket();
+ ::Socket* pSocket = pPlayerFrom->GetSocket();
if (pSocket != NULL)
pSocket->pushDataToQueue(data, dataSize, false);
}
else
{
- ::Socket *pSocket = pPlayerTo->GetSocket();
+ ::Socket* pSocket = pPlayerTo->GetSocket();
if (pSocket != NULL)
pSocket->pushDataToQueue(data, dataSize, true);
}
@@ -392,7 +421,7 @@ DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param)
}
int noDelay = 1;
- setsockopt(clientSocket, IPPROTO_TCP, TCP_NODELAY, (const char *)&noDelay, sizeof(noDelay));
+ setsockopt(clientSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&noDelay, sizeof(noDelay));
extern QNET_STATE _iQNetStubState;
if (_iQNetStubState != QNET_STATE_GAME_PLAY)
@@ -423,7 +452,7 @@ DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param)
LeaveCriticalSection(&s_freeSmallIdLock);
BYTE assignBuf[1] = { assignedSmallId };
- int sent = send(clientSocket, (const char *)assignBuf, 1, 0);
+ int sent = send(clientSocket, (const char*)assignBuf, 1, 0);
if (sent != 1)
{
app.DebugPrintf("Failed to send small ID to client\n");
@@ -444,15 +473,15 @@ DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param)
app.DebugPrintf("Win64 LAN: Client connected, assigned smallId=%d\n", assignedSmallId);
- IQNetPlayer *qnetPlayer = &IQNet::m_player[assignedSmallId];
+ IQNetPlayer* qnetPlayer = &IQNet::m_player[assignedSmallId];
- extern void Win64_SetupRemoteQNetPlayer(IQNetPlayer *player, BYTE smallId, bool isHost, bool isLocal);
+ extern void Win64_SetupRemoteQNetPlayer(IQNetPlayer * player, BYTE smallId, bool isHost, bool isLocal);
Win64_SetupRemoteQNetPlayer(qnetPlayer, assignedSmallId, false, false);
- extern CPlatformNetworkManagerStub *g_pPlatformNetworkManager;
+ extern CPlatformNetworkManagerStub* g_pPlatformNetworkManager;
g_pPlatformNetworkManager->NotifyPlayerJoined(qnetPlayer);
- DWORD *threadParam = new DWORD;
+ DWORD* threadParam = new DWORD;
*threadParam = connIdx;
HANDLE hThread = CreateThread(NULL, 0, RecvThreadProc, threadParam, 0, NULL);
@@ -466,8 +495,8 @@ DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param)
DWORD WINAPI WinsockNetLayer::RecvThreadProc(LPVOID param)
{
- DWORD connIdx = *(DWORD *)param;
- delete (DWORD *)param;
+ DWORD connIdx = *(DWORD*)param;
+ delete (DWORD*)param;
EnterCriticalSection(&s_connectionsLock);
if (connIdx >= (DWORD)s_connections.size())
@@ -479,7 +508,8 @@ DWORD WINAPI WinsockNetLayer::RecvThreadProc(LPVOID param)
BYTE clientSmallId = s_connections[connIdx].smallId;
LeaveCriticalSection(&s_connectionsLock);
- BYTE *recvBuf = new BYTE[WIN64_NET_RECV_BUFFER_SIZE];
+ std::vector<BYTE> recvBuf;
+ recvBuf.resize(WIN64_NET_RECV_BUFFER_SIZE);
while (s_active)
{
@@ -490,33 +520,47 @@ DWORD WINAPI WinsockNetLayer::RecvThreadProc(LPVOID param)
break;
}
- int packetSize = (header[0] << 24) | (header[1] << 16) | (header[2] << 8) | header[3];
+ 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_RECV_BUFFER_SIZE)
+ if (packetSize <= 0 || packetSize > WIN64_NET_MAX_PACKET_SIZE)
{
- app.DebugPrintf("Win64 LAN: Invalid packet size %d from client smallId=%d\n", packetSize, clientSmallId);
+ 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 (!RecvExact(sock, recvBuf, packetSize))
+ if ((int)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, packetSize);
+ HandleDataReceived(clientSmallId, s_hostSmallId, &recvBuf[0], packetSize);
}
- delete[] recvBuf;
-
EnterCriticalSection(&s_connectionsLock);
for (size_t i = 0; i < s_connections.size(); i++)
{
if (s_connections[i].smallId == clientSmallId)
{
s_connections[i].active = false;
- closesocket(s_connections[i].tcpSocket);
- s_connections[i].tcpSocket = INVALID_SOCKET;
+ if (s_connections[i].tcpSocket != INVALID_SOCKET)
+ {
+ closesocket(s_connections[i].tcpSocket);
+ s_connections[i].tcpSocket = INVALID_SOCKET;
+ }
break;
}
}
@@ -529,7 +573,7 @@ DWORD WINAPI WinsockNetLayer::RecvThreadProc(LPVOID param)
return 0;
}
-bool WinsockNetLayer::PopDisconnectedSmallId(BYTE *outSmallId)
+bool WinsockNetLayer::PopDisconnectedSmallId(BYTE* outSmallId)
{
bool found = false;
EnterCriticalSection(&s_disconnectLock);
@@ -550,9 +594,26 @@ void WinsockNetLayer::PushFreeSmallId(BYTE 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);
+}
+
DWORD WINAPI WinsockNetLayer::ClientRecvThreadProc(LPVOID param)
{
- BYTE *recvBuf = new BYTE[WIN64_NET_RECV_BUFFER_SIZE];
+ std::vector<BYTE> recvBuf;
+ recvBuf.resize(WIN64_NET_RECV_BUFFER_SIZE);
while (s_active && s_hostConnectionSocket != INVALID_SOCKET)
{
@@ -565,28 +626,34 @@ DWORD WINAPI WinsockNetLayer::ClientRecvThreadProc(LPVOID param)
int packetSize = (header[0] << 24) | (header[1] << 16) | (header[2] << 8) | header[3];
- if (packetSize <= 0 || packetSize > WIN64_NET_RECV_BUFFER_SIZE)
+ if (packetSize <= 0 || packetSize > WIN64_NET_MAX_PACKET_SIZE)
{
- app.DebugPrintf("Win64 LAN: Invalid packet size %d from host\n", packetSize);
+ app.DebugPrintf("Win64 LAN: Invalid packet size %d from host (max=%d)\n",
+ packetSize,
+ (int)WIN64_NET_MAX_PACKET_SIZE);
break;
}
- if (!RecvExact(s_hostConnectionSocket, recvBuf, packetSize))
+ if ((int)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, packetSize);
+ HandleDataReceived(s_hostSmallId, s_localSmallId, &recvBuf[0], packetSize);
}
- delete[] recvBuf;
-
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)
+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;
@@ -614,7 +681,7 @@ bool WinsockNetLayer::StartAdvertising(int gamePort, const wchar_t *hostName, un
}
BOOL broadcast = TRUE;
- setsockopt(s_advertiseSock, SOL_SOCKET, SO_BROADCAST, (const char *)&broadcast, sizeof(broadcast));
+ setsockopt(s_advertiseSock, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast));
s_advertising = true;
s_advertiseThread = CreateThread(NULL, 0, AdvertiseThreadProc, NULL, 0, NULL);
@@ -669,8 +736,8 @@ DWORD WINAPI WinsockNetLayer::AdvertiseThreadProc(LPVOID param)
Win64LANBroadcast data = s_advertiseData;
LeaveCriticalSection(&s_advertiseLock);
- int sent = sendto(s_advertiseSock, (const char *)&data, sizeof(data), 0,
- (struct sockaddr *)&broadcastAddr, sizeof(broadcastAddr));
+ int sent = sendto(s_advertiseSock, (const char*)&data, sizeof(data), 0,
+ (struct sockaddr*)&broadcastAddr, sizeof(broadcastAddr));
if (sent == SOCKET_ERROR && s_advertising)
{
@@ -696,7 +763,7 @@ bool WinsockNetLayer::StartDiscovery()
}
BOOL reuseAddr = TRUE;
- setsockopt(s_discoverySock, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuseAddr, sizeof(reuseAddr));
+ setsockopt(s_discoverySock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuseAddr, sizeof(reuseAddr));
struct sockaddr_in bindAddr;
memset(&bindAddr, 0, sizeof(bindAddr));
@@ -704,7 +771,7 @@ bool WinsockNetLayer::StartDiscovery()
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)
+ if (::bind(s_discoverySock, (struct sockaddr*)&bindAddr, sizeof(bindAddr)) == SOCKET_ERROR)
{
app.DebugPrintf("Win64 LAN: Discovery bind failed: %d\n", WSAGetLastError());
closesocket(s_discoverySock);
@@ -713,7 +780,7 @@ bool WinsockNetLayer::StartDiscovery()
}
DWORD timeout = 500;
- setsockopt(s_discoverySock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof(timeout));
+ setsockopt(s_discoverySock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
s_discovering = true;
s_discoveryThread = CreateThread(NULL, 0, DiscoveryThreadProc, NULL, 0, NULL);
@@ -763,7 +830,7 @@ DWORD WINAPI WinsockNetLayer::DiscoveryThreadProc(LPVOID param)
int senderLen = sizeof(senderAddr);
int recvLen = recvfrom(s_discoverySock, recvBuf, sizeof(recvBuf), 0,
- (struct sockaddr *)&senderAddr, &senderLen);
+ (struct sockaddr*)&senderAddr, &senderLen);
if (recvLen == SOCKET_ERROR)
{
@@ -773,7 +840,7 @@ DWORD WINAPI WinsockNetLayer::DiscoveryThreadProc(LPVOID param)
if (recvLen < (int)sizeof(Win64LANBroadcast))
continue;
- Win64LANBroadcast *broadcast = (Win64LANBroadcast *)recvBuf;
+ Win64LANBroadcast* broadcast = (Win64LANBroadcast*)recvBuf;
if (broadcast->magic != WIN64_LAN_BROADCAST_MAGIC)
continue;
@@ -841,4 +908,4 @@ DWORD WINAPI WinsockNetLayer::DiscoveryThreadProc(LPVOID param)
return 0;
}
-#endif
+#endif \ No newline at end of file