From b9025b50bdbb281fd433b04fac5239dbe9394f65 Mon Sep 17 00:00:00 2001 From: ANR2ME Date: Thu, 19 Mar 2020 15:21:00 +0700 Subject: [PATCH 1/7] Added a UPnP option to use original port for external port instead of using the shifted port by port offset, to be compatible with real PSP or other PSP emulators --- Core/Config.cpp | 3 ++- Core/Config.h | 1 + Core/HLE/proAdhoc.cpp | 39 ++++++++++++++++++++++++++++--------- Core/HLE/proAdhoc.h | 6 ++++++ Core/HLE/proAdhocServer.cpp | 4 ++-- Core/HLE/sceNet.cpp | 1 + Core/HLE/sceNetAdhoc.cpp | 27 ++++++++++++++++--------- Core/Util/PortManager.cpp | 29 +++++++++++++-------------- Core/Util/PortManager.h | 12 ++++++------ UI/GameSettingsScreen.cpp | 9 ++++++--- 10 files changed, 86 insertions(+), 45 deletions(-) diff --git a/Core/Config.cpp b/Core/Config.cpp index a61ea02740..3bc22a4a20 100644 --- a/Core/Config.cpp +++ b/Core/Config.cpp @@ -957,8 +957,9 @@ static ConfigSetting networkSettings[] = { ConfigSetting("EnableAdhocServer", &g_Config.bEnableAdhocServer, false, true, true), ConfigSetting("proAdhocServer", &g_Config.proAdhocServer, "myneighborsushicat.com", true, true), ConfigSetting("PortOffset", &g_Config.iPortOffset, 0, true, true), - ConfigSetting("EnableUPnP", &g_Config.bEnableUPnP, false, true, true), ConfigSetting("MinTimeout", &g_Config.iMinTimeout, 1, true, true), + ConfigSetting("EnableUPnP", &g_Config.bEnableUPnP, false, true, true), + ConfigSetting("UPnPUseOriginalPort", &g_Config.bUPnPUseOriginalPort, true, true, true), ConfigSetting("EnableNetworkChat", &g_Config.bEnableNetworkChat, false, true, true), ConfigSetting("ChatButtonPosition",&g_Config.iChatButtonPosition,BOTTOM_LEFT,true,true), diff --git a/Core/Config.h b/Core/Config.h index 8ef4696b4f..5bd145c601 100644 --- a/Core/Config.h +++ b/Core/Config.h @@ -412,6 +412,7 @@ public: bool bEnableWlan; bool bEnableAdhocServer; bool bEnableUPnP; + bool bUPnPUseOriginalPort; int iPortOffset; int iMinTimeout; int iWlanAdhocChannel; diff --git a/Core/HLE/proAdhoc.cpp b/Core/HLE/proAdhoc.cpp index 418612ee56..1bbbf61714 100644 --- a/Core/HLE/proAdhoc.cpp +++ b/Core/HLE/proAdhoc.cpp @@ -73,6 +73,7 @@ std::string message = ""; bool chatScreenVisible = false; bool updateChatScreen = false; int newChat = 0; +bool isOriPort = false; bool isLocalServer = false; sockaddr LocalhostIP; sockaddr LocalIP; @@ -82,11 +83,7 @@ bool isLocalMAC(const SceNetEtherAddr * addr) { SceNetEtherAddr saddr; getLocalMac(&saddr); - // Compare MAC Addresses - int match = memcmp((const void *)addr, (const void *)&saddr, ETHER_ADDR_LEN); - - // Return Result - return (match == 0); + return (memcmp((const void*)addr, (const void*)&saddr, ETHER_ADDR_LEN) == 0); } bool isPDPPortInUse(uint16_t port) { @@ -1604,6 +1601,33 @@ uint32_t getLocalIp(int sock) { return localAddr.sin_addr.s_addr; } +static std::vector> InitPrivateIPRanges() { + struct sockaddr_in saNet, saMask; + std::vector> ip_ranges; + + if (1 == inet_pton(AF_INET, "192.168.0.0", &(saNet.sin_addr)) && 1 == inet_pton(AF_INET, "255.255.0.0", &(saMask.sin_addr))) + ip_ranges.push_back({saNet.sin_addr.s_addr, saMask.sin_addr.s_addr}); + if (1 == inet_pton(AF_INET, "172.16.0.0", &(saNet.sin_addr)) && 1 == inet_pton(AF_INET, "255.240.0.0", &(saMask.sin_addr))) + ip_ranges.push_back({ saNet.sin_addr.s_addr, saMask.sin_addr.s_addr }); + if (1 == inet_pton(AF_INET, "10.0.0.0", &(saNet.sin_addr)) && 1 == inet_pton(AF_INET, "255.0.0.0", &(saMask.sin_addr))) + ip_ranges.push_back({ saNet.sin_addr.s_addr, saMask.sin_addr.s_addr }); + if (1 == inet_pton(AF_INET, "127.0.0.0", &(saNet.sin_addr)) && 1 == inet_pton(AF_INET, "255.0.0.0", &(saMask.sin_addr))) + ip_ranges.push_back({ saNet.sin_addr.s_addr, saMask.sin_addr.s_addr }); + if (1 == inet_pton(AF_INET, "169.254.0.0", &(saNet.sin_addr)) && 1 == inet_pton(AF_INET, "255.255.0.0", &(saMask.sin_addr))) + ip_ranges.push_back({ saNet.sin_addr.s_addr, saMask.sin_addr.s_addr }); + + return ip_ranges; +} + +bool isPrivateIP(uint32_t ip) { + static const std::vector> ip_ranges = InitPrivateIPRanges(); + for (auto ipRange : ip_ranges) { + if ((ip & ipRange.second) == (ipRange.first & ipRange.second)) // We can just use ipRange.first directly if it's already correctly formatted + return true; + } + return false; +} + void getLocalMac(SceNetEtherAddr * addr){ // Read MAC Address from config uint8_t mac[ETHER_ADDR_LEN] = {0}; @@ -1859,10 +1883,7 @@ int initNetwork(SceNetAdhocctlAdhocId *adhoc_id){ } bool isBroadcastMAC(const SceNetEtherAddr * addr) { - // Broadcast MAC - if (memcmp(addr->data, "\xFF\xFF\xFF\xFF\xFF\xFF", ETHER_ADDR_LEN) == 0) return true; - // Normal MAC - return false; + return (memcmp(addr->data, "\xFF\xFF\xFF\xFF\xFF\xFF", ETHER_ADDR_LEN) == 0); } bool resolveIP(uint32_t ip, SceNetEtherAddr * mac) { diff --git a/Core/HLE/proAdhoc.h b/Core/HLE/proAdhoc.h index 29ce58f2d1..c1d5fe8b25 100644 --- a/Core/HLE/proAdhoc.h +++ b/Core/HLE/proAdhoc.h @@ -844,6 +844,7 @@ extern SceNetAdhocPtpStat * ptp[255]; extern uint16_t portOffset; extern uint32_t minSocketTimeoutUS; +extern bool isOriPort; extern bool isLocalServer; extern sockaddr LocalhostIP; // Used to differentiate localhost IP on multiple-instance extern sockaddr LocalIP; // IP of Network Adapter used to connect to Adhoc Server (LAN/WAN) @@ -1159,6 +1160,11 @@ int getActivePeerCount(const bool excludeTimedout = true); int getLocalIp(sockaddr_in * SocketAddress); uint32_t getLocalIp(int sock); +/* + * Check if an IP (big-endian/network order) is Private or Public IP + */ +bool isPrivateIP(uint32_t ip); + /* * Get UDP Socket Max Message Size */ diff --git a/Core/HLE/proAdhocServer.cpp b/Core/HLE/proAdhocServer.cpp index c8ef8ea79c..7d663ba1d4 100644 --- a/Core/HLE/proAdhocServer.cpp +++ b/Core/HLE/proAdhocServer.cpp @@ -1685,13 +1685,13 @@ int proAdhocServerThread(int port) // (int argc, char * argv[]) INFO_LOG(SCENET, "AdhocServer: Listening for Connections on TCP Port %u", port); //SERVER_PORT // Port forward - g_PortManager.Add(port, IP_PROTOCOL_TCP); + g_PortManager.Add(IP_PROTOCOL_TCP, port); // Enter Server Loop result = server_loop(server); // Remove Port mapping - g_PortManager.Remove(port, IP_PROTOCOL_TCP); + g_PortManager.Remove(IP_PROTOCOL_TCP, port); // Notify User INFO_LOG(SCENET, "AdhocServer: Shutdown complete"); diff --git a/Core/HLE/sceNet.cpp b/Core/HLE/sceNet.cpp index 208cbfebd3..7a04f827cc 100644 --- a/Core/HLE/sceNet.cpp +++ b/Core/HLE/sceNet.cpp @@ -118,6 +118,7 @@ static void __ResetInitNetLib() { void __NetInit() { // Windows: Assuming WSAStartup already called beforehand portOffset = g_Config.iPortOffset; + isOriPort = g_Config.bEnableUPnP && g_Config.bUPnPUseOriginalPort; minSocketTimeoutUS = g_Config.iMinTimeout * 1000UL; InitLocalhostIP(); diff --git a/Core/HLE/sceNetAdhoc.cpp b/Core/HLE/sceNetAdhoc.cpp index 301c41d5c1..28dca3b32b 100644 --- a/Core/HLE/sceNetAdhoc.cpp +++ b/Core/HLE/sceNetAdhoc.cpp @@ -377,7 +377,7 @@ static int sceNetAdhocPdpCreate(const char *mac, int port, int bufferSize, u32 u // Fill in Data internal->id = usocket; internal->laddr = *saddr; - internal->lport = port; //getLocalPort(usocket) - portOffset; //should use the port given to the socket (in case it's UNUSED_PORT port) isn't? + internal->lport = port; //getLocalPort(usocket) - portOffset; internal->rcv_sb_cc = bufferSize; // Link Socket to Translator ID @@ -385,7 +385,7 @@ static int sceNetAdhocPdpCreate(const char *mac, int port, int bufferSize, u32 u // Forward Port on Router //sceNetPortOpen("UDP", port); - g_PortManager.Add(port + portOffset, IP_PROTOCOL_UDP); + g_PortManager.Add(IP_PROTOCOL_UDP, isOriPort ? port : port + portOffset, port + portOffset); // Success return i + 1; @@ -519,6 +519,9 @@ static int sceNetAdhocPdpSend(int id, const char *mac, u32 port, void *data, int // Get Peer IP if (resolveMAC((SceNetEtherAddr *)daddr, (uint32_t *)&target.sin_addr.s_addr)) { + // Some games (ie. PSP2) might try to talk to it's self, not sure if they talked through WAN or LAN when using public Adhoc Server tho + target.sin_port = htons(dport + ((isOriPort && !isPrivateIP(target.sin_addr.s_addr)) ? 0 : portOffset)); + // Acquire Network Lock //_acquireNetworkLock(); @@ -588,7 +591,7 @@ static int sceNetAdhocPdpSend(int id, const char *mac, u32 port, void *data, int sockaddr_in target; target.sin_family = AF_INET; target.sin_addr.s_addr = peer->ip_addr; - target.sin_port = htons(dport + portOffset); + target.sin_port = htons(dport + ((isOriPort && !isPrivateIP(peer->ip_addr)) ? 0 : portOffset)); int sent = sendto(socket->id, (const char *)data, len, 0, (sockaddr *)&target, sizeof(target)); int error = errno; @@ -980,7 +983,7 @@ static int sceNetAdhocPdpDelete(int id, int unknown) { // Remove Port Forward from Router //sceNetPortClose("UDP", sock->lport); - //g_PortManager.Remove(sock->lport + portOffset, IP_PROTOCOL_UDP); // Let's not remove mapping in real-time as it could cause lags/disconnection when joining a room with slow routers + //g_PortManager.Remove(IP_PROTOCOL_UDP, isOriPort ? sock->lport : sock->lport + portOffset); // Let's not remove mapping in real-time as it could cause lags/disconnection when joining a room with slow routers // Free Memory free(sock); @@ -1870,6 +1873,7 @@ static int sceNetAdhocPtpOpen(const char *srcmac, int sport, const char *dstmac, } SceNetEtherAddr* saddr = (SceNetEtherAddr*)srcmac; SceNetEtherAddr* daddr = (SceNetEtherAddr*)dstmac; + bool isClient = false; // Library is initialized if (netAdhocInited) { // Some games (ie. DBZ Shin Budokai 2) might be getting the saddr/srcmac content from SaveState and causing problems if current MAC is different :( So we try to fix it here @@ -1880,6 +1884,7 @@ static int sceNetAdhocPtpOpen(const char *srcmac, int sport, const char *dstmac, if (saddr != NULL && isLocalMAC(saddr) && daddr != NULL && !isBroadcastMAC(daddr)) { // Random Port required if (sport == 0) { + isClient = true; // Find unused Port // while (sport == 0 || _IsPTPPortInUse(sport)) { // // Generate Port Number @@ -1963,7 +1968,8 @@ static int sceNetAdhocPtpOpen(const char *srcmac, int sport, const char *dstmac, // Add Port Forward to Router. We may not even need to forward this local port, since PtpOpen usually have port 0 (any port) as source port and followed by PtpConnect (which mean acting as Client), right? //sceNetPortOpen("TCP", sport); - //g_PortManager.Add(sport + portOffset, IP_PROTOCOL_TCP); + if (!isClient) + g_PortManager.Add(IP_PROTOCOL_TCP, isOriPort ? sport : sport + portOffset, sport + portOffset); // Return PTP Socket Pointer return i + 1; @@ -2153,7 +2159,7 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int // Add Port Forward to Router. Or may be doesn't need to be forwarded since local port already accessible from outside if others were able to connect & get accepted at this point, right? //sceNetPortOpen("TCP", internal->lport); - //g_PortManager.Add(internal->lport + portOffset, IP_PROTOCOL_TCP); + //g_PortManager.Add(IP_PROTOCOL_TCP, internal->lport + portOffset); INFO_LOG(SCENET, "sceNetAdhocPtpAccept[%i->%i:%u]: Established (%s:%u)", id, i+1, internal->lport, inet_ntoa(peeraddr.sin_addr), internal->pport); @@ -2234,6 +2240,9 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) { // Grab Peer IP if (resolveMAC(&socket->paddr, (uint32_t *)&sin.sin_addr.s_addr)) { + // Some games (ie. PSP2) might try to talk to it's self, not sure if they talked through WAN or LAN when using public Adhoc Server tho + sin.sin_port = htons(socket->pport + ((isOriPort && !isPrivateIP(sin.sin_addr.s_addr)) ? 0 : portOffset)); + // Grab Nonblocking Flag uint32_t nbio = getBlockingFlag(socket->id); @@ -2245,7 +2254,7 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) { }*/ // Connect Socket to Peer (Nonblocking) - // Fixme: The First Non-blocking POSIX connect will always returns EAGAIN/EWOULDBLOCK because it returns without waiting for ACK, But GvG Next Plus is treating non-blocking connect just like blocking connect, May be on a real PSP the first non-blocking sceNetAdhocPtpConnect can be successfull? + // NOTE: Based on what i read at stackoverflow, The First Non-blocking POSIX connect will always returns EAGAIN/EWOULDBLOCK because it returns without waiting for ACK/handshake, But GvG Next Plus is treating non-blocking PtpConnect just like blocking connect, May be on a real PSP the first non-blocking sceNetAdhocPtpConnect can be successfull? int connectresult = connect(socket->id, (sockaddr *)&sin, sizeof(sin)); // Grab Error Code @@ -2352,7 +2361,7 @@ static int sceNetAdhocPtpClose(int id, int unknown) { // Remove Port Forward from Router //sceNetPortClose("TCP", socket->lport); - //g_PortManager.Remove(socket->lport + portOffset, IP_PROTOCOL_TCP); // Let's not remove mapping in real-time as it could cause lags/disconnection when joining a room with slow routers + //g_PortManager.Remove(IP_PROTOCOL_TCP, isOriPort ? socket->lport : socket->lport + portOffset); // Let's not remove mapping in real-time as it could cause lags/disconnection when joining a room with slow routers // Free Memory free(socket); @@ -2488,7 +2497,7 @@ static int sceNetAdhocPtpListen(const char *srcmac, int sport, int bufsize, int // Add Port Forward to Router //sceNetPortOpen("TCP", sport); - g_PortManager.Add(sport + portOffset, IP_PROTOCOL_TCP); + g_PortManager.Add(IP_PROTOCOL_TCP, isOriPort ? sport : sport + portOffset, sport + portOffset); // Return PTP Socket Pointer return i + 1; diff --git a/Core/Util/PortManager.cpp b/Core/Util/PortManager.cpp index 166944e75b..8e25cdca37 100644 --- a/Core/Util/PortManager.cpp +++ b/Core/Util/PortManager.cpp @@ -30,8 +30,8 @@ #include #include #include -#include "Core/HLE/proAdhoc.h" // This import is only used to get product id that was used to connect to adhoc server #include "Core/Util/PortManager.h" +#include #include "i18n/i18n.h" @@ -77,7 +77,7 @@ bool PortManager::Init(const unsigned int timeout) { char* descXML; int descXMLsize = 0; int descXMLstatus = 0; - int localport = m_LocalPort; // UPNP_LOCAL_PORT_ANY (0), or UPNP_LOCAL_PORT_SAME (1) as an alias for 1900 for backwards compatability? + int localport = m_LocalPort; // UPNP_LOCAL_PORT_ANY (0), or UPNP_LOCAL_PORT_SAME (1) as an alias for 1900 (for backwards compatability?) int ipv6 = 0; // 0 = IPv4, 1 = IPv6 unsigned char ttl = 2; // defaulting to 2 int error = 0; @@ -151,13 +151,8 @@ bool PortManager::Init(const unsigned int timeout) { INFO_LOG(SCENET, "PortManager - Connection Type: %s", connectionType); } - // Using Game ID & Player Name as default description for mapping (prioritizing the ID sent by the game to Adhoc server) - char productid[10] = { 0 }; - memcpy(productid, product_code.data, sizeof(product_code.data)); - std::string gameID = std::string(productid); - if (productid[0] == '\0') { - gameID = g_paramSFO.GetDiscID(); - } + // Using Game ID & Player Name as default description for mapping + std::string gameID = g_paramSFO.GetDiscID(); m_defaultDesc = "PPSSPP:" + gameID + ":" + g_Config.sNickName; freeUPNPDevlist(devlist); @@ -179,17 +174,21 @@ int PortManager::GetInitState() { return m_InitState; } -bool PortManager::Add(unsigned short port, const char* protocol) { +bool PortManager::Add(const char* protocol, unsigned short port, unsigned short intport) { char port_str[16]; + char intport_str[16]; int r; - INFO_LOG(SCENET, "PortManager::Add(%d, %s)", port, protocol); + if (intport == 0) + intport = port; + INFO_LOG(SCENET, "PortManager::Add(%s, %d, %d)", protocol, port, intport); if (urls == NULL || urls->controlURL == NULL || urls->controlURL[0] == '\0') { if (g_Config.bEnableUPnP) WARN_LOG(SCENET, "PortManager::Add - the init was not done !"); return false; } sprintf(port_str, "%d", port); + sprintf(intport_str, "%d", intport); // Only add new port map if it's not previously created by PPSSPP for current IP auto el_it = std::find_if(m_portList.begin(), m_portList.end(), [port_str, protocol](const std::pair &el) { return el.first == port_str && el.second == protocol; }); @@ -201,11 +200,11 @@ bool PortManager::Add(unsigned short port, const char* protocol) { r = UPNP_DeletePortMapping(urls->controlURL, datas->first.servicetype, port_str, protocol, NULL); } r = UPNP_AddPortMapping(urls->controlURL, datas->first.servicetype, - port_str, port_str, m_lanip.c_str(), m_defaultDesc.c_str(), protocol, NULL, m_leaseDuration.c_str()); + port_str, intport_str, m_lanip.c_str(), m_defaultDesc.c_str(), protocol, NULL, m_leaseDuration.c_str()); if (r == 725 && m_leaseDuration != "0") { m_leaseDuration = "0"; r = UPNP_AddPortMapping(urls->controlURL, datas->first.servicetype, - port_str, port_str, m_lanip.c_str(), m_defaultDesc.c_str(), protocol, NULL, m_leaseDuration.c_str()); + port_str, intport_str, m_lanip.c_str(), m_defaultDesc.c_str(), protocol, NULL, m_leaseDuration.c_str()); } if (r != 0) { @@ -224,10 +223,10 @@ bool PortManager::Add(unsigned short port, const char* protocol) { return true; } -bool PortManager::Remove(unsigned short port, const char* protocol) { +bool PortManager::Remove(const char* protocol, unsigned short port) { char port_str[16]; - INFO_LOG(SCENET, "PortManager::Remove(%d, %s)", port, protocol); + INFO_LOG(SCENET, "PortManager::Remove(%s, %d)", protocol, port); if (urls == NULL || urls->controlURL == NULL || urls->controlURL[0] == '\0') { if (g_Config.bEnableUPnP) WARN_LOG(SCENET, "PortManager::Remove - the init was not done !"); diff --git a/Core/Util/PortManager.h b/Core/Util/PortManager.h index 9a4cdedf05..85a285a5eb 100644 --- a/Core/Util/PortManager.h +++ b/Core/Util/PortManager.h @@ -69,19 +69,19 @@ public: // Get UPnP Initialization status int GetInitState(); - // Add a port & protocol (TCP, UDP or vendor-defined) to map for forwarding - bool Add(unsigned short port, const char* protocol); + // Add a port & protocol (TCP, UDP or vendor-defined) to map for forwarding (intport = 0 : same as [external] port) + bool Add(const char* protocol, unsigned short port, unsigned short intport = 0); - // Remove a port mapping - bool Remove(unsigned short port, const char* protocol); + // Remove a port mapping (external port) + bool Remove(const char* protocol, unsigned short port); - // Removes any lingering mapped ports from previous crashes + // Removes any lingering mapped ports created by PPSSPP from previous crashes bool Clear(); // Restore ports mapped by others that were taken by PPSSPP, better used after Clear() bool Restore(); - // Get port list mapped by PPSSPP for current LAN IP & others + // Get port lists mapped by PPSSPP for current LAN IP & other's applications bool RefreshPortList(); protected: diff --git a/UI/GameSettingsScreen.cpp b/UI/GameSettingsScreen.cpp index 4090861c53..b26cb38035 100644 --- a/UI/GameSettingsScreen.cpp +++ b/UI/GameSettingsScreen.cpp @@ -690,7 +690,6 @@ void GameSettingsScreen::CreateViews() { networkingSettings->Add(new ChoiceWithValueDisplay(&g_Config.proAdhocServer, n->T("Change proAdhocServer Address"), (const char *)nullptr))->OnClick.Handle(this, &GameSettingsScreen::OnChangeproAdhocServerAddress); networkingSettings->Add(new CheckBox(&g_Config.bEnableAdhocServer, n->T("Enable built-in PRO Adhoc Server", "Enable built-in PRO Adhoc Server"))); - networkingSettings->Add(new CheckBox(&g_Config.bEnableUPnP, n->T("Enable UPnP", "Enable UPnP (need a few seconds to detect)"))); networkingSettings->Add(new ChoiceWithValueDisplay(&g_Config.sMACAddress, n->T("Change Mac Address"), (const char *)nullptr))->OnClick.Handle(this, &GameSettingsScreen::OnChangeMacAddress); static const char* wlanChannels[] = { "Auto", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" }; auto wlanChannelChoice = networkingSettings->Add(new PopupMultiChoice(&g_Config.iWlanAdhocChannel, gr->T("WLAN Channel"), wlanChannels, 0, ARRAY_SIZE(wlanChannels), gr->GetName(), screenManager())); @@ -698,8 +697,12 @@ void GameSettingsScreen::CreateViews() { wlanChannelChoice->HideChoice(i+2); wlanChannelChoice->HideChoice(i+7); } - networkingSettings->Add(new PopupSliderChoice(&g_Config.iPortOffset, 0, 60000, n->T("Port offset", "Port offset(0 = PSP compatibility)"), 100, screenManager())); - networkingSettings->Add(new PopupSliderChoice(&g_Config.iMinTimeout, 1, 15000, n->T("Minimum Timeout", "Minimum Timeout (override low latency communication in milliseconds)"), 100, screenManager())); + networkingSettings->Add(new PopupSliderChoice(&g_Config.iPortOffset, 0, 60000, n->T("Port offset", "Port offset (0 = PSP compatibility)"), 100, screenManager())); + networkingSettings->Add(new PopupSliderChoice(&g_Config.iMinTimeout, 1, 15000, n->T("Minimum Timeout", "Minimum Timeout (override low latency in ms)"), 100, screenManager())); + + networkingSettings->Add(new ItemHeader(n->T("UPnP"))); + networkingSettings->Add(new CheckBox(&g_Config.bEnableUPnP, n->T("Enable UPnP", "Enable UPnP (need a few seconds to detect)"))); + networkingSettings->Add(new CheckBox(&g_Config.bUPnPUseOriginalPort, n->T("UPnP use original port", "UPnP use original port (PSP compatibility)")))->SetEnabledPtr(&g_Config.bEnableUPnP); networkingSettings->Add(new ItemHeader(n->T("Chat"))); networkingSettings->Add(new CheckBox(&g_Config.bEnableNetworkChat, n->T("Enable network chat", "Enable network chat"))); From 68fa15784c31cf3e3a9d0dd8432f2c5dc2fe53cb Mon Sep 17 00:00:00 2001 From: ANR2ME Date: Sun, 22 Mar 2020 03:08:01 +0700 Subject: [PATCH 2/7] Fixed UPnP port opened by PPSSPP detection, and Updated PortManager to be compliant to general purpose usage --- Core/HLE/sceNet.cpp | 8 +++++--- Core/Util/PortManager.cpp | 37 +++++++++++++++++++++---------------- Core/Util/PortManager.h | 8 ++++---- 3 files changed, 30 insertions(+), 23 deletions(-) diff --git a/Core/HLE/sceNet.cpp b/Core/HLE/sceNet.cpp index 7a04f827cc..85077c1afa 100644 --- a/Core/HLE/sceNet.cpp +++ b/Core/HLE/sceNet.cpp @@ -130,7 +130,8 @@ void __NetInit() { // Only initialize when UPnP is enabled since it takes a few seconds to detect UPnP device (may affect people who don't have UPnP device) if (g_Config.bEnableUPnP) { - g_PortManager.Init(); + // TODO: May be we should initialize & cleanup somewhere else than here for PortManager to be used as general purpose for whatever port forwarding PPSSPP needed + g_PortManager.Initialize(); } __ResetInitNetLib(); @@ -148,10 +149,11 @@ void __NetShutdown() { __ResetInitNetLib(); - if (g_Config.bEnableUPnP) { + // Since PortManager supposed to be general purpose for whatever port forwarding PPSSPP needed, may be we shouldn't clear & restore ports in here? But currently there is an issue with UPnP functions used in PortManager's destructor :( + if (g_PortManager.GetInitState() == UPNP_INITSTATE_DONE) { g_PortManager.Clear(); g_PortManager.Restore(); - g_PortManager.Deinit(); + g_PortManager.Terminate(); } } diff --git a/Core/Util/PortManager.cpp b/Core/Util/PortManager.cpp index 8e25cdca37..0ba1f2a83b 100644 --- a/Core/Util/PortManager.cpp +++ b/Core/Util/PortManager.cpp @@ -46,12 +46,13 @@ PortManager::PortManager(): } PortManager::~PortManager() { + // FIXME: It seems using any UPnP functions in this destructor that gets triggered when exiting PPSSPP will resulting to UPNPCOMMAND_HTTP_ERROR :( Did miniUPnPc library already shutted down at this point? Clear(); Restore(); - Deinit(); + Terminate(); } -void PortManager::Deinit() { +void PortManager::Terminate() { if (urls) { FreeUPNPUrls(urls); free(urls); @@ -67,10 +68,10 @@ void PortManager::Deinit() { m_defaultDesc.clear(); m_leaseDuration.clear(); m_LocalPort = UPNP_LOCAL_PORT_ANY; - m_InitState = UPNP_INITSTATE_DONE; + m_InitState = UPNP_INITSTATE_NONE; } -bool PortManager::Init(const unsigned int timeout) { +bool PortManager::Initialize(const unsigned int timeout) { // Windows: Assuming WSAStartup already called beforehand struct UPNPDev* devlist; struct UPNPDev* dev; @@ -95,12 +96,11 @@ bool PortManager::Init(const unsigned int timeout) { WARN_LOG(SCENET, "PortManager - Initialization already in progress"); return false; } - // We should redetect UPnP just in case the player switched to a different network in the middle - /*case UPNP_INITSTATE_DONE: { + // Should we redetect UPnP? just in case the player switched to a different network in the middle + case UPNP_INITSTATE_DONE: { WARN_LOG(SCENET, "PortManager - Already Initialized"); - return false; + return true; } - */ default: break; } @@ -153,7 +153,7 @@ bool PortManager::Init(const unsigned int timeout) { // Using Game ID & Player Name as default description for mapping std::string gameID = g_paramSFO.GetDiscID(); - m_defaultDesc = "PPSSPP:" + gameID + ":" + g_Config.sNickName; + m_defaultDesc = "PPSSPP:" + gameID + ":" + g_Config.sNickName; // Some routers may automatically prefixed it with "UPnP:" freeUPNPDevlist(devlist); @@ -212,7 +212,7 @@ bool PortManager::Add(const char* protocol, unsigned short port, unsigned short if (r == UPNPCOMMAND_HTTP_ERROR) { auto n = GetI18NCategory("Networking"); host->NotifyUserMessage(n->T("UPnP need to be reinitialized"), 6.0f, 0x0000ff); - Deinit(); // Most of the time errors occurred because the router is no longer reachable (ie. changed networks) so we should invalidate the state to prevent further lags due to timeouts + Terminate(); // Most of the time errors occurred because the router is no longer reachable (ie. changed networks) so we should invalidate the state to prevent further lags due to timeouts return false; } } @@ -240,7 +240,7 @@ bool PortManager::Remove(const char* protocol, unsigned short port) { if (r == UPNPCOMMAND_HTTP_ERROR) { auto n = GetI18NCategory("Networking"); host->NotifyUserMessage(n->T("UPnP need to be reinitialized"), 6.0f, 0x0000ff); - Deinit(); // Most of the time errors occurred because the router is no longer reachable (ie. changed networks) so we should invalidate the state to prevent further lags due to timeouts + Terminate(); // Most of the time errors occurred because the router is no longer reachable (ie. changed networks) so we should invalidate the state to prevent further lags due to timeouts return false; } } @@ -316,8 +316,9 @@ bool PortManager::Clear() { do { snprintf(index, 6, "%d", i); rHost[0] = '\0'; enabled[0] = '\0'; - duration[0] = '\0'; desc[0] = '\0'; + duration[0] = '\0'; desc[0] = '\0'; protocol[0] = '\0'; extPort[0] = '\0'; intPort[0] = '\0'; intAddr[0] = '\0'; + // May gets UPNPCOMMAND_HTTP_ERROR when called while exiting PPSSPP (ie. used in destructor) r = UPNP_GetGenericPortMappingEntry(urls->controlURL, datas->first.servicetype, index, @@ -325,7 +326,7 @@ bool PortManager::Clear() { protocol, desc, enabled, rHost, duration); // Only removes port mappings created by PPSSPP for current LAN IP - if (r == 0 && intAddr == m_lanip && std::strncmp(desc, "PPSSPP", 6) == 0) { + if (r == 0 && intAddr == m_lanip && std::string(desc).find("PPSSPP:") != std::string::npos) { int r2 = UPNP_DeletePortMapping(urls->controlURL, datas->first.servicetype, extPort, protocol, rHost); if (r2 != 0) { @@ -371,7 +372,7 @@ bool PortManager::RefreshPortList() { do { snprintf(index, 6, "%d", i); rHost[0] = '\0'; enabled[0] = '\0'; - duration[0] = '\0'; desc[0] = '\0'; + duration[0] = '\0'; desc[0] = '\0'; protocol[0] = '\0'; extPort[0] = '\0'; intPort[0] = '\0'; intAddr[0] = '\0'; r = UPNP_GetGenericPortMappingEntry(urls->controlURL, datas->first.servicetype, @@ -380,13 +381,17 @@ bool PortManager::RefreshPortList() { protocol, desc, enabled, rHost, duration); if (r == 0) { + std::string desc_str = std::string(desc); + // Some router might prefix the description with "UPnP:" so we may need to truncate it to prevent it from getting multiple prefix when restored later + if (desc_str.find("UPnP:") == 0) + desc_str = desc_str.substr(5); // Only include port mappings created by PPSSPP for current LAN IP - if (intAddr == m_lanip && std::strncmp(desc, "PPSSPP", 6) == 0) { + if (intAddr == m_lanip && desc_str.find("PPSSPP:") != std::string::npos) { m_portList.push_back({ extPort, protocol }); } // Port mappings belong to others that might be taken by PPSSPP later else { - m_otherPortList.push_back({ false, protocol, extPort, intPort, intAddr, rHost, desc, duration, enabled }); + m_otherPortList.push_back({ false, protocol, extPort, intPort, intAddr, rHost, desc_str, duration, enabled }); } } i++; diff --git a/Core/Util/PortManager.h b/Core/Util/PortManager.h index 85a285a5eb..37040218dc 100644 --- a/Core/Util/PortManager.h +++ b/Core/Util/PortManager.h @@ -61,10 +61,10 @@ public: // Initialize UPnP // timeout: milliseconds to wait for a router to respond (default = 2000 ms) - bool Init(const unsigned int timeout = 2000); + bool Initialize(const unsigned int timeout = 2000); // Uninitialize/Reset the state - void Deinit(); + void Terminate(); // Get UPnP Initialization status int GetInitState(); @@ -75,13 +75,13 @@ public: // Remove a port mapping (external port) bool Remove(const char* protocol, unsigned short port); - // Removes any lingering mapped ports created by PPSSPP from previous crashes + // Removes any lingering mapped ports created by PPSSPP (including from previous crashes) bool Clear(); // Restore ports mapped by others that were taken by PPSSPP, better used after Clear() bool Restore(); - // Get port lists mapped by PPSSPP for current LAN IP & other's applications + // Retrieves port lists mapped by PPSSPP for current LAN IP & other's applications bool RefreshPortList(); protected: From 65bc68609c11f8550e7f6150d88217b9597460c2 Mon Sep 17 00:00:00 2001 From: ANR2ME Date: Sun, 22 Mar 2020 12:08:17 +0700 Subject: [PATCH 3/7] Added an option to Disable Nagle Algorithm (Enable TCP No Delay) --- Core/Config.cpp | 1 + Core/Config.h | 1 + Core/HLE/sceNetAdhoc.cpp | 6 +++--- UI/GameSettingsScreen.cpp | 1 + 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Core/Config.cpp b/Core/Config.cpp index 3bc22a4a20..0a4ada08f4 100644 --- a/Core/Config.cpp +++ b/Core/Config.cpp @@ -958,6 +958,7 @@ static ConfigSetting networkSettings[] = { ConfigSetting("proAdhocServer", &g_Config.proAdhocServer, "myneighborsushicat.com", true, true), ConfigSetting("PortOffset", &g_Config.iPortOffset, 0, true, true), ConfigSetting("MinTimeout", &g_Config.iMinTimeout, 1, true, true), + ConfigSetting("TCPNoDelay", &g_Config.bTCPNoDelay, false, true, true), ConfigSetting("EnableUPnP", &g_Config.bEnableUPnP, false, true, true), ConfigSetting("UPnPUseOriginalPort", &g_Config.bUPnPUseOriginalPort, true, true, true), diff --git a/Core/Config.h b/Core/Config.h index 5bd145c601..03e3b34584 100644 --- a/Core/Config.h +++ b/Core/Config.h @@ -411,6 +411,7 @@ public: std::string proAdhocServer; bool bEnableWlan; bool bEnableAdhocServer; + bool bTCPNoDelay; bool bEnableUPnP; bool bUPnPUseOriginalPort; int iPortOffset; diff --git a/Core/HLE/sceNetAdhoc.cpp b/Core/HLE/sceNetAdhoc.cpp index 28dca3b32b..dee0dd28eb 100644 --- a/Core/HLE/sceNetAdhoc.cpp +++ b/Core/HLE/sceNetAdhoc.cpp @@ -1917,7 +1917,7 @@ static int sceNetAdhocPtpOpen(const char *srcmac, int sport, const char *dstmac, setSockTimeout(tcpsocket, SO_SNDTIMEO, rexmt_int); // Disable Nagle Algo to send immediately. Or may be we shouldn't disable Nagle since there is PtpFlush function? - //setSockNoDelay(tcpsocket, 1); + if (g_Config.bTCPNoDelay) setSockNoDelay(tcpsocket, 1); // Binding Information for local Port sockaddr_in addr; @@ -2107,7 +2107,7 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int setsockopt(newsocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&one, sizeof(one)); // Disable Nagle Algo to send immediately. Or may be we shouldn't disable Nagle since there is PtpFlush function? - //setSockNoDelay(newsocket, 1); + if (g_Config.bTCPNoDelay) setSockNoDelay(newsocket, 1); // Grab Local Address if (getsockname(newsocket, (sockaddr *)&local, &locallen) == 0) { @@ -2444,7 +2444,7 @@ static int sceNetAdhocPtpListen(const char *srcmac, int sport, int bufsize, int setSockTimeout(tcpsocket, SO_RCVTIMEO, rexmt_int); // Disable Nagle Algo to send immediately. Or may be we shouldn't disable Nagle since there is PtpFlush function? - //setSockNoDelay(tcpsocket, 1); + if (g_Config.bTCPNoDelay) setSockNoDelay(tcpsocket, 1); // Binding Information for local Port sockaddr_in addr; diff --git a/UI/GameSettingsScreen.cpp b/UI/GameSettingsScreen.cpp index b26cb38035..9d1012f97b 100644 --- a/UI/GameSettingsScreen.cpp +++ b/UI/GameSettingsScreen.cpp @@ -699,6 +699,7 @@ void GameSettingsScreen::CreateViews() { } networkingSettings->Add(new PopupSliderChoice(&g_Config.iPortOffset, 0, 60000, n->T("Port offset", "Port offset (0 = PSP compatibility)"), 100, screenManager())); networkingSettings->Add(new PopupSliderChoice(&g_Config.iMinTimeout, 1, 15000, n->T("Minimum Timeout", "Minimum Timeout (override low latency in ms)"), 100, screenManager())); + networkingSettings->Add(new CheckBox(&g_Config.bTCPNoDelay, n->T("TCP No Delay", "TCP No Delay (faster TCP)"))); networkingSettings->Add(new ItemHeader(n->T("UPnP"))); networkingSettings->Add(new CheckBox(&g_Config.bEnableUPnP, n->T("Enable UPnP", "Enable UPnP (need a few seconds to detect)"))); From e21ea719e97e486f1092b7ac252c05fc8fdb86ba Mon Sep 17 00:00:00 2001 From: ANR2ME Date: Mon, 23 Mar 2020 21:51:45 +0700 Subject: [PATCH 4/7] Fixed PortManager fallback Cleanup issue when exiting PPSSPP due to early WSACleanup --- Core/HLE/sceNet.cpp | 2 +- Core/Util/PortManager.cpp | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Core/HLE/sceNet.cpp b/Core/HLE/sceNet.cpp index 85077c1afa..2af5ff7f03 100644 --- a/Core/HLE/sceNet.cpp +++ b/Core/HLE/sceNet.cpp @@ -149,7 +149,7 @@ void __NetShutdown() { __ResetInitNetLib(); - // Since PortManager supposed to be general purpose for whatever port forwarding PPSSPP needed, may be we shouldn't clear & restore ports in here? But currently there is an issue with UPnP functions used in PortManager's destructor :( + // Since PortManager supposed to be general purpose for whatever port forwarding PPSSPP needed, may be we shouldn't clear & restore ports in here? it will be cleared and restored by PortManager's destructor when exiting PPSSPP anyway if (g_PortManager.GetInitState() == UPNP_INITSTATE_DONE) { g_PortManager.Clear(); g_PortManager.Restore(); diff --git a/Core/Util/PortManager.cpp b/Core/Util/PortManager.cpp index 0ba1f2a83b..34819be5bc 100644 --- a/Core/Util/PortManager.cpp +++ b/Core/Util/PortManager.cpp @@ -33,6 +33,7 @@ #include "Core/Util/PortManager.h" #include #include "i18n/i18n.h" +#include "net/resolve.h" PortManager g_PortManager; @@ -43,16 +44,20 @@ PortManager::PortManager(): m_InitState(UPNP_INITSTATE_NONE), m_LocalPort(UPNP_LOCAL_PORT_ANY), m_leaseDuration("43200") { + // Since WSAStartup can be used multiple times it should be safe to do this right? + net::Init(); } PortManager::~PortManager() { - // FIXME: It seems using any UPnP functions in this destructor that gets triggered when exiting PPSSPP will resulting to UPNPCOMMAND_HTTP_ERROR :( Did miniUPnPc library already shutted down at this point? + // FIXME: On Windows it seems using any UPnP functions in this destructor that gets triggered when exiting PPSSPP will resulting to UPNPCOMMAND_HTTP_ERROR due to early WSACleanup (miniupnpc was getting WSANOTINITIALISED internally) Clear(); Restore(); Terminate(); + net::Shutdown(); } void PortManager::Terminate() { + INFO_LOG(SCENET, "PortManager::Terminate()"); if (urls) { FreeUPNPUrls(urls); free(urls); @@ -83,9 +88,9 @@ bool PortManager::Initialize(const unsigned int timeout) { unsigned char ttl = 2; // defaulting to 2 int error = 0; - INFO_LOG(SCENET, "PortManager::Init(%d)", timeout); + INFO_LOG(SCENET, "PortManager::Initialize(%d)", timeout); if (!g_Config.bEnableUPnP) { - ERROR_LOG(SCENET, "PortManager::Init - UPnP is Disabled on Networking Settings"); + ERROR_LOG(SCENET, "PortManager::Initialize - UPnP is Disabled on Networking Settings"); return false; } From 1d30a9efec770c99e6620d8f407da885aa72f5ed Mon Sep 17 00:00:00 2001 From: ANR2ME Date: Thu, 26 Mar 2020 16:10:50 +0700 Subject: [PATCH 5/7] Fix possible crash issue during Networking Cleanup --- Core/HLE/sceNet.cpp | 35 +++--- Core/HLE/sceNet.h | 2 + Core/HLE/sceNetAdhoc.cpp | 224 +++++++++++++++++++++++---------------- Core/HLE/sceNetAdhoc.h | 5 +- 4 files changed, 157 insertions(+), 109 deletions(-) diff --git a/Core/HLE/sceNet.cpp b/Core/HLE/sceNet.cpp index 2af5ff7f03..fbe60def3d 100644 --- a/Core/HLE/sceNet.cpp +++ b/Core/HLE/sceNet.cpp @@ -138,14 +138,8 @@ void __NetInit() { } void __NetShutdown() { - // Checks to avoid confusing logspam - if (netAdhocctlInited) sceNetAdhocctlTerm(); - if (netAdhocInited) sceNetAdhocTerm(); - - if (netApctlInited) sceNetApctlTerm(); - if (netInetInited) sceNetInetTerm(); - - if (netInited) sceNetTerm(); + // Network Cleanup + Net_Term(); __ResetInitNetLib(); @@ -222,13 +216,14 @@ static inline void FreeUser(u32 &addr) { addr = 0; } -static u32 sceNetTerm() { +u32 Net_Term() { // May also need to Terminate netAdhocctl and netAdhoc to free some resources & threads, since the game (ie. GTA:VCS, Wipeout Pulse, etc) might not called them before calling sceNetTerm and causing them to behave strangely on the next sceNetInit & sceNetAdhocInit - if (netAdhocctlInited) sceNetAdhocctlTerm(); - if (netAdhocInited) sceNetAdhocTerm(); + NetAdhocctl_Term(); + NetAdhoc_Term(); - if (netApctlInited) sceNetApctlTerm(); - if (netInetInited) sceNetInetTerm(); + // TODO: Not implemented yet + //sceNetApctl_Term(); + //NetInet_Term(); // Library is initialized if (netInited) { @@ -249,15 +244,21 @@ static u32 sceNetTerm() { // Library shutdown } - WARN_LOG(SCENET, "sceNetTerm()"); - netInited = false; FreeUser(netPoolAddr); FreeUser(netThread1Addr); FreeUser(netThread2Addr); + netInited = false; + + return 0; +} + +static u32 sceNetTerm() { + WARN_LOG(SCENET, "sceNetTerm()"); + int retval = Net_Term(); // Give time to make sure everything are cleaned up - hleDelayResult(0, "give time to init/cleanup", adhocEventDelayMS * 1000); - return 0; + hleDelayResult(retval, "give time to init/cleanup", adhocEventDelayMS * 1000); + return retval; } /* diff --git a/Core/HLE/sceNet.h b/Core/HLE/sceNet.h index 2f7a9044bd..84615a2427 100644 --- a/Core/HLE/sceNet.h +++ b/Core/HLE/sceNet.h @@ -109,6 +109,8 @@ void __NetInit(); void __NetShutdown(); void __NetDoState(PointerWrap &p); +u32 Net_Term(); + int sceNetInetPoll(void *fds, u32 nfds, int timeout); int sceNetInetTerm(); int sceNetApctlTerm(); diff --git a/Core/HLE/sceNetAdhoc.cpp b/Core/HLE/sceNetAdhoc.cpp index dee0dd28eb..8c34e64f0d 100644 --- a/Core/HLE/sceNetAdhoc.cpp +++ b/Core/HLE/sceNetAdhoc.cpp @@ -954,27 +954,13 @@ int sceNetAdhocPollSocket(u32 socketStructAddr, int count, int timeout, int nonb return ERROR_NET_ADHOC_NOT_INITIALIZED; } -/** - * Adhoc Emulator PDP Socket Delete - * @param id Socket File Descriptor - * @param flag Bitflags (Unused) - * @return 0 on success or... ADHOC_INVALID_ARG, ADHOC_NOT_INITIALIZED, ADHOC_INVALID_SOCKET_ID - */ -static int sceNetAdhocPdpDelete(int id, int unknown) { - // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? - INFO_LOG(SCENET, "sceNetAdhocPdpDelete(%d, %d) at %08x", id, unknown, currentMIPS->pc); - /* - if (!g_Config.bEnableWlan) { - return 0; - } - */ - +int NetAdhocPdp_Delete(int id, int unknown) { // Library is initialized if (netAdhocInited) { // Valid Arguments if (id > 0 && id <= 255) { // Cast Socket - SceNetAdhocPdpStat * sock = pdp[id - 1]; + SceNetAdhocPdpStat* sock = pdp[id - 1]; // Valid Socket if (sock != NULL) { @@ -1007,6 +993,24 @@ static int sceNetAdhocPdpDelete(int id, int unknown) { return ERROR_NET_ADHOC_NOT_INITIALIZED; } +/** + * Adhoc Emulator PDP Socket Delete + * @param id Socket File Descriptor + * @param flag Bitflags (Unused) + * @return 0 on success or... ADHOC_INVALID_ARG, ADHOC_NOT_INITIALIZED, ADHOC_INVALID_SOCKET_ID + */ +static int sceNetAdhocPdpDelete(int id, int unknown) { + // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? + INFO_LOG(SCENET, "sceNetAdhocPdpDelete(%d, %d) at %08x", id, unknown, currentMIPS->pc); + /* + if (!g_Config.bEnableWlan) { + return 0; + } + */ + + return NetAdhocPdp_Delete(id, unknown); +} + static int sceNetAdhocctlGetAdhocId(u32 productStructAddr) { ERROR_LOG(SCENET, "UNIMPL sceNetAdhocctlGetAdhocId(%08x)", productStructAddr); @@ -1230,12 +1234,7 @@ static u32 sceNetAdhocctlAddHandler(u32 handlerPtr, u32 handlerArg) { return retval; } -static u32 sceNetAdhocctlDisconnect() { - // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? - char grpName[9] = { 0 }; - memcpy(grpName, parameter.group_name.data, ADHOCCTL_GROUPNAME_LEN); // Copied to null-terminated var to prevent unexpected behaviour on Logs - INFO_LOG(SCENET, "sceNetAdhocctlDisconnect() at %08x [group=%s]", currentMIPS->pc, grpName); - +u32 NetAdhocctl_Disconnect() { // Library initialized if (netAdhocctlInited) { // Connected State (Adhoc Mode) @@ -1253,7 +1252,7 @@ static u32 sceNetAdhocctlDisconnect() { //_acquireNetworkLock(); // Send Disconnect Request Packet - int iResult = send(metasocket, (const char *)&opcode, 1, 0); + int iResult = send(metasocket, (const char*)&opcode, 1, 0); if (iResult == SOCKET_ERROR) { ERROR_LOG(SCENET, "Socket error (%i) when sending", errno); } @@ -1283,9 +1282,9 @@ static u32 sceNetAdhocctlDisconnect() { // Multithreading Unlock //peerlock.unlock(); - + // Notify Event Handlers (even if we weren't connected, not doing this will freeze games like God Eater, which expect this behaviour) - notifyAdhocctlHandlers(ADHOCCTL_EVENT_DISCONNECT, 0); + notifyAdhocctlHandlers(ADHOCCTL_EVENT_DISCONNECT, 0); hleCheckCurrentCallbacks(); // Return Success, some games might ignore returned value and always treat it as success, otherwise repeatedly calling this function @@ -1296,6 +1295,15 @@ static u32 sceNetAdhocctlDisconnect() { return 0; //ERROR_NET_ADHOC_NOT_INITIALIZED; // Wipeout Pulse will repeatedly calling this function if returned value is ERROR_NET_ADHOC_NOT_INITIALIZED } +static u32 sceNetAdhocctlDisconnect() { + // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? + char grpName[9] = { 0 }; + memcpy(grpName, parameter.group_name.data, ADHOCCTL_GROUPNAME_LEN); // Copied to null-terminated var to prevent unexpected behaviour on Logs + INFO_LOG(SCENET, "sceNetAdhocctlDisconnect() at %08x [group=%s]", currentMIPS->pc, grpName); + + return NetAdhocctl_Disconnect(); +} + static u32 sceNetAdhocctlDelHandler(u32 handlerID) { if (adhocctlHandlers.find(handlerID) != adhocctlHandlers.end()) { adhocctlHandlers.erase(handlerID); @@ -1307,14 +1315,11 @@ static u32 sceNetAdhocctlDelHandler(u32 handlerID) { return 0; } -int sceNetAdhocctlTerm() { - // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? - INFO_LOG(SCENET, "sceNetAdhocctlTerm()"); - - //if (netAdhocMatchingInited) sceNetAdhocMatchingTerm(); - +int NetAdhocctl_Term() { if (netAdhocctlInited) { - if (threadStatus != ADHOCCTL_STATE_DISCONNECTED) sceNetAdhocctlDisconnect(); + if (threadStatus != ADHOCCTL_STATE_DISCONNECTED) + NetAdhocctl_Disconnect(); + if (networkInited) { // Terminate Adhoc Threads friendFinderRunning = false; @@ -1345,6 +1350,15 @@ int sceNetAdhocctlTerm() { return 0; } +int sceNetAdhocctlTerm() { + // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? + INFO_LOG(SCENET, "sceNetAdhocctlTerm()"); + + //if (netAdhocMatchingInited) NetAdhocMatching_Term(); + + return NetAdhocctl_Term(); +} + static int sceNetAdhocctlGetNameByAddr(const char *mac, u32 nameAddr) { char tmpmac[18]; DEBUG_LOG(SCENET, "UNTESTED sceNetAdhocctlGetNameByAddr(%s, %08x)", mac2str((SceNetEtherAddr*)mac, tmpmac), nameAddr); @@ -1669,12 +1683,12 @@ int sceNetAdhocctlCreateEnterGameModeMin(const char *group_name, int game_type, return sceNetAdhocctlCreateEnterGameMode(group_name, game_type, num_members, membersAddr, timeout, flag); //0; } -int sceNetAdhocTerm() { - // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup all the sockets right? - +int NetAdhoc_Term() { // Since Adhocctl & AdhocMatching uses Sockets & Threads we should terminate them also to release their resources - if (netAdhocMatchingInited) sceNetAdhocMatchingTerm(); - if (netAdhocctlInited) sceNetAdhocctlTerm(); + if (netAdhocMatchingInited) + NetAdhocMatching_Term(); + if (netAdhocctlInited) + NetAdhocctl_Term(); // Library is initialized if (netAdhocInited) { @@ -1693,14 +1707,23 @@ int sceNetAdhocTerm() { // Unload Internet Modules (Just keep it in memory... unloading crashes?!) // if (_manage_modules != 0) sceUtilityUnloadModule(PSP_MODULE_NET_INET); // Library shutdown - + netAdhocInited = false; - return hleLogSuccessInfoI(SCENET, 0); - } else { + //return hleLogSuccessInfoI(SCENET, 0); + } + /*else { // TODO: Reportedly returns SCE_KERNEL_ERROR_LWMUTEX_NOT_FOUND in some cases? // Only seen returning 0 in tests. return hleLogWarning(SCENET, 0, "already uninitialized"); - } + }*/ + + return 0; +} + +int sceNetAdhocTerm() { + // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup all the sockets right? + + return hleLogSuccessInfoI(SCENET, NetAdhoc_Term()); } static int sceNetAdhocGetPdpStat(u32 structSize, u32 structAddr) { @@ -2338,6 +2361,39 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) { return ERROR_NET_ADHOC_NOT_INITIALIZED; } +int NetAdhocPtp_Close(int id, int unknown) { + // Library is initialized + if (netAdhocInited) { + // Valid Arguments & Atleast one Socket + if (id > 0 && id <= 255 && ptp[id - 1] != NULL) { + // Cast Socket + SceNetAdhocPtpStat* socket = ptp[id - 1]; + + // Close Connection + closesocket(socket->id); + + // Remove Port Forward from Router + //sceNetPortClose("TCP", socket->lport); + //g_PortManager.Remove(IP_PROTOCOL_TCP, isOriPort ? socket->lport : socket->lport + portOffset); // Let's not remove mapping in real-time as it could cause lags/disconnection when joining a room with slow routers + + // Free Memory + free(socket); + + // Free Reference + ptp[id - 1] = NULL; + + // Success + return 0; + } + + // Invalid Argument + return ERROR_NET_ADHOC_INVALID_SOCKET_ID; + } + + // Library is uninitialized + return ERROR_NET_ADHOC_NOT_INITIALIZED; +} + /** * Adhoc Emulator PTP Socket Closer * @param id Socket File Descriptor @@ -2346,39 +2402,11 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) { */ static int sceNetAdhocPtpClose(int id, int unknown) { INFO_LOG(SCENET,"sceNetAdhocPtpClose(%d,%d) at %08x",id,unknown,currentMIPS->pc); - if (!g_Config.bEnableWlan) { + /*if (!g_Config.bEnableWlan) { return 0; - } - // Library is initialized - if (netAdhocInited) { - // Valid Arguments & Atleast one Socket - if (id > 0 && id <= 255 && ptp[id - 1] != NULL) { - // Cast Socket - SceNetAdhocPtpStat * socket = ptp[id - 1]; - - // Close Connection - closesocket(socket->id); - - // Remove Port Forward from Router - //sceNetPortClose("TCP", socket->lport); - //g_PortManager.Remove(IP_PROTOCOL_TCP, isOriPort ? socket->lport : socket->lport + portOffset); // Let's not remove mapping in real-time as it could cause lags/disconnection when joining a room with slow routers - - // Free Memory - free(socket); - - // Free Reference - ptp[id - 1] = NULL; - - // Success - return 0; - } - - // Invalid Argument - return ERROR_NET_ADHOC_INVALID_SOCKET_ID; - } + }*/ - // Library is uninitialized - return ERROR_NET_ADHOC_NOT_INITIALIZED; + return NetAdhocPtp_Close(id, unknown); } @@ -2842,10 +2870,8 @@ int sceNetAdhocGetSocketAlert(int id, u32 flagPtr) { return 0; } -int sceNetAdhocMatchingStop(int matchingId) { - WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingStop(%i) at %08x", matchingId, currentMIPS->pc); - - SceNetAdhocMatchingContext * item = findMatchingContext(matchingId); +int NetAdhocMatching_Stop(int matchingId) { + SceNetAdhocMatchingContext* item = findMatchingContext(matchingId); if (item != NULL) { item->inputRunning = false; @@ -2887,17 +2913,21 @@ int sceNetAdhocMatchingStop(int matchingId) { return 0; } -int sceNetAdhocMatchingDelete(int matchingId) { - // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? +int sceNetAdhocMatchingStop(int matchingId) { + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingStop(%i) at %08x", matchingId, currentMIPS->pc); + return NetAdhocMatching_Stop(matchingId); +} + +int NetAdhocMatching_Delete(int matchingId) { // Previous Context Reference - SceNetAdhocMatchingContext * prev = NULL; + SceNetAdhocMatchingContext* prev = NULL; // Multithreading Lock peerlock.lock(); //contextlock.lock(); // Context Pointer - SceNetAdhocMatchingContext * item = contexts; + SceNetAdhocMatchingContext* item = contexts; // Iterate contexts for (; item != NULL; item = item->next) { @@ -2911,7 +2941,7 @@ int sceNetAdhocMatchingDelete(int matchingId) { // Stop it first if it's still running if (item->running) { - sceNetAdhocMatchingStop(matchingId); + NetAdhocMatching_Stop(matchingId); } // Delete the Fake PSP Thread //__KernelDeleteThread(item->matching_thid, SCE_KERNEL_ERROR_THREAD_TERMINATED, "AdhocMatching deleted"); @@ -2919,7 +2949,7 @@ int sceNetAdhocMatchingDelete(int matchingId) { // Make sure nobody locking/using the socket item->socketlock->lock(); // Delete the socket - sceNetAdhocPdpDelete(item->socket, 0); // item->connected = (sceNetAdhocPdpDelete(item->socket, 0) < 0); + NetAdhocPdp_Delete(item->socket, 0); // item->connected = (sceNetAdhocPdpDelete(item->socket, 0) < 0); item->socketlock->unlock(); // Free allocated memories free(item->hello); @@ -2928,10 +2958,10 @@ int sceNetAdhocMatchingDelete(int matchingId) { // Destroy locks item->eventlock->lock(); // Make sure it's not locked when being deleted item->eventlock->unlock(); - delete item->eventlock; + delete item->eventlock; item->inputlock->lock(); // Make sure it's not locked when being deleted item->inputlock->unlock(); - delete item->inputlock; + delete item->inputlock; item->socketlock->lock(); // Make sure it's not locked when being deleted item->socketlock->unlock(); delete item->socketlock; @@ -2950,6 +2980,14 @@ int sceNetAdhocMatchingDelete(int matchingId) { // Multithreading Unlock peerlock.unlock(); //contextlock.unlock(); + return 0; +} + +int sceNetAdhocMatchingDelete(int matchingId) { + // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? + + NetAdhocMatching_Delete(matchingId); + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingDelete(%i) at %08x", matchingId, currentMIPS->pc); // Give a little time to make sure everything are cleaned up before the following AdhocMatchingCreate, Not too long tho, otherwise Naruto Ultimate Ninja Heroes 3 will have an issue @@ -2974,21 +3012,27 @@ int sceNetAdhocMatchingInit(u32 memsize) { return 0; } -int sceNetAdhocMatchingTerm() { - WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingTerm()"); - // Should we cleanup all created matching contexts first? just in case there are games that doesn't delete them before calling this +int NetAdhocMatching_Term() { if (netAdhocMatchingInited) { // Delete all Matching contexts SceNetAdhocMatchingContext* next = NULL; - SceNetAdhocMatchingContext * context = contexts; + SceNetAdhocMatchingContext* context = contexts; while (context != NULL) { next = context->next; - //if (context->running) sceNetAdhocMatchingStop(context->id); - sceNetAdhocMatchingDelete(context->id); + //if (context->running) NetAdhocMatching_Stop(context->id); + NetAdhocMatching_Delete(context->id); context = next; } contexts = NULL; } + + return 0; +} + +int sceNetAdhocMatchingTerm() { + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingTerm()"); + // Should we cleanup all created matching contexts first? just in case there are games that doesn't delete them before calling this + NetAdhocMatching_Term(); netAdhocMatchingInited = false; return 0; diff --git a/Core/HLE/sceNetAdhoc.h b/Core/HLE/sceNetAdhoc.h index e2e9a434a2..0577caac50 100644 --- a/Core/HLE/sceNetAdhoc.h +++ b/Core/HLE/sceNetAdhoc.h @@ -53,5 +53,6 @@ extern int adhocEventDelayMS; // This will affect the duration of "Connecting... extern std::recursive_mutex adhocEvtMtx; extern int IsAdhocctlInCB; -int sceNetAdhocctlTerm(); -int sceNetAdhocTerm(); +int NetAdhocMatching_Term(); +int NetAdhocctl_Term(); +int NetAdhoc_Term(); From df268453889ecf16261d39abf8fcca50038defc6 Mon Sep 17 00:00:00 2001 From: ANR2ME Date: Mon, 4 May 2020 21:44:40 +0700 Subject: [PATCH 6/7] Minor fixes --- Core/HLE/proAdhoc.cpp | 8 +++--- Core/HLE/proAdhoc.h | 6 +++-- Core/HLE/sceNet.cpp | 2 +- Core/HLE/sceNetAdhoc.cpp | 56 +++++++++++++++++++++------------------- 4 files changed, 37 insertions(+), 35 deletions(-) diff --git a/Core/HLE/proAdhoc.cpp b/Core/HLE/proAdhoc.cpp index 1bbbf61714..49806c1ce5 100644 --- a/Core/HLE/proAdhoc.cpp +++ b/Core/HLE/proAdhoc.cpp @@ -160,7 +160,7 @@ void addFriend(SceNetAdhocctlConnectPacketS2C * packet) { if (peer != NULL) { char tmpmac[18]; u32 tmpip = packet->ip; - WARN_LOG(SCENET, "Friend Peer Already Existed! Updating [%s][%s][%s]", packet->name.data, mac2str(&packet->mac, tmpmac), inet_ntoa(*(struct in_addr*)&tmpip)); //inet_ntoa(*(in_addr*)&packet->ip) + WARN_LOG(SCENET, "Friend Peer Already Existed! Updating [%s][%s][%s]", mac2str(&packet->mac, tmpmac), inet_ntoa(*(struct in_addr*)&tmpip), packet->name.data); //inet_ntoa(*(in_addr*)&packet->ip) peer->nickname = packet->name; peer->mac_addr = packet->mac; peer->ip_addr = packet->ip; @@ -1007,7 +1007,7 @@ void AfterMatchingMipsCall::run(MipsCall &call) { u32 v0 = currentMIPS->r[MIPS_REG_V0]; if (__IsInInterrupt()) ERROR_LOG(SCENET, "AfterMatchingMipsCall::run [ID=%i][Event=%d] is Returning Inside an Interrupt!", contextID, EventID); if (Memory::IsValidAddress(bufAddr)) userMemory.Free(bufAddr); - SetMatchingInCallback(context, false); + //SetMatchingInCallback(context, false); DEBUG_LOG(SCENET, "AfterMatchingMipsCall::run [ID=%i][Event=%d] [cbId: %u][retV0: %08x]", contextID, EventID, call.cbId, v0); //call.setReturnValue(v0); } @@ -1300,13 +1300,11 @@ int friendFinder(){ // Cast Packet SceNetAdhocctlConnectPacketS2C * packet = (SceNetAdhocctlConnectPacketS2C *)rx; - DEBUG_LOG(SCENET, "FriendFinder: OPCODE_CONNECT"); - // Fix strings with null-terminated packet->name.data[ADHOCCTL_NICKNAME_LEN - 1] = 0; // Log Incoming Peer - INFO_LOG(SCENET, "Incoming Peer Data..."); + INFO_LOG(SCENET, "FriendFinder: Incoming OPCODE_CONNECT [%s][%s][%s]", mac2str(&packet->mac), inet_ntoa(*(in_addr*)&packet->ip), packet->name.data); // Add User addFriend(packet); diff --git a/Core/HLE/proAdhoc.h b/Core/HLE/proAdhoc.h index c1d5fe8b25..4fa39b2690 100644 --- a/Core/HLE/proAdhoc.h +++ b/Core/HLE/proAdhoc.h @@ -479,12 +479,14 @@ typedef struct SceNetAdhocMatchingContext { SceUID matching_thid; // Event Caller Thread - std::thread eventThread; // s32_le event_thid; + std::thread eventThread; + //s32_le event_thid; bool eventRunning = false; bool IsMatchingInCB = false; // IO Handler Thread - std::thread inputThread; // s32_le input_thid; + std::thread inputThread; + //s32_le input_thid; bool inputRunning = false; // Event Caller Thread Message Stack diff --git a/Core/HLE/sceNet.cpp b/Core/HLE/sceNet.cpp index fbe60def3d..b001caeeed 100644 --- a/Core/HLE/sceNet.cpp +++ b/Core/HLE/sceNet.cpp @@ -274,7 +274,7 @@ static int sceNetInit(u32 poolSize, u32 calloutPri, u32 calloutStack, u32 netini // TODO: The correct behavior is actually to allocate more and leak the other threads/pool. // But we reset here for historic reasons (GTA:VCS potentially triggers this.) if (netInited) - sceNetTerm(); // This cleanup attempt might not worked when SaveState were loaded in the middle of multiplayer game and re-entering multiplayer, thus causing memory leaks & wasting binded ports. May be we shouldn't save/load "Inited" vars on SaveState? + Net_Term(); // This cleanup attempt might not worked when SaveState were loaded in the middle of multiplayer game and re-entering multiplayer, thus causing memory leaks & wasting binded ports. May be we shouldn't save/load "Inited" vars on SaveState? if (poolSize == 0) { return hleLogError(SCENET, SCE_KERNEL_ERROR_ILLEGAL_MEMSIZE, "invalid pool size"); diff --git a/Core/HLE/sceNetAdhoc.cpp b/Core/HLE/sceNetAdhoc.cpp index 8c34e64f0d..f12b4444ce 100644 --- a/Core/HLE/sceNetAdhoc.cpp +++ b/Core/HLE/sceNetAdhoc.cpp @@ -585,7 +585,8 @@ static int sceNetAdhocPdpSend(int id, const char *mac, u32 port, void *data, int SceNetAdhocctlPeerInfo * peer = friends; for (; peer != NULL; peer = peer->next) { // Does Skipping sending to timed out friends could cause desync when players moving group at the time MP game started? - //if (peer->last_recv == 0) continue; + if (peer->last_recv == 0) + continue; // Fill in Target Structure sockaddr_in target; @@ -736,10 +737,10 @@ static int sceNetAdhocPdpRecv(int id, void *addr, void * port, void *buf, void * *sport = ntohs(sin.sin_port) - portOffset; // Update last recv timestamp, may cause disconnection not detected properly tho - /*peerlock.lock(); + peerlock.lock(); auto peer = findFriend(&mac); if (peer != NULL) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled(); - peerlock.unlock();*/ + peerlock.unlock(); } // Free Network Lock @@ -785,10 +786,10 @@ static int sceNetAdhocPdpRecv(int id, void *addr, void * port, void *buf, void * *len = received; // Kurok homebrew seems to use the new value of len than returned value as data length // Update last recv timestamp, may cause disconnection not detected properly tho - /*peerlock.lock(); + peerlock.lock(); auto peer = findFriend(&mac); if (peer != NULL) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled(); - peerlock.unlock();*/ + peerlock.unlock(); // Free Network Lock //_freeNetworkLock(); @@ -1367,10 +1368,9 @@ static int sceNetAdhocctlGetNameByAddr(const char *mac, u32 nameAddr) { if (netAdhocctlInited) { // Valid Arguments - if (mac != NULL && nameAddr != 0) + if (mac != NULL && Memory::IsValidAddress(nameAddr)) { - SceNetAdhocctlNickname * nickname = NULL; - if (Memory::IsValidAddress(nameAddr)) nickname = (SceNetAdhocctlNickname *)Memory::GetPointer(nameAddr); + SceNetAdhocctlNickname * nickname = (SceNetAdhocctlNickname *)Memory::GetPointer(nameAddr); // Get Local MAC Address SceNetEtherAddr localmac; getLocalMac(&localmac); @@ -2733,10 +2733,10 @@ static int sceNetAdhocPtpRecv(int id, u32 dataAddr, u32 dataSizeAddr, int timeou *len = received; // Update last recv timestamp, may cause disconnection not detected properly tho - /*peerlock.lock(); + peerlock.lock(); auto peer = findFriend(&socket->paddr); if (peer != NULL) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled(); - peerlock.unlock();*/ + peerlock.unlock(); char tmpmac[18]; DEBUG_LOG(SCENET, "sceNetAdhocPtpRecv[%i:%u]: Received %u bytes from %s:%u", id, socket->lport, received, mac2str(&socket->paddr, tmpmac), socket->pport); @@ -3209,13 +3209,13 @@ static int sceNetAdhocMatchingStart(int matchingId, int evthPri, int evthStack, peer->state = PSP_ADHOC_MATCHING_PEER_P2P; }*/ - // Create & Start the Fake PSP Thread + // Create & Start the Fake PSP Thread ("matching_ev%d" and "matching_io%d") std::string thrname = std::string("MatchingThr") + std::to_string(matchingId); - item->matching_thid = __KernelCreateThread(thrname.c_str(), __KernelGetCurThreadModuleId(), matchingThreadHackAddr, evthPri, evthStack, PSP_THREAD_ATTR_USER, 0, false); - //item->matchingThread = new HLEHelperThread(thrname, "sceNetAdhocMatching", "AdhocMatchingFunc", inthPri, inthStack); + item->matching_thid = sceKernelCreateThread(thrname.c_str(), matchingThreadHackAddr, evthPri, evthStack, 0, 0); + //item->matchingThread = new HLEHelperThread(thrname.c_str(), "sceNetAdhocMatching", "__NetMatchingCallbacks", inthPri, inthStack); if (item->matching_thid > 0) { - __KernelStartThread(item->matching_thid, 0, 0); - //item->matchingThread->Start(0, 0); + sceKernelStartThread(item->matching_thid, 0, 0); //sceKernelStartThread(context->event_thid, sizeof(context), &context); + //item->matchingThread->Start(matchingId, 0); } //Create the threads @@ -4029,7 +4029,7 @@ int sceNetAdhocMatchingGetPoolStat(u32 poolstatPtr) { void __NetTriggerCallbacks() { std::lock_guard adhocGuard(adhocEvtMtx); - int delayus = 1000; + int delayus = 10000; auto params = adhocctlEvents.begin(); if (params != adhocctlEvents.end()) @@ -4047,14 +4047,15 @@ void __NetTriggerCallbacks() args[2] = it->second.argument; AfterAdhocMipsCall* after = (AfterAdhocMipsCall*)__KernelCreateAction(actionAfterAdhocMipsCall); after->SetData(it->first, flags, args[2]); - SetAdhocctlInCallback(true); - __KernelDirectMipsCall(it->second.entryPoint, after, args, 3, true); + //SetAdhocctlInCallback(true); + //__KernelDirectMipsCall(it->second.entryPoint, after, args, 3, true); + hleEnqueueCall(it->second.entryPoint, 3, args, after); } adhocctlEvents.pop_front(); if (flags == ADHOCCTL_EVENT_CONNECT) - delayus = (adhocEventDelayMS + 2*adhocExtraPollDelayMS) * 1000; + delayus = (adhocEventDelayMS + 2*adhocExtraPollDelayMS) * 1000; // May affects Dissidia 012 and GTA VCS else - delayus = (adhocEventPollDelayMS + 2*adhocExtraPollDelayMS) * 1000; //Added an extra delay to prevent I/O Timing method from causing disconnection + delayus = (adhocEventPollDelayMS + 2*adhocExtraPollDelayMS) * 1000; // Added an extra delay to prevent I/O Timing method from causing disconnection } } @@ -4062,10 +4063,10 @@ void __NetTriggerCallbacks() hleDelayResult(0, "Prevent Adhocctl thread from blocking", delayus); } -void __NetMatchingCallbacks() +void __NetMatchingCallbacks() //(int matchingId) { std::lock_guard adhocGuard(adhocEvtMtx); - int delayus = 1000; + int delayus = 10000; auto params = matchingEvents.begin(); if (params != matchingEvents.end()) @@ -4079,9 +4080,10 @@ void __NetMatchingCallbacks() AfterMatchingMipsCall* after = (AfterMatchingMipsCall*)__KernelCreateAction(actionAfterMatchingMipsCall); after->SetData(args[0], args[1], args[2]); //SetMatchingInCallback(context, true); - __KernelDirectMipsCall(args[5], after, args, 5, true); + //__KernelDirectMipsCall(args[5], after, args, 5, true); + hleEnqueueCall(args[5], 5, args, after); matchingEvents.pop_front(); - delayus = (adhocMatchingEventDelayMS + 2*adhocExtraPollDelayMS) * 1000; //Added an extra delay to prevent I/O Timing method from causing disconnection + delayus = (adhocMatchingEventDelayMS + 2*adhocExtraPollDelayMS) * 1000; // Added an extra delay to prevent I/O Timing method from causing disconnection } } @@ -4175,7 +4177,7 @@ static int sceNetAdhocctlGetPeerList(u32 sizeAddr, u32 bufAddr) { // Multithreading Lock peerlock.lock(); - bool excludeTimedout = false; //true; + bool excludeTimedout = true; // Length Calculation Mode if (buf == NULL) { int activePeers = getActivePeerCount(excludeTimedout); @@ -5457,7 +5459,7 @@ int matchingEventThread(int matchingId) } // Share CPU Time - sleep_ms(1); //10 //sceKernelDelayThread(10000); + sleep_ms(10); //1 //sceKernelDelayThread(10000); // Don't do anything if it's paused, otherwise the log will be flooded while (Core_IsStepping() && coreState != CORE_POWERDOWN && contexts != NULL && context->eventRunning) sleep_ms(1); @@ -5688,7 +5690,7 @@ int matchingInputThread(int matchingId) // TODO: The MatchingInput thread is usi handleTimeout(context); } // Share CPU Time - sleep_ms(1); //10 //sceKernelDelayThread(10000); + sleep_ms(10); //1 //sceKernelDelayThread(10000); // Don't do anything if it's paused, otherwise the log will be flooded while (Core_IsStepping() && coreState != CORE_POWERDOWN && contexts != NULL && context->inputRunning) sleep_ms(1); From 6695001b94332be30d9220f8d9280b79874213d7 Mon Sep 17 00:00:00 2001 From: ANR2ME Date: Mon, 25 May 2020 11:59:39 +0700 Subject: [PATCH 7/7] Fix timeout comparison --- Core/HLE/sceNetAdhoc.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Core/HLE/sceNetAdhoc.cpp b/Core/HLE/sceNetAdhoc.cpp index f12b4444ce..c69dd24dab 100644 --- a/Core/HLE/sceNetAdhoc.cpp +++ b/Core/HLE/sceNetAdhoc.cpp @@ -753,9 +753,9 @@ static int sceNetAdhocPdpRecv(int id, void *addr, void * port, void *buf, void * if (flag == 0) { // Simulate blocking behaviour with non-blocking socket - uint32_t starttime = (uint32_t)(real_time_now() * 1000.0); + uint32_t starttime = (uint32_t)(real_time_now() * 1000000.0); // Wait for Connection. On Windows: recvfrom on UDP can get error WSAECONNRESET when previous sendto's destination is unreachable (or destination port is not bound), may need to disable SIO_UDP_CONNRESET - while ((timeout == 0 || ((uint32_t)(real_time_now() * 1000.0) - starttime) < (uint32_t)timeout) && (received == SOCKET_ERROR) && (connectInProgress(error) || error == ECONNRESET)) { + while ((timeout == 0 || ((uint32_t)(real_time_now() * 1000000.0) - starttime) < (uint32_t)timeout) && (received == SOCKET_ERROR) && (connectInProgress(error) || error == ECONNRESET)) { received = recvfrom(socket->id, (char*)buf, *len, 0, (sockaddr*)&sin, &sinlen); error = errno; // Wait 1ms @@ -2096,10 +2096,10 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int // Blocking Behaviour if (!flag && newsocket == SOCKET_ERROR) { // Get Start Time - uint32_t starttime = (uint32_t)(real_time_now()*1000.0); + uint32_t starttime = (uint32_t)(real_time_now()*1000000.0); // Retry until Timeout hits - while ((timeout == 0 || ((uint32_t)(real_time_now()*1000.0) - starttime) < (uint32_t)timeout) && (newsocket == SOCKET_ERROR) && connectInProgress(error)) { + while ((timeout == 0 || ((uint32_t)(real_time_now()*1000000.0) - starttime) < (uint32_t)timeout) && (newsocket == SOCKET_ERROR) && connectInProgress(error)) { // Accept Connection newsocket = accept(socket->id, (sockaddr *)&peeraddr, &peeraddrlen); error = errno; @@ -2314,14 +2314,14 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) { // Blocking Mode else { // Grab Connection Start Time - uint32_t starttime = (uint32_t)(real_time_now()*1000.0); + uint32_t starttime = (uint32_t)(real_time_now()*1000000.0); // Peer Information (for Connection-Polling) sockaddr_in peer; memset(&peer, 0, sizeof(peer)); socklen_t peerlen = sizeof(peer); // Wait for Connection - while ((timeout == 0 || ( (uint32_t)(real_time_now()*1000.0) - starttime) < (uint32_t)timeout) && getpeername(socket->id, (sockaddr *)&peer, &peerlen) != 0) { + while ((timeout == 0 || ( (uint32_t)(real_time_now()*1000000.0) - starttime) < (uint32_t)timeout) && getpeername(socket->id, (sockaddr *)&peer, &peerlen) != 0) { // Wait 1ms sleep_ms(1); } @@ -2709,9 +2709,9 @@ static int sceNetAdhocPtpRecv(int id, u32 dataAddr, u32 dataSizeAddr, int timeou if (flag == 0) { // Simulate blocking behaviour with non-blocking socket - uint32_t starttime = (uint32_t)(real_time_now() * 1000.0); + uint32_t starttime = (uint32_t)(real_time_now() * 1000000.0); // Wait for Connection - while ((timeout == 0 || ((uint32_t)(real_time_now() * 1000.0) - starttime) < (uint32_t)timeout) && (received == SOCKET_ERROR) && connectInProgress(error)) { + while ((timeout == 0 || ((uint32_t)(real_time_now() * 1000000.0) - starttime) < (uint32_t)timeout) && (received == SOCKET_ERROR) && connectInProgress(error)) { received = recv(socket->id, (char*)buf, *len, 0); error = errno; // Wait 1ms