diff --git a/Core/Util/PortManager.cpp b/Core/Util/PortManager.cpp index fe2fb1debd..083aa0488d 100644 --- a/Core/Util/PortManager.cpp +++ b/Core/Util/PortManager.cpp @@ -26,9 +26,12 @@ // All credit goes to him and the official miniupnp project! http://miniupnp.free.fr/ #include // find_if +#include #include #include #include +#include +#include #include "Common/TimeUtil.h" #include "Common/Data/Text/I18n.h" @@ -43,21 +46,10 @@ #include "Core/Util/PortManager.h" PortManager g_PortManager; -static bool upnpServiceRunning = false; -static std::thread upnpServiceThread; -static std::recursive_mutex upnpLock; -static std::deque upnpReqs; - -PortManager::PortManager(): - m_InitState(UPNP_INITSTATE_NONE), - m_LocalPort(UPNP_LOCAL_PORT_ANY), - m_leaseDuration("43200") { - // Don't call net::Init or similar here, we don't want stuff like that to happen before main. -} - -PortManager::~PortManager() { - // 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) -} +static std::thread g_upnpServiceThread; +static std::mutex g_upnpLock; +static std::condition_variable g_upnpCond; +static std::deque g_upnpReqs; void PortManager::Shutdown() { Clear(); @@ -66,7 +58,7 @@ void PortManager::Shutdown() { } void PortManager::Terminate() { - VERBOSE_LOG(Log::Net, "PortManager::Terminate()"); + DEBUG_LOG(Log::Net, "PortManager::Terminate()"); if (urls) { #ifdef WITH_UPNP FreeUPNPUrls(urls); @@ -100,7 +92,7 @@ bool PortManager::Initialize(const unsigned int timeout) { unsigned char ttl = 2; // defaulting to 2 int error = 0; - VERBOSE_LOG(Log::Net, "PortManager::Initialize(%d)", timeout); + DEBUG_LOG(Log::Net, "PortManager::Initialize(%d)", timeout); if (!g_Config.bEnableUPnP) { ERROR_LOG(Log::Net, "PortManager::Initialize - UPnP is Disabled on Networking Settings"); return false; @@ -195,6 +187,7 @@ bool PortManager::Initialize(const unsigned int timeout) { //m_LocalPort = localport; // We shouldn't keep the right port for the next game reset if we wanted to redetect UPnP m_InitState = UPNP_INITSTATE_DONE; RefreshPortList(); + return true; } @@ -475,20 +468,35 @@ int upnpService(const unsigned int timeout) { INFO_LOG(Log::Net, "UPnPService: Begin of UPnPService Thread"); // Service Loop - while (upnpServiceRunning) { - // Sleep for 1ms for faster response if active, otherwise sleep longer (TODO: Improve on this). - sleep_ms(g_Config.bEnableUPnP ? 1 : 500, "upnp-poll"); + while (true) { + UPnPArgs arg; + bool haveArg; + { + std::unique_lock lock(g_upnpLock); + // Also wake up periodically even with nothing queued (and on UPnP_Notify()), so we + // can retry a failed/disconnected UPnP init or notice the enable setting flipped, + // without needing an explicit Add/Remove request to prod us. + g_upnpCond.wait_for(lock, std::chrono::seconds(5), [] { return !g_upnpReqs.empty(); }); + haveArg = !g_upnpReqs.empty(); + if (haveArg) { + arg = g_upnpReqs.front(); + } + } + + // Exit requests must be handled regardless of whether UPnP is enabled or has + // finished initializing, otherwise shutdown could wait on this thread forever. + if (haveArg && arg.cmd == UPNP_CMD_EXIT) { + std::lock_guard lock(g_upnpLock); + g_upnpReqs.pop_front(); + break; + } // Attempts to reconnect if not connected yet or got disconnected if (g_Config.bEnableUPnP && g_PortManager.GetInitState() == UPNP_INITSTATE_NONE) { g_PortManager.Initialize(timeout); } - if (g_Config.bEnableUPnP && g_PortManager.GetInitState() == UPNP_INITSTATE_DONE && !upnpReqs.empty()) { - upnpLock.lock(); - UPnPArgs arg = upnpReqs.front(); - upnpLock.unlock(); - + if (haveArg && g_Config.bEnableUPnP && g_PortManager.GetInitState() == UPNP_INITSTATE_DONE) { bool ok = true; switch (arg.cmd) { case UPNP_CMD_ADD: @@ -503,9 +511,8 @@ int upnpService(const unsigned int timeout) { // It's only considered failed when disconnected (should be retried when reconnected) if (ok) { - upnpLock.lock(); - upnpReqs.pop_front(); - upnpLock.unlock(); + std::lock_guard lock(g_upnpLock); + g_upnpReqs.pop_front(); } } } @@ -516,36 +523,46 @@ int upnpService(const unsigned int timeout) { } // Should we ingore any leftover UPnP requests? instead of processing it on the next game start - upnpLock.lock(); - upnpReqs.clear(); - upnpLock.unlock(); + { + std::unique_lock lock(g_upnpLock); + g_upnpReqs.clear(); + } INFO_LOG(Log::Net, "UPnPService: End of UPnPService Thread"); return 0; } -void __UPnPInit(const int timeout_ms) { - if (!upnpServiceRunning) { - upnpServiceRunning = true; - upnpServiceThread = std::thread(upnpService, timeout_ms); - } +void __UPnPInit(const unsigned int timeout) { + _dbg_assert_(!g_upnpServiceThread.joinable()); + + g_upnpServiceThread = std::thread(upnpService, timeout); } void __UPnPShutdown() { - if (upnpServiceRunning) { - upnpServiceRunning = false; - if (upnpServiceThread.joinable()) { - upnpServiceThread.join(); - } + _dbg_assert_(g_upnpServiceThread.joinable()); + { + std::lock_guard upnpGuard(g_upnpLock); + g_upnpReqs.push_back({ UPNP_CMD_EXIT }); + g_upnpCond.notify_one(); + } + + if (g_upnpServiceThread.joinable()) { + g_upnpServiceThread.join(); } } void UPnP_Add(const char* protocol, unsigned short port, unsigned short intport) { - std::lock_guard upnpGuard(upnpLock); - upnpReqs.push_back({ UPNP_CMD_ADD, protocol, port, intport }); + std::lock_guard upnpGuard(g_upnpLock); + g_upnpReqs.push_back({ UPNP_CMD_ADD, protocol, port, intport }); + g_upnpCond.notify_one(); } void UPnP_Remove(const char* protocol, unsigned short port) { - std::lock_guard upnpGuard(upnpLock); - upnpReqs.push_back({ UPNP_CMD_REMOVE, protocol, port, port }); + std::lock_guard upnpGuard(g_upnpLock); + g_upnpReqs.push_back({ UPNP_CMD_REMOVE, protocol, port, port }); + g_upnpCond.notify_one(); +} + +void UPnP_Notify() { + g_upnpCond.notify_one(); } diff --git a/Core/Util/PortManager.h b/Core/Util/PortManager.h index b42e3f9e08..2b209bf429 100644 --- a/Core/Util/PortManager.h +++ b/Core/Util/PortManager.h @@ -46,12 +46,18 @@ struct UPnPArgs { #define IP_PROTOCOL_TCP "TCP" #define IP_PROTOCOL_UDP "UDP" -#define UPNP_INITSTATE_NONE 0 -#define UPNP_INITSTATE_BUSY 1 -#define UPNP_INITSTATE_DONE 2 -#define UPNP_CMD_ADD 0 -#define UPNP_CMD_REMOVE 1 +enum { + UPNP_INITSTATE_NONE = 0, + UPNP_INITSTATE_BUSY = 1, + UPNP_INITSTATE_DONE = 2, +}; + +enum { + UPNP_CMD_ADD = 0, + UPNP_CMD_REMOVE = 1, + UPNP_CMD_EXIT = 2, +}; struct UPNPUrls; struct IGDdatas; @@ -70,9 +76,6 @@ struct PortMap { class PortManager { public: - PortManager(); - ~PortManager(); - // Initialize UPnP // timeout: milliseconds to wait for a router to respond (default = 2000 ms) bool Initialize(const unsigned int timeout = 2000); @@ -116,7 +119,7 @@ private: extern PortManager g_PortManager; -void __UPnPInit(const int timeout_ms); +void __UPnPInit(const unsigned int timeout_ms); void __UPnPShutdown(); // Add a port & protocol (TCP, UDP or vendor-defined) to map for forwarding (intport = 0 : same as [external] port) @@ -124,3 +127,8 @@ void UPnP_Add(const char* protocol, unsigned short port, unsigned short intport // Remove a port mapping (external port) void UPnP_Remove(const char* protocol, unsigned short port); + +// Wakes the UPnP service thread immediately, without queuing a request - useful after +// changing the enable setting or similar, so it can (re)connect without waiting for the +// periodic retry. +void UPnP_Notify(); diff --git a/UI/GameSettingsScreen.cpp b/UI/GameSettingsScreen.cpp index e0b978f4c2..0e0da1765c 100644 --- a/UI/GameSettingsScreen.cpp +++ b/UI/GameSettingsScreen.cpp @@ -78,6 +78,7 @@ #include "Core/HLE/sceUsbCam.h" #include "Core/HLE/sceUsbMic.h" #include "Core/HLE/sceUtility.h" +#include "Core/Util/PortManager.h" #include "GPU/Common/PostShader.h" #include "GPU/GPU.h" @@ -1047,7 +1048,11 @@ void GameSettingsScreen::CreateNetworkingSettings(UI::ViewGroup *networkingSetti dnsServer->SetDisabledPtr(&g_Config.bInfrastructureAutoDNS); networkingSettings->Add(new ItemHeader(n->T("UPnP (port-forwarding)"))); - 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.bEnableUPnP, n->T("Enable UPnP", "Enable UPnP (need a few seconds to detect)")))->OnClick.Add([](UI::EventParams &e) { + // Wake the UPnP service thread immediately so it reacts to the new setting instead + // of waiting for the next periodic retry (or a port request that may never come). + UPnP_Notify(); + }); auto *useOriPort = networkingSettings->Add(new CheckBox(&g_Config.bUPnPUseOriginalPort, n->T("UPnP use original port", "UPnP use original port (Enabled = PSP compatibility)"))); networkingSettings->Add(new SettingHint(n->T("UseOriginalPort Tip", "May not work for all devices or games, see wiki."), useOriPort));