From 9b9083d3e5140b05ac374024682f68fc8b7b9ff5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Sun, 16 Aug 2026 19:55:26 +0200 Subject: [PATCH] Fix for headless port problem by Claude --- Common/Net/HTTPServer.cpp | 28 ++++++++++++---- Core/CmdLine.cpp | 4 +++ Core/Debugger/WebSocket/GameSubscriber.cpp | 39 ++++++++++++++++++++++ Core/WebServer.cpp | 36 ++++++++++++++++++-- Core/WebServer.h | 11 ++++++ docs/WebSocketDebugger.md | 13 +++++++- headless/Headless.cpp | 10 ++++++ unittest/UnitTest.cpp | 2 ++ 8 files changed, 133 insertions(+), 10 deletions(-) diff --git a/Common/Net/HTTPServer.cpp b/Common/Net/HTTPServer.cpp index 91505edf74..ba4d689541 100644 --- a/Common/Net/HTTPServer.cpp +++ b/Common/Net/HTTPServer.cpp @@ -158,6 +158,24 @@ void Server::SetFallbackHandler(UrlHandlerFunc handler) { fallback_ = handler; } +// SO_REUSEADDR means two very different things depending on the platform, and only one of them is +// what we want here ("don't make me wait out TIME_WAIT when restarting the server quickly"). +// +// On Windows it *also* lets a socket bind a port another socket is already actively listening on - +// both binds succeed, and which one receives any given connection is undefined. That's a real +// hazard (it's how port hijacking works), and it bit us concretely: two PPSSPP instances launched +// with the same --debugger=PORT would both report "Listening on port N", and a debugger client +// could silently end up attached to the wrong process. SO_EXCLUSIVEADDRUSE is the Windows way to +// ask for the POSIX behavior, so use that there and plain SO_REUSEADDR everywhere else. +static void SetPortReusePolicy(int sock) { + int opt = 1; +#if PPSSPP_PLATFORM(WINDOWS) + setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char *)&opt, sizeof(opt)); +#else + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt)); +#endif +} + bool Server::Listen(int port, const char *reason, net::DNSType type) { bool success = false; if (type == net::DNSType::ANY || type == net::DNSType::IPV6) { @@ -180,9 +198,7 @@ bool Server::Listen4(int port, const char *reason) { server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(port); - int opt = 1; - // Enable re-binding to avoid the pain when restarting the server quickly. - setsockopt(listenerSock_, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt)); + SetPortReusePolicy(listenerSock_); if (bind(listenerSock_, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { #if PPSSPP_PLATFORM(WINDOWS) @@ -227,12 +243,10 @@ bool Server::Listen6(int port, bool ipv6_only, const char *reason) { server_addr.sin6_addr = in6addr_any; server_addr.sin6_port = htons(port); - int opt = 1; - // Enable re-binding to avoid the pain when restarting the server quickly. - setsockopt(listenerSock_, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt)); + SetPortReusePolicy(listenerSock_); // Enable listening on IPv6 and IPv4? - opt = ipv6_only ? 1 : 0; + int opt = ipv6_only ? 1 : 0; setsockopt(listenerSock_, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&opt, sizeof(opt)); if (bind(listenerSock_, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { diff --git a/Core/CmdLine.cpp b/Core/CmdLine.cpp index 564b5dd35a..11e8f77281 100644 --- a/Core/CmdLine.cpp +++ b/Core/CmdLine.cpp @@ -3,6 +3,7 @@ #include "Core/Config.h" #include "Core/CmdLine.h" +#include "Core/WebServer.h" #include "Common/StringUtils.h" #include "Common/Log/LogManager.h" @@ -511,6 +512,9 @@ void CommandLineOptions::ApplyToConfig() const { g_Config.DoNotSaveSetting(&g_Config.iRemoteISOPort); g_Config.bRemoteDebuggerOnStartup = true; g_Config.DoNotSaveSetting(&g_Config.bRemoteDebuggerOnStartup); + // --debugger=0 still means "pick any free port", but a specific port was asked for by + // something that intends to connect to it, so don't quietly come up on a different one. + WebServerSetRequireExactPort(debuggerPort.value() != 0); } if (logLevel.has_value()) { diff --git a/Core/Debugger/WebSocket/GameSubscriber.cpp b/Core/Debugger/WebSocket/GameSubscriber.cpp index b738bd1d9b..007fb12ef7 100644 --- a/Core/Debugger/WebSocket/GameSubscriber.cpp +++ b/Core/Debugger/WebSocket/GameSubscriber.cpp @@ -15,13 +15,38 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. +#include "ppsspp_config.h" + +// For the process id in the version response. On desktop Windows this is deliberately the CRT's +// _getpid() rather than Win32 GetCurrentProcessId(), to avoid pulling windows.h into this file - it +// defines an OPTIONAL macro that collides with DebuggerParamType::OPTIONAL. UWP has no _getpid, and +// there windows.h is safe to include because WebSocketUtils.h below #undef's OPTIONAL for it. +#if PPSSPP_PLATFORM(UWP) +#include "Common/CommonWindows.h" +#elif PPSSPP_PLATFORM(WINDOWS) && !defined(__MINGW32__) +#include +#else +#include +#endif + #include "Common/System/System.h" #include "Core/Config.h" +#include "Core/CoreParameter.h" #include "Core/Debugger/WebSocket/GameSubscriber.h" #include "Core/Debugger/WebSocket/WebSocketUtils.h" #include "Core/ELF/ParamSFO.h" #include "Core/System.h" +static uint32_t GetOwnProcessID() { +#if PPSSPP_PLATFORM(UWP) + return (uint32_t)GetCurrentProcessId(); +#elif PPSSPP_PLATFORM(WINDOWS) && !defined(__MINGW32__) + return (uint32_t)_getpid(); +#else + return (uint32_t)getpid(); +#endif +} + DebuggerSubscriber *WebSocketGameInit(DebuggerEventHandlerMap &map) { map["game.reset"] = &WebSocketGameReset; map["game.status"] = &WebSocketGameStatus; @@ -89,6 +114,12 @@ void WebSocketGameStatus(DebuggerRequest &req) { // Response (same event name): // - name: string, "PPSSPP" unless some special build. // - version: string, typically starts with "v" and may have git build info. +// - pid: unsigned integer, OS process id of this PPSSPP instance. +// - path: null, or string path of the executable/disc image currently loaded. +// +// pid and path are here so an automation client can confirm it's attached to the instance it +// meant to attach to. Ports aren't enough on their own: a leftover process may still be holding +// the one you asked for, and you'd never know you were driving the wrong emulator. void WebSocketVersion(DebuggerRequest &req) { JsonWriter &json = req.Respond(); @@ -104,4 +135,12 @@ void WebSocketVersion(DebuggerRequest &req) { json.writeString("name", "PPSSPP"); json.writeString("version", PPSSPP_GIT_VERSION); + + json.writeUint("pid", GetOwnProcessID()); + + const Path &fileToStart = PSP_CoreParameter().fileToStart; + if (fileToStart.empty()) + json.writeNull("path"); + else + json.writeString("path", fileToStart.ToString()); } diff --git a/Core/WebServer.cpp b/Core/WebServer.cpp index 0f7ad9d36c..86aa11b6b1 100644 --- a/Core/WebServer.cpp +++ b/Core/WebServer.cpp @@ -16,6 +16,8 @@ // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. #include +#include +#include #include #include #include @@ -55,7 +57,11 @@ static const int REPORT_PORT = 80; static std::thread serverThread; static ServerStatus serverStatus; static std::mutex serverStatusLock; +static std::condition_variable serverStatusCond; static WebServerFlags serverFlags; +// See WebServerSetRequireExactPort(). Atomic because it's set from whichever thread parsed the +// command line, and read from the server thread. +static std::atomic serverRequireExactPort; std::mutex g_webServerLock; static Path g_uploadPath; // TODO: Supply this through registration instead. @@ -83,8 +89,11 @@ std::string ServerUriDecode(std::string_view encoded) { } static void UpdateStatus(ServerStatus s) { - std::lock_guard guard(serverStatusLock); - serverStatus = s; + { + std::lock_guard guard(serverStatusLock); + serverStatus = s; + } + serverStatusCond.notify_all(); } static ServerStatus RetrieveStatus() { @@ -784,6 +793,19 @@ static void WebServerThread() { http->RegisterHandler("/upload_file", &HandleUploadPost); if (!http->Listen(g_Config.iRemoteISOPort, "debugger-webserver")) { + if (serverRequireExactPort) { + // Someone asked for this specific port (--debugger=PORT) - see + // WebServerSetRequireExactPort(). Coming up on a different one would just look like + // success while nothing can connect, so give up loudly instead. + ERROR_LOG(Log::FileSystem, "Unable to listen on port %d, and it was explicitly requested (debugger - webserver). Is another PPSSPP instance already using it?", g_Config.iRemoteISOPort); + // Headless treats this as fatal; the GUI app stays usable, so at least say why there's + // no debugger rather than leaving it a mystery. + if (serverFlags & WebServerFlags::DEBUGGER) { + g_OSD.Show(OSDType::MESSAGE_ERROR, "Debugger web server could not use port " + std::to_string(g_Config.iRemoteISOPort), 8.0f, "debugger"); + } + UpdateStatus(ServerStatus::FINISHED); + return; + } if (!http->Listen(0, "debugger-webserver")) { ERROR_LOG(Log::FileSystem, "Unable to listen on any port (debugger - webserver)"); UpdateStatus(ServerStatus::FINISHED); @@ -893,3 +915,13 @@ bool WebServerRunning(WebServerFlags flags) { int WebServerPort() { return g_Config.iRemoteISOPort; } + +void WebServerSetRequireExactPort(bool require) { + serverRequireExactPort = require; +} + +bool WebServerWaitForStartup() { + std::unique_lock guard(serverStatusLock); + serverStatusCond.wait(guard, [] { return serverStatus != ServerStatus::STARTING; }); + return serverStatus == ServerStatus::RUNNING; +} diff --git a/Core/WebServer.h b/Core/WebServer.h index 3737119bd3..618e31426c 100644 --- a/Core/WebServer.h +++ b/Core/WebServer.h @@ -39,6 +39,17 @@ bool WebServerStopped(WebServerFlags flags); bool WebServerRunning(WebServerFlags flags); void ShutdownWebServer(); +// By default, if g_Config.iRemoteISOPort is taken we quietly fall back to any free port - fine for +// the "Local Server Port" preference, where the user just wants the thing to come up. It's the +// wrong behavior for --debugger=PORT: an automation client was told to connect to that exact port, +// so landing on a different one leaves it connecting to nothing (or, worse, to some other PPSSPP +// instance that got there first). Set this to make the bind failure fatal instead. +void WebServerSetRequireExactPort(bool require); + +// Blocks until the server thread has either started listening or given up, and returns whether +// it's actually listening. Only meaningful right after StartWebServer(). +bool WebServerWaitForStartup(); + bool RemoteISOFileSupported(const std::string &filename); void WebServerSetUploadPath(const Path &path); int WebServerPort(); diff --git a/docs/WebSocketDebugger.md b/docs/WebSocketDebugger.md index 736d6a340c..7750bbf51d 100644 --- a/docs/WebSocketDebugger.md +++ b/docs/WebSocketDebugger.md @@ -72,7 +72,11 @@ By convention, send a `version` event right after connecting (see { "event": "version", "name": "my-tool", "version": "1.0" } ``` PPSSPP responds with its own name/version, and remembers yours (currently -just for internal bookkeeping/future logging). +just for internal bookkeeping/future logging). The response also carries +`pid` (OS process id) and `path` (the executable/disc currently loaded, or +`null`), so an automation client can confirm it attached to the instance it +meant to - a port alone doesn't prove that, since a leftover process may still +be holding the port you asked for. ## Broadcast (unsolicited) events @@ -134,6 +138,13 @@ file - this is just an index. `Core/CmdLine.cpp`/`.h` (`CmdLineMode::Both`). `ApplyToConfig()` sets `iRemoteISOPort`/`bRemoteDebuggerOnStartup` for that run without persisting them to the config file. + - A **non-zero** `PORT` is treated as mandatory (`WebServerSetRequireExactPort()`): + if it can't be bound, the server does *not* silently fall back to some other + free port the way the "Local Server Port" preference does, because a client + was told to connect there. Headless exits non-zero; the application build + logs an error and shows an OSD message but keeps running. Use `--debugger=0` + and read the actual port from the `Listening on port N` log line if you'd + rather not care which port you get. - On the **application** build this is exactly like ticking "Allow remote debugger" - the game boots and runs normally, debugger listening alongside it. diff --git a/headless/Headless.cpp b/headless/Headless.cpp index 52e68ccb81..ba2ef8b647 100644 --- a/headless/Headless.cpp +++ b/headless/Headless.cpp @@ -845,6 +845,16 @@ int main(int argc, const char* argv[]) { if (cmdLineOptions.debuggerPort.has_value()) { coreParameter.startBreak = true; StartWebServer(WebServerFlags::DEBUGGER); + // We break at start and wait for a debugger to drive us, so coming up without one just + // hangs until the timeout. Better to say why and bail - see WebServerSetRequireExactPort(). + if (!WebServerWaitForStartup()) { + fprintf(stderr, "Failed to start the debugger web server on port %d\n", cmdLineOptions.debuggerPort.value()); + // The server thread has exited but is still joinable - without this, its std::thread + // destructor would call std::terminate() on the way out and we'd abort instead of + // returning a useful exit code. + ShutdownWebServer(); + return 1; + } } if (stateToLoad) { diff --git a/unittest/UnitTest.cpp b/unittest/UnitTest.cpp index a0df995093..44fc6a5023 100644 --- a/unittest/UnitTest.cpp +++ b/unittest/UnitTest.cpp @@ -134,6 +134,8 @@ void NativeFrame(GraphicsContext *graphicsContext) {} void NativeResized() {} bool System_MakeRequest(SystemRequestType type, int requestId, const std::string ¶m1, const std::string ¶m2, int64_t param3, int64_t param4) { return false; } +// Pulled in via Core/WebServer.cpp's OpenWebDebugger(), which CmdLine.cpp now references. +void System_LaunchUrl(LaunchUrlType urlType, std::string_view url) {} void System_InputBoxGetString(const std::string &title, const std::string &defaultValue, std::function cb) { cb(false, ""); } void System_AskForPermission(SystemPermission permission) {} PermissionStatus System_GetPermissionStatus(SystemPermission permission) { return PERMISSION_STATUS_GRANTED; }