diff --git a/AGENTS.md b/AGENTS.md index 5f54b90..dad3805 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,11 +1,13 @@ # SteamAPIBridge -Read README.md for runtime ownership and ABI boundaries. Build with the x86 Debug -and Release scripts and run CTest. Keep public exports C-compatible and prefixed -SteamBridge_. Do not link steam_api.lib, initialize or shut down the host Steam -session, or expose vendor C++ objects in the public ABI. External SDK trees are -read-only. Preserve historical interface slots and verify callback layouts against -the referenced Valve headers when extending compatibility. Record simulated and +Read README.md for runtime ownership and ABI boundaries. Build with the Windows +x86/x64 and Linux scripts and run CTest on each platform you change. Keep public exports +C-compatible and prefixed SteamBridge_. Do not link steam_api.lib or expose vendor C++ +objects in the public ABI. Only host mode (SteamBridge_Host*/Server*) initializes or +shuts down Steam, and only when the host requests it; plugin-mode code never touches +the game's Steam session. External SDK trees are read-only. +Preserve historical interface slots and verify callback layouts against the +referenced Valve headers when extending compatibility. Record simulated and real-game verification separately. Tests exercise behavior and binary loading, not documentation or configuration text. diff --git a/CMakeLists.txt b/CMakeLists.txt index 5caa93c..44c59b9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,30 +8,62 @@ endif() cmake_policy(SET CMP0091 NEW) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") project(SteamAPIBridge VERSION 1.0.0 LANGUAGES CXX) -if(NOT WIN32 OR NOT MSVC OR NOT CMAKE_SIZEOF_VOID_P EQUAL 4) - message(FATAL_ERROR "SteamAPIBridge requires Windows MSVC x86 (-A Win32).") +if(WIN32 AND NOT MSVC) + message(FATAL_ERROR "SteamAPIBridge requires MSVC on Windows.") +elseif(NOT WIN32 AND NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "SteamAPIBridge supports Windows and Linux.") endif() -get_property(steambridge_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) -if(steambridge_multi_config) - set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Supported configurations" FORCE) -elseif(NOT CMAKE_BUILD_TYPE MATCHES "^(Debug|Release)$") - message(FATAL_ERROR "Select Debug or Release.") +# A parent project keeps its own configurations. +if(PROJECT_IS_TOP_LEVEL) + get_property(steambridge_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if(steambridge_multi_config) + set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Supported configurations" FORCE) + elseif(NOT CMAKE_BUILD_TYPE MATCHES "^(Debug|Release)$") + message(FATAL_ERROR "Select Debug or Release.") + endif() endif() set(STEAMSDK_SOURCE_PATH "$ENV{STEAMSDK_SOURCE_PATH}" CACHE PATH "Read-only SteamSDK source") include(cmake/Dependencies.cmake) steambridge_prepare_dependencies() include(cmake/SourceGroups.cmake) -add_library(SteamAPIBridge SHARED src/SteamAPIBridge.cpp) +add_library(SteamAPIBridge SHARED src/SteamAPIBridge.cpp src/Host.cpp src/Platform.h src/LegacyInterfaces.h) steambridge_assign_source_groups(SteamAPIBridge) add_library(SteamAPIBridge::SteamAPIBridge ALIAS SteamAPIBridge) target_compile_features(SteamAPIBridge PRIVATE cxx_std_20) -target_compile_definitions(SteamAPIBridge PRIVATE STEAMAPIBRIDGE_EXPORTS WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) target_include_directories(SteamAPIBridge PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include" PRIVATE "${STEAMSDK_SOURCE_PATH}") -target_compile_options(SteamAPIBridge PRIVATE /W4 /permissive- /Zi) -target_link_options(SteamAPIBridge PRIVATE /DEBUG) set_target_properties(SteamAPIBridge PROPERTIES DEBUG_POSTFIX "") -install(TARGETS SteamAPIBridge RUNTIME DESTINATION svencoop/metahook/dlls) -install(FILES "$" DESTINATION svencoop/metahook/dlls) +if(MSVC) + target_compile_definitions(SteamAPIBridge PRIVATE STEAMAPIBRIDGE_EXPORTS WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) + target_compile_options(SteamAPIBridge PRIVATE /W4 /permissive- /Zi) + target_link_options(SteamAPIBridge PRIVATE /DEBUG) +else() + target_compile_definitions(SteamAPIBridge PRIVATE STEAMAPIBRIDGE_EXPORTS) + target_compile_options(SteamAPIBridge PRIVATE -Wall -Wextra) + target_link_libraries(SteamAPIBridge PRIVATE ${CMAKE_DL_LIBS}) + # Only the SteamBridge_ C ABI is exported; the version script also hides libstdc++ template instances. + set_target_properties(SteamAPIBridge PROPERTIES CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN ON LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/SteamAPIBridge.map") + target_link_options(SteamAPIBridge PRIVATE "LINKER:--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/SteamAPIBridge.map") +endif() +# The steam_api runtime that host mode loads from the bridge's directory. +if(WIN32 AND CMAKE_SIZEOF_VOID_P EQUAL 8) + set(steambridge_runtime "${STEAMSDK_SOURCE_PATH}/bin/steam_api64.dll") +elseif(WIN32) + set(steambridge_runtime "${STEAMSDK_SOURCE_PATH}/bin/steam_api.dll") +elseif(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(steambridge_runtime "${STEAMSDK_SOURCE_PATH}/bin/linux64/libsteam_api.so") +else() + set(steambridge_runtime "${STEAMSDK_SOURCE_PATH}/bin/linux32/libsteam_api.so") +endif() +set(STEAMAPIBRIDGE_RUNTIME "${steambridge_runtime}" CACHE INTERNAL "steam_api runtime for the target architecture") +set(STEAMAPIBRIDGE_INSTALL_DIR "svencoop/metahook/dlls" CACHE STRING "Install directory of the bridge, relative to the install prefix") +option(STEAMAPIBRIDGE_INSTALL_RUNTIME "Install the steam_api runtime beside the bridge for host mode" OFF) +install(TARGETS SteamAPIBridge RUNTIME DESTINATION "${STEAMAPIBRIDGE_INSTALL_DIR}" LIBRARY DESTINATION "${STEAMAPIBRIDGE_INSTALL_DIR}") +if(MSVC) + install(FILES "$" DESTINATION "${STEAMAPIBRIDGE_INSTALL_DIR}") +endif() +if(STEAMAPIBRIDGE_INSTALL_RUNTIME) + install(FILES "${STEAMAPIBRIDGE_RUNTIME}" DESTINATION "${STEAMAPIBRIDGE_INSTALL_DIR}") +endif() option(STEAMAPIBRIDGE_BUILD_TESTS "Build bridge regression tests" ${PROJECT_IS_TOP_LEVEL}) if(STEAMAPIBRIDGE_BUILD_TESTS) enable_testing() diff --git a/README.md b/README.md index af3f5ad..7bd6425 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,37 @@ # SteamAPIBridge -Windows MSVC x86 compatibility DLL for MetaHookSv SteamAPI consumers. Plugins link -`SteamAPIBridge.lib`; the game supplies and initializes its own `steam_api.dll`. -The bridge neither imports SteamAPI functions nor replaces the game's runtime. +C ABI bridge to the Steamworks API for Windows (MSVC x86/x64) and Linux (x86/x64). +It has two modes: + +* **Plugin mode** (MetaHookSv consumers): plugins link `SteamAPIBridge.lib`; the game + supplies and initializes its own `steam_api.dll`. The bridge only uses the runtime + that is already loaded and never initializes or shuts Steam down. +* **Host mode** (a game engine without its own Steam session): the host asks the bridge + to load the runtime and own SteamAPI/SteamGameServer initialization, callback pumping + and shutdown, through the `SteamBridge_Host*`, `SteamBridge_User*`, + `SteamBridge_Voice*` and `SteamBridge_Server*` functions. + +In both modes the bridge resolves the runtime dynamically and does not link +`steam_api.lib`. ## Runtime contract -The C interface is `include/SteamAPIBridge.h`. It exposes SteamID, screenshot and -HTTP operations, status codes, opaque consumer contexts and function callbacks. -No Steam interface pointer, STL object or allocation ownership crosses the DLL ABI. -`SB_OK` is zero; failed create operations clear their output handles. +The C interface is `include/SteamAPIBridge.h`. It exposes status codes, opaque +consumer contexts, function callbacks and plain event structures. No Steam interface +pointer, STL object or allocation ownership crosses the ABI. `SB_OK` is zero; failed +create or query operations clear their outputs. + +### Plugin mode + +The runtime is the loaded `steam_api.dll` (Windows x86), `steam_api64.dll` (Windows +x64) or `libsteam_api.so` (Linux). Contexts expose SteamID, screenshot and HTTP +operations. * Modern runtimes: dynamically request User023, Screenshots003 and HTTP003 using `SteamInternal_FindOrCreateUserInterface`. -* GoldSrc 8684 runtime: use its **SteamClient012 Windows ABI** with the existing - user/pipe to request the same versions. User016 and Screenshots001 are supported - fallbacks. Private declarations record their historical Valve SDK provenance. +* GoldSrc 8684 runtime (Windows x86 only): use its **SteamClient012 Windows ABI** with + the existing user/pipe to request the same versions. User016 and Screenshots001 are + supported fallbacks. Private declarations record their historical Valve SDK provenance. * HTTP always requires HTTP003. Older HTTP002 revisions have incompatible method availability despite sharing a version string; the bridge does not silently omit cookies or certificate verification settings. @@ -27,12 +43,12 @@ bound to its first available module/user/pipe session; create a new context for new game session. Interface objects are resolved on each operation, not cached across sessions. An unavailable initial runtime may be retried on the same context. -The game alone runs `SteamAPI_Init`, `SteamAPI_RunCallbacks` and `SteamAPI_Shutdown`. -Callbacks execute synchronously on the host callback thread, outside bridge locks. -Event pointers are borrowed during the call. Callbacks may unsubscribe, release a -request or destroy their context; native callback objects are retired until dispatch -has returned. Do not destroy a context concurrently with calls using that context. -Application callbacks must not throw across the C ABI. +In plugin mode the game alone runs `SteamAPI_Init`, `SteamAPI_RunCallbacks` and +`SteamAPI_Shutdown`. Callbacks execute synchronously on the host callback thread, +outside bridge locks. Event pointers are borrowed during the call. Callbacks may +unsubscribe, release a request or destroy their context; native callback objects are +retired until dispatch has returned. Do not destroy a context concurrently with calls +using that context. Application callbacks must not throw across the C ABI. Screenshot completion results retain Steam's numeric EResult values. HTTP events distinguish headers, data and completion. Headers/data are ordinary Steam callbacks @@ -40,34 +56,86 @@ filtered by request handle; completion is a call result dispatched at most once. Request/response buffers belong to the caller. Read response data before releasing the request. No successful interface lookup certifies game-engine compatibility. +### Host mode + +`SteamBridge_HostInit(runtimePath, initializeClient)` loads `runtimePath`, or the +platform runtime from the bridge's own directory when it is `NULL`. Host mode requires +a modern runtime exporting `SteamAPI_InitFlat`, `SteamInternal_GameServer_Init_V2` and +the `SteamInternal_FindOrCreate*Interface` accessors; Steamworks SDK v1.65 is pinned. +A missing runtime or export returns `SB_UNAVAILABLE`, and a failed client initialization +(`SteamAPI_InitFlat`: Steam not running, application not owned) returns `SB_FAILED`; +both leave the runtime unloaded. A dedicated server passes `initializeClient = 0` and +only uses the game server functions. + +* Client: game connection tickets (`InitiateGameConnection_DEPRECATED`), SteamID, + persona name, app subscription and voice (User023, Friends018, Apps009). Missing + interfaces make the corresponding calls return `SB_UNAVAILABLE`. +* Game server (`SteamBridge_ServerInit`): GameServer015 logon, server rules and + heartbeats, ticket authentication (`SendUserConnectAndAuthenticate_DEPRECATED`), + bots and shared-socket master server packets. The interface version list matches + `SteamGameServer_InitEx`. +* Events: ClientGameServerDeny, GameServerChangeRequested and GameOverlayActivated + reach the client callback during `SteamBridge_HostRunCallbacks`; SteamServersConnected, + SteamServerConnectFailure, GSPolicyResponse and GSClientApprove/Deny/Kick reach the + server callback during `SteamBridge_ServerRunCallbacks`. Fields are copied out of + Steam's payloads; IP addresses and ports pass through unchanged. + +Host functions are not thread-safe; call them from the host's main thread. A callback +may call `SteamBridge_HostShutdown` or `SteamBridge_ServerShutdown`; the shutdown runs +after the native dispatcher returns. `SteamBridge_HostShutdown` shuts down an active +game server first. Plugin contexts may use the runtime that host mode loaded; destroy +them before `SteamBridge_HostShutdown`. + ## Build and install ```bat scripts\build-SteamAPIBridge-x86-Debug.bat scripts\build-SteamAPIBridge-x86-Release.bat +scripts\build-SteamAPIBridge-x64-Debug.bat +scripts\build-SteamAPIBridge-x64-Release.bat ``` -Requires CMake 3.21+, Visual Studio 2022 Win32 and C++20. Uses the static CRT. +```sh +scripts/build-SteamAPIBridge-linux.sh x64 Release +scripts/build-SteamAPIBridge-linux.sh x86 Release # needs g++-multilib +``` + +Requires CMake 3.21+ and C++20: Visual Studio 2022 (Win32 or x64, static CRT) on +Windows, GCC or Clang on Linux. Linux builds export only the `SteamBridge_` symbols. `STEAMSDK_SOURCE_PATH` accepts a read-only local dependency tree; otherwise the pinned SDK is fetched. `STEAMAPIBRIDGE_BUILD_TESTS` defaults on for standalone builds, off as a subproject. +As a subproject the bridge keeps the parent's build configurations. CMake target: `SteamAPIBridge` (alias `SteamAPIBridge::SteamAPIBridge`). Consumers reuse this target in the aggregate; standalone consumers build a fixed bridge commit through `STEAMAPIBRIDGE_SOURCE_PATH` or FetchContent. Installation stages -the DLL/PDB under `svencoop/metahook/dlls`; the installer maps the selected game mod. -No `steam_api.dll` is installed. The game must make `metahook/dlls` available before -loading consumers, as the MetaHook loader already does. +the bridge (and PDB on Windows) under `STEAMAPIBRIDGE_INSTALL_DIR`, by default +`svencoop/metahook/dlls`; the installer maps the selected game mod. The game must make +that directory available before loading consumers, as the MetaHook loader already does. +`STEAMAPIBRIDGE_INSTALL_RUNTIME` (default `OFF`) also installs the SDK's `steam_api` +runtime for the target architecture beside the bridge, as host mode expects; +`STEAMAPIBRIDGE_RUNTIME` names that file for consumers that stage it themselves. ## Verification -CTest covers absent/uninitialized Steam, legacy and intermediate-modern exports, -exact-version availability and retry, SteamID/screenshots, cookie/certificate +CTest covers, on every supported platform, absent runtimes and host mode against a +fixture runtime: client initialization failure and retry, connection tickets, voice +capture/decoding and non-OK voice results, client and game server event translation +and dispatcher separation, deferred shutdown from callbacks, game server setters and +authentication, packets, and dedicated (server-only) sessions. On Windows it also +covers plugin mode: absent/uninitialized Steam, legacy (x86) and intermediate-modern +exports, exact-version availability and retry, SteamID/screenshots, cookie/certificate forwarding, stream events, context isolation, cancellation and reentrant destruction. Fixtures never initialize the real Steam client or make network requests. -`SteamBridgeLoadSmoke` accepts real Steam DLL and consumer DLL paths for loader-only -checks. These checks do not validate Steam authentication, screenshot submission, -real HTTP traffic, engine hooks or gameplay. Those require running each target game. + +Two manual tools are built but not run by CTest. `SteamBridgeLoadSmoke` (Windows) +accepts real Steam DLL and consumer DLL paths for loader-only checks. +`SteamBridgeHostSmoke [seconds]` needs a running, logged-in Steam client and +`steam_appid.txt` in the working directory: it initializes the client, logs a game +server on anonymously, authenticates the client's ticket and exits zero on +GSClientApprove. Neither validates screenshot submission, real HTTP traffic, engine +hooks or gameplay; those require running each target game. The SDK notice is installed with the runtime. Historical ABI declarations derive from Valve Steamworks headers; see their provenance in `src/LegacyInterfaces.h`. diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index 9d6ee1b..475c382 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -3,7 +3,7 @@ function(steambridge_prepare_dependencies) include(FetchContent) FetchContent_Declare(steambridge_sdk GIT_REPOSITORY https://github.com/MetaHookSv/SteamSDK - GIT_TAG 3c1abaf6277f9f99fd16ef40557d6852820b848f + GIT_TAG ba2bfcc008b8aa197aba05e6122a15d6d236b80b GIT_SUBMODULES "" SOURCE_SUBDIR _source_only) FetchContent_MakeAvailable(steambridge_sdk) set(STEAMSDK_SOURCE_PATH "${steambridge_sdk_SOURCE_DIR}") diff --git a/include/SteamAPIBridge.h b/include/SteamAPIBridge.h index ac1d431..fc3995c 100644 --- a/include/SteamAPIBridge.h +++ b/include/SteamAPIBridge.h @@ -1,12 +1,17 @@ #pragma once #include -#ifdef STEAMAPIBRIDGE_EXPORTS -# define STEAMBRIDGE_API __declspec(dllexport) +#if defined(_WIN32) +# ifdef STEAMAPIBRIDGE_EXPORTS +# define STEAMBRIDGE_API __declspec(dllexport) +# else +# define STEAMBRIDGE_API __declspec(dllimport) +# endif +# define STEAMBRIDGE_CALL __cdecl #else -# define STEAMBRIDGE_API __declspec(dllimport) +# define STEAMBRIDGE_API __attribute__((visibility("default"))) +# define STEAMBRIDGE_CALL #endif -#define STEAMBRIDGE_CALL __cdecl #ifdef __cplusplus extern "C" { @@ -91,6 +96,136 @@ extern "C" STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_HTTPSetCookies(SteamBridgeContextHandle context, uint32_t request, uint32_t cookies); STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_HTTPSetCookie(SteamBridgeContextHandle context, uint32_t cookies, const char* host, const char* url, const char* cookie); + // Host session. A host that has no Steam session of its own (a game engine) asks the + // bridge to load the runtime and own SteamAPI/SteamGameServer initialization. Consumers + // of a game that initializes Steam itself must not call these functions. + // runtimePath names the steam_api runtime file; NULL loads the platform runtime + // (steam_api.dll, steam_api64.dll or libsteam_api.so) from the bridge's directory. + // IP addresses and ports are passed to Steam unchanged. Host functions are not + // thread-safe; call them from the host's main thread. + enum + { + SB_CLIENT_GAMESERVER_DENY = 1, + SB_CLIENT_GAMESERVER_CHANGE = 2, + SB_CLIENT_OVERLAY = 3 + }; + enum + { + SB_SERVER_LOGON_SUCCESS = 1, + SB_SERVER_LOGON_FAILURE = 2, + SB_SERVER_POLICY = 3, + SB_SERVER_CLIENT_APPROVE = 4, + SB_SERVER_CLIENT_DENY = 5, + SB_SERVER_CLIENT_KICK = 6 + }; + // Values of Steamworks EServerMode. + enum + { + SB_SERVER_MODE_NO_AUTHENTICATION = 1, + SB_SERVER_MODE_AUTHENTICATION = 2, + SB_SERVER_MODE_SECURE = 3 + }; + enum + { + SB_SERVER_TEXT_BYTES = 128, + SB_CLIENT_SERVER_BYTES = 64 + }; + + // serverIP/serverPort are copied from Steam's ClientGameServerDeny_t unchanged. + typedef struct SteamBridgeClientEvent + { + uint32_t kind; + uint32_t serverIP; + uint32_t serverPort; + uint32_t secure; + uint32_t reason; + uint32_t active; + char server[SB_CLIENT_SERVER_BYTES]; + char password[SB_CLIENT_SERVER_BYTES]; + } SteamBridgeClientEvent; + // result is the Steam EResult of a logon failure; reason is the EDenyReason of a deny or kick. + typedef struct SteamBridgeServerEvent + { + uint32_t kind; + int32_t result; + uint32_t secure; + uint32_t reason; + uint64_t steamID; + uint64_t ownerSteamID; + char text[SB_SERVER_TEXT_BYTES]; + } SteamBridgeServerEvent; + typedef void(STEAMBRIDGE_CALL* SteamBridgeClientCallback)(void*, const SteamBridgeClientEvent*); + typedef void(STEAMBRIDGE_CALL* SteamBridgeServerCallback)(void*, const SteamBridgeServerEvent*); + + // Loads the runtime and, when initializeClient is nonzero, initializes the Steam client. + // A dedicated server passes zero and only uses the game server functions. + // SB_UNAVAILABLE: the runtime or a required export is missing; SB_FAILED: SteamAPI + // initialization failed (Steam is not running or the user does not own the application); + // SB_INVALID_ARGUMENT: the host session is already active. + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_HostInit(const char* runtimePath, uint32_t initializeClient); + // Shuts down the game server (if active) and the client, then unloads the runtime. + // Called from a host callback, the shutdown runs after the dispatcher returns. + STEAMBRIDGE_API void STEAMBRIDGE_CALL SteamBridge_HostShutdown(void); + STEAMBRIDGE_API uint32_t STEAMBRIDGE_CALL SteamBridge_HostIsActive(void); + STEAMBRIDGE_API uint32_t STEAMBRIDGE_CALL SteamBridge_HostIsClientActive(void); + // Dispatches client callbacks; events reach the client callback synchronously. + STEAMBRIDGE_API void STEAMBRIDGE_CALL SteamBridge_HostRunCallbacks(void); + STEAMBRIDGE_API void STEAMBRIDGE_CALL SteamBridge_HostSetClientCallback(SteamBridgeClientCallback callback, void* user); + + // Writes the client's connection ticket for a game server; *size receives its length. + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_UserInitiateGameConnection(void* ticket, uint32_t capacity, uint64_t serverSteamID, uint32_t serverIP, uint16_t serverPort, uint32_t secure, uint32_t* size); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_UserTerminateGameConnection(uint32_t serverIP, uint16_t serverPort); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_UserAdvertiseGame(uint64_t serverSteamID, uint32_t serverIP, uint16_t serverPort); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_UserGetSteamID(uint64_t* id); + // Copies the persona name, truncated and NUL-terminated. + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_UserGetPersonaName(char* name, uint32_t capacity); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_UserIsSubscribedApp(uint32_t appID, uint32_t* subscribed); + + // Voice. Get and Decompress succeed only for Steam's k_EVoiceResultOK; any other + // voice result returns SB_FAILED with zero lengths. + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_VoiceStartRecording(void); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_VoiceStopRecording(void); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_VoiceGetAvailable(uint32_t* compressedBytes); + // pcm may be NULL. Otherwise Steam also writes uncompressed PCM at pcmSampleRate. + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_VoiceGet(void* compressed, uint32_t capacity, uint32_t* compressedBytes, void* pcm, uint32_t pcmCapacity, uint32_t* pcmBytes, uint32_t pcmSampleRate); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_VoiceDecompress(const void* compressed, uint32_t bytes, void* pcm, uint32_t pcmCapacity, uint32_t* pcmBytes, uint32_t sampleRate); + STEAMBRIDGE_API uint32_t STEAMBRIDGE_CALL SteamBridge_VoiceGetOptimalSampleRate(void); + + // Game server. mode is an SB_SERVER_MODE_* value. + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerInit(uint32_t serverIP, uint16_t gamePort, uint16_t queryPort, int32_t mode, const char* version); + // Called from a host callback, the shutdown runs after the dispatcher returns. + STEAMBRIDGE_API void STEAMBRIDGE_CALL SteamBridge_ServerShutdown(void); + STEAMBRIDGE_API uint32_t STEAMBRIDGE_CALL SteamBridge_ServerIsActive(void); + // Dispatches game server callbacks; events reach the server callback synchronously. + STEAMBRIDGE_API void STEAMBRIDGE_CALL SteamBridge_ServerRunCallbacks(void); + STEAMBRIDGE_API void STEAMBRIDGE_CALL SteamBridge_ServerSetCallback(SteamBridgeServerCallback callback, void* user); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSetProduct(const char* product); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSetModDir(const char* modDir); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSetDedicatedServer(uint32_t dedicated); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSetGameDescription(const char* description); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerLogOnAnonymous(void); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerLogOff(void); + STEAMBRIDGE_API uint32_t STEAMBRIDGE_CALL SteamBridge_ServerIsLoggedOn(void); + STEAMBRIDGE_API uint32_t STEAMBRIDGE_CALL SteamBridge_ServerIsSecure(void); + STEAMBRIDGE_API uint64_t STEAMBRIDGE_CALL SteamBridge_ServerGetSteamID(void); + STEAMBRIDGE_API uint32_t STEAMBRIDGE_CALL SteamBridge_ServerWasRestartRequested(void); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSetAdvertiseServerActive(uint32_t active); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSetMaxPlayerCount(int32_t players); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSetBotPlayerCount(int32_t bots); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSetServerName(const char* name); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSetMapName(const char* map); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSetPasswordProtected(uint32_t passwordProtected); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerClearAllKeyValues(void); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSetKeyValue(const char* key, const char* value); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSendUserConnectAndAuthenticate(uint32_t clientIP, const void* ticket, uint32_t bytes, uint64_t* steamID); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerCreateUnauthenticatedUserConnection(uint64_t* steamID); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerSendUserDisconnect(uint64_t steamID); + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerUpdateUserData(uint64_t steamID, const char* name, uint32_t score); + // Shared-socket master server traffic. + STEAMBRIDGE_API SteamBridgeStatus STEAMBRIDGE_CALL SteamBridge_ServerHandleIncomingPacket(const void* data, uint32_t bytes, uint32_t ip, uint16_t port); + // Returns the packet length, or zero when no packet is pending. + STEAMBRIDGE_API uint32_t STEAMBRIDGE_CALL SteamBridge_ServerGetNextOutgoingPacket(void* data, uint32_t capacity, uint32_t* ip, uint16_t* port); + #ifdef __cplusplus } #endif diff --git a/scripts/build-SteamAPIBridge-linux.sh b/scripts/build-SteamAPIBridge-linux.sh new file mode 100755 index 0000000..fe85708 --- /dev/null +++ b/scripts/build-SteamAPIBridge-linux.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Usage: build-SteamAPIBridge-linux.sh [CMake options] +set -e +case "$1" in x86) bits=32 ;; x64) bits=64 ;; *) exit 2 ;; esac +case "$2" in Debug|Release) ;; *) exit 2 ;; esac +arch=$1 +configuration=$2 +shift 2 +source_dir=$(cd "$(dirname "$0")/.." && pwd) +build_dir="$source_dir/build/linux-$arch/$configuration" +cmake -S "$source_dir" -B "$build_dir" -DCMAKE_BUILD_TYPE="$configuration" \ + -DCMAKE_CXX_FLAGS="-m$bits" -DCMAKE_SHARED_LINKER_FLAGS="-m$bits" -DCMAKE_EXE_LINKER_FLAGS="-m$bits" \ + -DCMAKE_INSTALL_PREFIX="$source_dir/install/linux-$arch/$configuration" "$@" +cmake --build "$build_dir" --parallel +ctest --test-dir "$build_dir" --output-on-failure +cmake --install "$build_dir" diff --git a/scripts/build-SteamAPIBridge-windows.bat b/scripts/build-SteamAPIBridge-windows.bat new file mode 100644 index 0000000..ecb114a --- /dev/null +++ b/scripts/build-SteamAPIBridge-windows.bat @@ -0,0 +1,15 @@ +@echo off +setlocal +if not "%Configuration%"=="Debug" if not "%Configuration%"=="Release" exit /b 2 +if not "%Arch%"=="x86" if not "%Arch%"=="x64" exit /b 2 +if "%Arch%"=="x86" (set "Platform=Win32") else (set "Platform=x64") +for %%I in ("%~dp0..") do set "TaskSourceDir=%%~fI" +set "TaskBuildDir=%TaskSourceDir%\build\%Arch%\%Configuration%" +cmake -G "Visual Studio 17 2022" -A %Platform% -S "%TaskSourceDir%" -B "%TaskBuildDir%" -DCMAKE_INSTALL_PREFIX="%TaskSourceDir%\install\%Arch%\%Configuration%" %* +if errorlevel 1 exit /b %errorlevel% +cmake --build "%TaskBuildDir%" --config %Configuration% --parallel +if errorlevel 1 exit /b %errorlevel% +ctest --test-dir "%TaskBuildDir%" -C %Configuration% --output-on-failure +if errorlevel 1 exit /b %errorlevel% +cmake --install "%TaskBuildDir%" --config %Configuration% +exit /b %errorlevel% diff --git a/scripts/build-SteamAPIBridge-x64-Debug.bat b/scripts/build-SteamAPIBridge-x64-Debug.bat new file mode 100644 index 0000000..65ef4c2 --- /dev/null +++ b/scripts/build-SteamAPIBridge-x64-Debug.bat @@ -0,0 +1,5 @@ +@echo off +setlocal +set "Configuration=Debug" +call "%~dp0build-SteamAPIBridge-x64.bat" %* +exit /b %errorlevel% diff --git a/scripts/build-SteamAPIBridge-x64-Release.bat b/scripts/build-SteamAPIBridge-x64-Release.bat new file mode 100644 index 0000000..523f74f --- /dev/null +++ b/scripts/build-SteamAPIBridge-x64-Release.bat @@ -0,0 +1,5 @@ +@echo off +setlocal +set "Configuration=Release" +call "%~dp0build-SteamAPIBridge-x64.bat" %* +exit /b %errorlevel% diff --git a/scripts/build-SteamAPIBridge-x64.bat b/scripts/build-SteamAPIBridge-x64.bat new file mode 100644 index 0000000..ed1d9c7 --- /dev/null +++ b/scripts/build-SteamAPIBridge-x64.bat @@ -0,0 +1,5 @@ +@echo off +setlocal +set "Arch=x64" +call "%~dp0build-SteamAPIBridge-windows.bat" %* +exit /b %errorlevel% diff --git a/scripts/build-SteamAPIBridge-x86.bat b/scripts/build-SteamAPIBridge-x86.bat index 49c261e..c7ce764 100644 --- a/scripts/build-SteamAPIBridge-x86.bat +++ b/scripts/build-SteamAPIBridge-x86.bat @@ -1,13 +1,5 @@ @echo off setlocal -if not "%Configuration%"=="Debug" if not "%Configuration%"=="Release" exit /b 2 -for %%I in ("%~dp0..") do set "TaskSourceDir=%%~fI" -set "TaskBuildDir=%TaskSourceDir%\build\x86\%Configuration%" -cmake -G "Visual Studio 17 2022" -A Win32 -S "%TaskSourceDir%" -B "%TaskBuildDir%" -DCMAKE_INSTALL_PREFIX="%TaskSourceDir%\install\x86\%Configuration%" %* -if errorlevel 1 exit /b %errorlevel% -cmake --build "%TaskBuildDir%" --config %Configuration% --parallel -if errorlevel 1 exit /b %errorlevel% -ctest --test-dir "%TaskBuildDir%" -C %Configuration% --output-on-failure -if errorlevel 1 exit /b %errorlevel% -cmake --install "%TaskBuildDir%" --config %Configuration% +set "Arch=x86" +call "%~dp0build-SteamAPIBridge-windows.bat" %* exit /b %errorlevel% diff --git a/src/Host.cpp b/src/Host.cpp new file mode 100644 index 0000000..83b2264 --- /dev/null +++ b/src/Host.cpp @@ -0,0 +1,556 @@ +#include "Platform.h" +#include +#include +#include +#include +#include +#include + +namespace +{ +using platform::Resolve; +using InitFlatFn = ESteamAPIInitResult(S_CALLTYPE*)(SteamErrMsg*); +using GameServerInitFn = ESteamAPIInitResult(S_CALLTYPE*)(uint32, uint16, uint16, EServerMode, const char*, const char*, SteamErrMsg*); +using VoidFn = void(S_CALLTYPE*)(); +using GetUserFn = HSteamUser(S_CALLTYPE*)(); +using FindInterfaceFn = void*(S_CALLTYPE*)(HSteamUser, const char*); +using RegisterCallbackFn = void(S_CALLTYPE*)(CCallbackBase*, int); +using UnregisterFn = void(S_CALLTYPE*)(CCallbackBase*); + +// Keep in sync with SteamGameServer_InitEx in steam/steam_gameserver.h. +constexpr char GameServerInterfaceVersions[] = + STEAMUTILS_INTERFACE_VERSION "\0" STEAMNETWORKINGUTILS_INTERFACE_VERSION "\0" STEAMGAMESERVER_INTERFACE_VERSION "\0" STEAMGAMESERVERSTATS_INTERFACE_VERSION "\0" STEAMHTTP_INTERFACE_VERSION "\0" STEAMINVENTORY_INTERFACE_VERSION "\0" STEAMNETWORKING_INTERFACE_VERSION "\0" STEAMNETWORKINGMESSAGES_INTERFACE_VERSION "\0" STEAMNETWORKINGSOCKETS_INTERFACE_VERSION "\0" STEAMUGC_INTERFACE_VERSION "\0" + "\0"; + +struct HostCallback; +struct Host +{ + platform::Module module{}; + InitFlatFn initFlat{}; + VoidFn shutdown{}, runCallbacks{}, serverShutdown{}, serverRunCallbacks{}; + GetUserFn getUser{}, serverGetUser{}; + FindInterfaceFn findUser{}, findServer{}; + GameServerInitFn serverInit{}; + RegisterCallbackFn registerCallback{}; + UnregisterFn unregisterCallback{}; + ISteamUser* user{}; + ISteamFriends* friends{}; + ISteamApps* apps{}; + ISteamGameServer* server{}; + bool client{}; + SteamBridgeClientCallback clientFn{}; + void* clientUser{}; + SteamBridgeServerCallback serverFn{}; + void* serverUser{}; + std::vector> clientCallbacks, serverCallbacks; + // Shutdown requested by a host callback runs after the native dispatcher returns. + unsigned dispatchDepth{}; + bool pendingServerShutdown{}, pendingHostShutdown{}; +} host; + +// Copies a truncated, NUL-terminated string; capacity must be nonzero. +void CopyText(char* destination, size_t capacity, const char* source) +{ + size_t length = strnlen(source, capacity - 1); + std::memcpy(destination, source, length); + destination[length] = 0; +} +template void CopyText(char (&destination)[Size], const char* source) { CopyText(destination, Size, source); } +struct HostCallback final : CCallbackBase +{ + int size; + HostCallback(int id, int bytes, bool gameServer) : size(bytes) + { + m_iCallback = id; + if (gameServer) m_nCallbackFlags |= k_ECallbackFlagsGameServer; + } + int GetCallbackSizeBytes() override { return size; } + void Run(void* payload, bool, SteamAPICall_t) override { Run(payload); } + void Run(void* payload) override + { + if (!payload) return; + if (m_nCallbackFlags & k_ECallbackFlagsGameServer) RunServer(payload); + else + RunClient(payload); + } + void RunClient(void* payload) + { + SteamBridgeClientEvent event{}; + if (m_iCallback == ClientGameServerDeny_t::k_iCallback) + { + auto p = static_cast(payload); + event.kind = SB_CLIENT_GAMESERVER_DENY; + event.serverIP = p->m_unGameServerIP; + event.serverPort = p->m_usGameServerPort; + event.secure = p->m_bSecure; + event.reason = p->m_uReason; + } + else if (m_iCallback == GameServerChangeRequested_t::k_iCallback) + { + auto p = static_cast(payload); + event.kind = SB_CLIENT_GAMESERVER_CHANGE; + CopyText(event.server, p->m_rgchServer); + CopyText(event.password, p->m_rgchPassword); + } + else + { + event.kind = SB_CLIENT_OVERLAY; + event.active = static_cast(payload)->m_bActive != 0; + } + Dispatch(host.clientFn, host.clientUser, &event); + } + void RunServer(void* payload) + { + SteamBridgeServerEvent event{}; + switch (m_iCallback) + { + case SteamServersConnected_t::k_iCallback: + event.kind = SB_SERVER_LOGON_SUCCESS; + break; + case SteamServerConnectFailure_t::k_iCallback: + event.kind = SB_SERVER_LOGON_FAILURE; + event.result = static_cast(payload)->m_eResult; + break; + case GSPolicyResponse_t::k_iCallback: + event.kind = SB_SERVER_POLICY; + event.secure = static_cast(payload)->m_bSecure != 0; + break; + case GSClientApprove_t::k_iCallback: + { + auto p = static_cast(payload); + event.kind = SB_SERVER_CLIENT_APPROVE; + event.steamID = p->m_SteamID.ConvertToUint64(); + event.ownerSteamID = p->m_OwnerSteamID.ConvertToUint64(); + break; + } + case GSClientDeny_t::k_iCallback: + { + auto p = static_cast(payload); + event.kind = SB_SERVER_CLIENT_DENY; + event.steamID = p->m_SteamID.ConvertToUint64(); + event.reason = p->m_eDenyReason; + CopyText(event.text, p->m_rgchOptionalText); + break; + } + default: + { + auto p = static_cast(payload); + event.kind = SB_SERVER_CLIENT_KICK; + event.steamID = p->m_SteamID.ConvertToUint64(); + event.reason = p->m_eDenyReason; + break; + } + } + Dispatch(host.serverFn, host.serverUser, &event); + } + template static void Dispatch(F fn, void* user, const E* event) + { + if (!fn) return; + ++host.dispatchDepth; + // Exceptions must not cross the C callback boundary. + try + { + fn(user, event); + } + catch (...) + {} + --host.dispatchDepth; + } +}; +template void Register(std::vector>& list, bool gameServer) +{ + auto callback = std::make_unique(T::k_iCallback, int(sizeof(T)), gameServer); + host.registerCallback(callback.get(), T::k_iCallback); + list.push_back(std::move(callback)); +} +void Unregister(std::vector>& list) +{ + for (auto& callback : list) + host.unregisterCallback(callback.get()); + list.clear(); +} +void ShutdownServer() +{ + if (!host.server) return; + Unregister(host.serverCallbacks); + host.server = nullptr; + host.serverShutdown(); +} +void ShutdownHost() +{ + if (!host.module) return; + ShutdownServer(); + Unregister(host.clientCallbacks); + if (host.client) host.shutdown(); + platform::UnloadRuntime(host.module); + auto clientFn = host.clientFn; + auto clientUser = host.clientUser; + auto serverFn = host.serverFn; + auto serverUser = host.serverUser; + host = Host{}; + host.clientFn = clientFn; + host.clientUser = clientUser; + host.serverFn = serverFn; + host.serverUser = serverUser; +} +void RunPendingShutdown() +{ + if (host.dispatchDepth) return; + if (host.pendingHostShutdown) ShutdownHost(); + else if (host.pendingServerShutdown) + ShutdownServer(); + host.pendingHostShutdown = false; + host.pendingServerShutdown = false; +} +bool Resolved(const Host& h) +{ + return h.initFlat && h.shutdown && h.runCallbacks && h.getUser && h.findUser && h.serverInit && h.serverShutdown && h.serverRunCallbacks && h.serverGetUser && h.findServer && h.registerCallback && h.unregisterCallback; +} +SteamBridgeStatus Result(bool value) { return value ? SB_OK : SB_FAILED; } +template SteamBridgeStatus Server(F&& fn) +{ + if (!host.server) return SB_UNAVAILABLE; + fn(*host.server); + return SB_OK; +} +} // namespace + +SteamBridgeStatus SteamBridge_HostInit(const char* runtimePath, uint32_t initializeClient) +{ + if (host.module) return SB_INVALID_ARGUMENT; + try + { + auto module = platform::LoadRuntime(runtimePath); + if (!module) return SB_UNAVAILABLE; + Host h{}; + h.module = module; + h.initFlat = Resolve(module, "SteamAPI_InitFlat"); + h.shutdown = Resolve(module, "SteamAPI_Shutdown"); + h.runCallbacks = Resolve(module, "SteamAPI_RunCallbacks"); + h.getUser = Resolve(module, "SteamAPI_GetHSteamUser"); + h.findUser = Resolve(module, "SteamInternal_FindOrCreateUserInterface"); + h.serverInit = Resolve(module, "SteamInternal_GameServer_Init_V2"); + h.serverShutdown = Resolve(module, "SteamGameServer_Shutdown"); + h.serverRunCallbacks = Resolve(module, "SteamGameServer_RunCallbacks"); + h.serverGetUser = Resolve(module, "SteamGameServer_GetHSteamUser"); + h.findServer = Resolve(module, "SteamInternal_FindOrCreateGameServerInterface"); + h.registerCallback = Resolve(module, "SteamAPI_RegisterCallback"); + h.unregisterCallback = Resolve(module, "SteamAPI_UnregisterCallback"); + if (!Resolved(h)) + { + platform::UnloadRuntime(module); + return SB_UNAVAILABLE; + } + if (initializeClient) + { + SteamErrMsg message{}; + if (h.initFlat(&message) != k_ESteamAPIInitResult_OK) + { + platform::UnloadRuntime(module); + return SB_FAILED; + } + HSteamUser steamUser = h.getUser(); + h.client = true; + h.user = static_cast(h.findUser(steamUser, STEAMUSER_INTERFACE_VERSION)); + h.friends = static_cast(h.findUser(steamUser, STEAMFRIENDS_INTERFACE_VERSION)); + h.apps = static_cast(h.findUser(steamUser, STEAMAPPS_INTERFACE_VERSION)); + } + h.clientFn = host.clientFn; + h.clientUser = host.clientUser; + h.serverFn = host.serverFn; + h.serverUser = host.serverUser; + host = std::move(h); + if (host.client) + { + Register(host.clientCallbacks, false); + Register(host.clientCallbacks, false); + Register(host.clientCallbacks, false); + } + return SB_OK; + } + catch (...) + { + ShutdownHost(); + return SB_FAILED; + } +} +void SteamBridge_HostShutdown() +{ + host.pendingHostShutdown = true; + RunPendingShutdown(); +} +uint32_t SteamBridge_HostIsActive() { return host.module != nullptr; } +uint32_t SteamBridge_HostIsClientActive() { return host.client; } +void SteamBridge_HostRunCallbacks() +{ + if (!host.client) return; + ++host.dispatchDepth; + host.runCallbacks(); + --host.dispatchDepth; + RunPendingShutdown(); +} +void SteamBridge_HostSetClientCallback(SteamBridgeClientCallback callback, void* user) +{ + host.clientFn = callback; + host.clientUser = user; +} + +SteamBridgeStatus SteamBridge_UserInitiateGameConnection(void* ticket, uint32_t capacity, uint64_t serverSteamID, uint32_t serverIP, uint16_t serverPort, uint32_t secure, uint32_t* size) +{ + if (!size) return SB_INVALID_ARGUMENT; + *size = 0; + if (!ticket || !capacity) return SB_INVALID_ARGUMENT; + if (!host.user) return SB_UNAVAILABLE; + int bytes = host.user->InitiateGameConnection_DEPRECATED(ticket, int(capacity), CSteamID(uint64(serverSteamID)), serverIP, serverPort, secure != 0); + if (bytes <= 0 || uint32_t(bytes) > capacity) return SB_FAILED; + *size = uint32_t(bytes); + return SB_OK; +} +SteamBridgeStatus SteamBridge_UserTerminateGameConnection(uint32_t serverIP, uint16_t serverPort) +{ + if (!host.user) return SB_UNAVAILABLE; + host.user->TerminateGameConnection_DEPRECATED(serverIP, serverPort); + return SB_OK; +} +SteamBridgeStatus SteamBridge_UserAdvertiseGame(uint64_t serverSteamID, uint32_t serverIP, uint16_t serverPort) +{ + if (!host.user) return SB_UNAVAILABLE; + host.user->AdvertiseGame(CSteamID(uint64(serverSteamID)), serverIP, serverPort); + return SB_OK; +} +SteamBridgeStatus SteamBridge_UserGetSteamID(uint64_t* id) +{ + if (!id) return SB_INVALID_ARGUMENT; + *id = 0; + if (!host.user) return SB_UNAVAILABLE; + *id = host.user->GetSteamID().ConvertToUint64(); + return *id ? SB_OK : SB_UNAVAILABLE; +} +SteamBridgeStatus SteamBridge_UserGetPersonaName(char* name, uint32_t capacity) +{ + if (!name || !capacity) return SB_INVALID_ARGUMENT; + name[0] = 0; + if (!host.friends) return SB_UNAVAILABLE; + const char* persona = host.friends->GetPersonaName(); + if (!persona) return SB_FAILED; + CopyText(name, capacity, persona); + return SB_OK; +} +SteamBridgeStatus SteamBridge_UserIsSubscribedApp(uint32_t appID, uint32_t* subscribed) +{ + if (!subscribed) return SB_INVALID_ARGUMENT; + *subscribed = 0; + if (!host.apps) return SB_UNAVAILABLE; + *subscribed = host.apps->BIsSubscribedApp(appID); + return SB_OK; +} + +SteamBridgeStatus SteamBridge_VoiceStartRecording() +{ + if (!host.user) return SB_UNAVAILABLE; + host.user->StartVoiceRecording(); + return SB_OK; +} +SteamBridgeStatus SteamBridge_VoiceStopRecording() +{ + if (!host.user) return SB_UNAVAILABLE; + host.user->StopVoiceRecording(); + return SB_OK; +} +SteamBridgeStatus SteamBridge_VoiceGetAvailable(uint32_t* compressedBytes) +{ + if (!compressedBytes) return SB_INVALID_ARGUMENT; + *compressedBytes = 0; + if (!host.user) return SB_UNAVAILABLE; + uint32 bytes{}; + if (host.user->GetAvailableVoice(&bytes) != k_EVoiceResultOK) return SB_FAILED; + *compressedBytes = bytes; + return SB_OK; +} +SteamBridgeStatus SteamBridge_VoiceGet(void* compressed, uint32_t capacity, uint32_t* compressedBytes, void* pcm, uint32_t pcmCapacity, uint32_t* pcmBytes, uint32_t pcmSampleRate) +{ + if (!compressedBytes || !pcmBytes) return SB_INVALID_ARGUMENT; + *compressedBytes = 0; + *pcmBytes = 0; + if (!compressed || !capacity || (pcm && !pcmCapacity)) return SB_INVALID_ARGUMENT; + if (!host.user) return SB_UNAVAILABLE; + uint32 written{}, pcmWritten{}; + bool wantPCM = pcm != nullptr; + if (host.user->GetVoice(true, compressed, capacity, &written, wantPCM, pcm, wantPCM ? pcmCapacity : 0, wantPCM ? &pcmWritten : nullptr, wantPCM ? pcmSampleRate : 0) != k_EVoiceResultOK) return SB_FAILED; + if (written > capacity || pcmWritten > pcmCapacity) return SB_FAILED; + *compressedBytes = written; + *pcmBytes = pcmWritten; + return SB_OK; +} +SteamBridgeStatus SteamBridge_VoiceDecompress(const void* compressed, uint32_t bytes, void* pcm, uint32_t pcmCapacity, uint32_t* pcmBytes, uint32_t sampleRate) +{ + if (!pcmBytes) return SB_INVALID_ARGUMENT; + *pcmBytes = 0; + if (!compressed || !bytes || !pcm || !pcmCapacity) return SB_INVALID_ARGUMENT; + if (!host.user) return SB_UNAVAILABLE; + uint32 written{}; + if (host.user->DecompressVoice(compressed, bytes, pcm, pcmCapacity, &written, sampleRate) != k_EVoiceResultOK || written > pcmCapacity) return SB_FAILED; + *pcmBytes = written; + return SB_OK; +} +uint32_t SteamBridge_VoiceGetOptimalSampleRate() { return host.user ? host.user->GetVoiceOptimalSampleRate() : 0; } + +SteamBridgeStatus SteamBridge_ServerInit(uint32_t serverIP, uint16_t gamePort, uint16_t queryPort, int32_t mode, const char* version) +{ + if (!version || mode < SB_SERVER_MODE_NO_AUTHENTICATION || mode > SB_SERVER_MODE_SECURE) return SB_INVALID_ARGUMENT; + if (!host.module) return SB_UNAVAILABLE; + if (host.server) return SB_INVALID_ARGUMENT; + SteamErrMsg message{}; + if (host.serverInit(serverIP, gamePort, queryPort, static_cast(mode), version, GameServerInterfaceVersions, &message) != k_ESteamAPIInitResult_OK) return SB_FAILED; + auto server = static_cast(host.findServer(host.serverGetUser(), STEAMGAMESERVER_INTERFACE_VERSION)); + if (!server) + { + host.serverShutdown(); + return SB_FAILED; + } + try + { + Register(host.serverCallbacks, true); + Register(host.serverCallbacks, true); + Register(host.serverCallbacks, true); + Register(host.serverCallbacks, true); + Register(host.serverCallbacks, true); + Register(host.serverCallbacks, true); + } + catch (...) + { + Unregister(host.serverCallbacks); + host.serverShutdown(); + return SB_FAILED; + } + host.server = server; + return SB_OK; +} +void SteamBridge_ServerShutdown() +{ + host.pendingServerShutdown = true; + RunPendingShutdown(); +} +uint32_t SteamBridge_ServerIsActive() { return host.server != nullptr; } +void SteamBridge_ServerRunCallbacks() +{ + if (!host.server) return; + ++host.dispatchDepth; + host.serverRunCallbacks(); + --host.dispatchDepth; + RunPendingShutdown(); +} +void SteamBridge_ServerSetCallback(SteamBridgeServerCallback callback, void* user) +{ + host.serverFn = callback; + host.serverUser = user; +} +SteamBridgeStatus SteamBridge_ServerSetProduct(const char* product) +{ + if (!product) return SB_INVALID_ARGUMENT; + return Server([&](ISteamGameServer& api) { api.SetProduct(product); }); +} +SteamBridgeStatus SteamBridge_ServerSetModDir(const char* modDir) +{ + if (!modDir) return SB_INVALID_ARGUMENT; + return Server([&](ISteamGameServer& api) { api.SetModDir(modDir); }); +} +SteamBridgeStatus SteamBridge_ServerSetDedicatedServer(uint32_t dedicated) +{ + return Server([&](ISteamGameServer& api) { api.SetDedicatedServer(dedicated != 0); }); +} +SteamBridgeStatus SteamBridge_ServerSetGameDescription(const char* description) +{ + if (!description) return SB_INVALID_ARGUMENT; + return Server([&](ISteamGameServer& api) { api.SetGameDescription(description); }); +} +SteamBridgeStatus SteamBridge_ServerLogOnAnonymous() +{ + return Server([](ISteamGameServer& api) { api.LogOnAnonymous(); }); +} +SteamBridgeStatus SteamBridge_ServerLogOff() +{ + return Server([](ISteamGameServer& api) { api.LogOff(); }); +} +uint32_t SteamBridge_ServerIsLoggedOn() { return host.server && host.server->BLoggedOn(); } +uint32_t SteamBridge_ServerIsSecure() { return host.server && host.server->BSecure(); } +uint64_t SteamBridge_ServerGetSteamID() { return host.server ? host.server->GetSteamID().ConvertToUint64() : 0; } +uint32_t SteamBridge_ServerWasRestartRequested() { return host.server && host.server->WasRestartRequested(); } +SteamBridgeStatus SteamBridge_ServerSetAdvertiseServerActive(uint32_t active) +{ + return Server([&](ISteamGameServer& api) { api.SetAdvertiseServerActive(active != 0); }); +} +SteamBridgeStatus SteamBridge_ServerSetMaxPlayerCount(int32_t players) +{ + return Server([&](ISteamGameServer& api) { api.SetMaxPlayerCount(players); }); +} +SteamBridgeStatus SteamBridge_ServerSetBotPlayerCount(int32_t bots) +{ + return Server([&](ISteamGameServer& api) { api.SetBotPlayerCount(bots); }); +} +SteamBridgeStatus SteamBridge_ServerSetServerName(const char* name) +{ + if (!name) return SB_INVALID_ARGUMENT; + return Server([&](ISteamGameServer& api) { api.SetServerName(name); }); +} +SteamBridgeStatus SteamBridge_ServerSetMapName(const char* map) +{ + if (!map) return SB_INVALID_ARGUMENT; + return Server([&](ISteamGameServer& api) { api.SetMapName(map); }); +} +SteamBridgeStatus SteamBridge_ServerSetPasswordProtected(uint32_t passwordProtected) +{ + return Server([&](ISteamGameServer& api) { api.SetPasswordProtected(passwordProtected != 0); }); +} +SteamBridgeStatus SteamBridge_ServerClearAllKeyValues() +{ + return Server([](ISteamGameServer& api) { api.ClearAllKeyValues(); }); +} +SteamBridgeStatus SteamBridge_ServerSetKeyValue(const char* key, const char* value) +{ + if (!key || !value) return SB_INVALID_ARGUMENT; + return Server([&](ISteamGameServer& api) { api.SetKeyValue(key, value); }); +} +SteamBridgeStatus SteamBridge_ServerSendUserConnectAndAuthenticate(uint32_t clientIP, const void* ticket, uint32_t bytes, uint64_t* steamID) +{ + if (!steamID) return SB_INVALID_ARGUMENT; + *steamID = 0; + if (!ticket || !bytes) return SB_INVALID_ARGUMENT; + if (!host.server) return SB_UNAVAILABLE; + CSteamID id; + bool accepted = host.server->SendUserConnectAndAuthenticate_DEPRECATED(clientIP, ticket, bytes, &id); + *steamID = id.ConvertToUint64(); + return Result(accepted); +} +SteamBridgeStatus SteamBridge_ServerCreateUnauthenticatedUserConnection(uint64_t* steamID) +{ + if (!steamID) return SB_INVALID_ARGUMENT; + *steamID = 0; + if (!host.server) return SB_UNAVAILABLE; + *steamID = host.server->CreateUnauthenticatedUserConnection().ConvertToUint64(); + return Result(*steamID != 0); +} +SteamBridgeStatus SteamBridge_ServerSendUserDisconnect(uint64_t steamID) +{ + return Server([&](ISteamGameServer& api) { api.SendUserDisconnect_DEPRECATED(CSteamID(uint64(steamID))); }); +} +SteamBridgeStatus SteamBridge_ServerUpdateUserData(uint64_t steamID, const char* name, uint32_t score) +{ + if (!name) return SB_INVALID_ARGUMENT; + if (!host.server) return SB_UNAVAILABLE; + return Result(host.server->BUpdateUserData(CSteamID(uint64(steamID)), name, score)); +} +SteamBridgeStatus SteamBridge_ServerHandleIncomingPacket(const void* data, uint32_t bytes, uint32_t ip, uint16_t port) +{ + if (!data || !bytes) return SB_INVALID_ARGUMENT; + if (!host.server) return SB_UNAVAILABLE; + return Result(host.server->HandleIncomingPacket(data, int(bytes), ip, port)); +} +uint32_t SteamBridge_ServerGetNextOutgoingPacket(void* data, uint32_t capacity, uint32_t* ip, uint16_t* port) +{ + if (!data || !capacity || !ip || !port || !host.server) return 0; + *ip = 0; + *port = 0; + int bytes = host.server->GetNextOutgoingPacket(data, int(capacity), ip, port); + return bytes > 0 && uint32_t(bytes) <= capacity ? uint32_t(bytes) : 0; +} diff --git a/src/Platform.h b/src/Platform.h new file mode 100644 index 0000000..64a1e94 --- /dev/null +++ b/src/Platform.h @@ -0,0 +1,78 @@ +#pragma once +#if defined(_WIN32) +# include +#else +# include +#endif +#include + +namespace platform +{ +#if defined(_WIN32) +using Module = HMODULE; +# if defined(_WIN64) +inline constexpr char RuntimeName[] = "steam_api64.dll"; +# else +inline constexpr char RuntimeName[] = "steam_api.dll"; +# endif +#else +using Module = void*; +inline constexpr char RuntimeName[] = "libsteam_api.so"; +#endif + +// Returns the already loaded runtime without taking a reference. +inline Module FindRuntime() +{ +#if defined(_WIN32) + return GetModuleHandleA(RuntimeName); +#else + Module module = dlopen(RuntimeName, RTLD_NOW | RTLD_NOLOAD); + if (module) dlclose(module); + return module; +#endif +} +inline std::string BridgeDirectory() +{ + static const int anchor = 0; +#if defined(_WIN32) + HMODULE self{}; + char path[MAX_PATH]{}; + if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast(&anchor), &self)) return {}; + DWORD length = GetModuleFileNameA(self, path, MAX_PATH); + if (!length || length == MAX_PATH) return {}; + std::string directory(path, length); +#else + Dl_info info{}; + if (!dladdr(&anchor, &info) || !info.dli_fname) return {}; + std::string directory(info.dli_fname); +#endif + auto separator = directory.find_last_of("/\\"); + return separator == std::string::npos ? std::string() : directory.substr(0, separator + 1); +} +// Loads path, or the platform runtime beside the bridge when path is null. +inline Module LoadRuntime(const char* path) +{ + std::string file = path ? std::string(path) : BridgeDirectory() + RuntimeName; +#if defined(_WIN32) + return LoadLibraryExA(file.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); +#else + return dlopen(file.c_str(), RTLD_NOW | RTLD_LOCAL); +#endif +} +inline void UnloadRuntime(Module module) +{ +#if defined(_WIN32) + FreeLibrary(module); +#else + dlclose(module); +#endif +} +template T Resolve(Module module, const char* name) +{ +#if defined(_WIN32) + return reinterpret_cast(GetProcAddress(module, name)); +#else + return reinterpret_cast(dlsym(module, name)); +#endif +} +} // namespace platform diff --git a/src/SteamAPIBridge.cpp b/src/SteamAPIBridge.cpp index 9ccf6c7..f0ed1a0 100644 --- a/src/SteamAPIBridge.cpp +++ b/src/SteamAPIBridge.cpp @@ -1,4 +1,4 @@ -#include +#include "Platform.h" #include #include #include "LegacyInterfaces.h" @@ -11,10 +11,10 @@ namespace { -template T Resolve(HMODULE module, const char* name) { return reinterpret_cast(GetProcAddress(module, name)); } +using platform::Resolve; struct Runtime { - HMODULE module{}; + platform::Module module{}; HSteamUser user{}; HSteamPipe pipe{}; decltype(&SteamAPI_RegisterCallback) registerCallback{}; @@ -29,7 +29,7 @@ struct Runtime Runtime() { - module = GetModuleHandleW(L"steam_api.dll"); + module = platform::FindRuntime(); if (!module) return; auto getUser = Resolve(module, "SteamAPI_GetHSteamUser"); auto getPipe = Resolve(module, "SteamAPI_GetHSteamPipe"); @@ -44,6 +44,8 @@ struct Runtime screenshots = static_cast(find(user, STEAMSCREENSHOTS_INTERFACE_VERSION)); http = static_cast(find(user, STEAMHTTP_INTERFACE_VERSION)); } +#if defined(_WIN32) && !defined(_WIN64) + // The GoldSrc 8684 runtime exists only for Windows x86. else if (auto getClient = Resolve(module, "SteamClient")) { if (auto client = getClient()) @@ -56,6 +58,7 @@ struct Runtime if (!screenshots) oldScreenshots = static_cast(client->GetISteamScreenshots(user, pipe, "STEAMSCREENSHOTS_INTERFACE_VERSION001")); } } +#endif } bool callbacks() const { return registerCallback && unregisterCallback; } bool httpReady() const { return http && callbacks() && registerResult && unregisterResult; } @@ -71,7 +74,7 @@ struct Request } // namespace struct SteamBridgeContext { - HMODULE module{}; + platform::Module module{}; HSteamUser user{}; HSteamPipe pipe{}; std::unordered_map requests; @@ -114,7 +117,7 @@ bool Bind(SteamBridgeContext& c, const Runtime& r) struct Callback final : CCallbackBase, std::enable_shared_from_this { std::weak_ptr owner; - HMODULE module; + platform::Module module; decltype(&SteamAPI_UnregisterCallback) unregisterCallback; decltype(&SteamAPI_UnregisterCallResult) unregisterResult; SteamAPICall_t call{}; @@ -126,7 +129,7 @@ struct Callback final : CCallbackBase, std::enable_shared_from_this { if (!active) return; active = false; - if (GetModuleHandleW(L"steam_api.dll") != module) return; + if (platform::FindRuntime() != module) return; if (call) unregisterResult(this, call); else unregisterCallback(this); @@ -363,8 +366,8 @@ SteamBridgeStatus SteamBridge_TagScreenshotUser(SteamBridgeContextHandle context if (!c) return SB_INVALID_ARGUMENT; Runtime r; if (!Bind(*c, r)) return SB_UNAVAILABLE; - if (r.screenshots) return Result(r.screenshots->TagUser(screenshot, CSteamID(id))); - if (r.oldScreenshots) return Result(r.oldScreenshots->TagUser(screenshot, CSteamID(id))); + if (r.screenshots) return Result(r.screenshots->TagUser(screenshot, CSteamID(uint64(id)))); + if (r.oldScreenshots) return Result(r.oldScreenshots->TagUser(screenshot, CSteamID(uint64(id)))); return SB_UNAVAILABLE; } SteamBridgeStatus SteamBridge_HTTPCreate(SteamBridgeContextHandle context, int32_t method, const char* url, uint32_t* request) @@ -411,7 +414,7 @@ SteamBridgeStatus SteamBridge_HTTPSend(SteamBridgeContextHandle context, uint32_ } SteamAPICall_t call{}; if (!(stream ? r.http->SendHTTPRequestAndStreamResponse(request, &call) : r.http->SendHTTPRequest(request, &call)) || !call) return SB_FAILED; - auto cb = std::make_shared(c, r, HTTPRequestCompleted_t::k_iCallback, sizeof(HTTPRequestCompleted_t)); + auto cb = std::make_shared(c, r, HTTPRequestCompleted_t::k_iCallback, int(sizeof(HTTPRequestCompleted_t))); cb->call = call; cb->request = request; cb->active = true; diff --git a/src/SteamAPIBridge.map b/src/SteamAPIBridge.map new file mode 100644 index 0000000..5ecd470 --- /dev/null +++ b/src/SteamAPIBridge.map @@ -0,0 +1,6 @@ +{ + global: + SteamBridge_*; + local: + *; +}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 58c8673..ad84a80 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,20 +1,64 @@ -add_executable(SteamBridgeUnavailable Unavailable.cpp) -target_link_libraries(SteamBridgeUnavailable PRIVATE SteamAPIBridge) -target_compile_options(SteamBridgeUnavailable PRIVATE /UNDEBUG) -add_custom_command(TARGET SteamBridgeUnavailable POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "$" "$") +if(MSVC) + set(steambridge_test_options /UNDEBUG) +else() + set(steambridge_test_options -UNDEBUG) +endif() +if(WIN32 AND CMAKE_SIZEOF_VOID_P EQUAL 8) + set(steambridge_runtime_name steam_api64) +else() + set(steambridge_runtime_name steam_api) +endif() +# Test executables share one directory, and a single target copies the bridge there; +# per-executable copies race in parallel builds. +set(steambridge_test_bin "${CMAKE_CURRENT_BINARY_DIR}/bin/$") +if(WIN32) + add_custom_target(SteamBridgeTestRuntime + COMMAND ${CMAKE_COMMAND} -E make_directory "${steambridge_test_bin}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "$" "${steambridge_test_bin}/$") + add_dependencies(SteamBridgeTestRuntime SteamAPIBridge) +endif() +function(steambridge_add_test_executable target) + add_executable(${target} ${ARGN}) + target_link_libraries(${target} PRIVATE SteamAPIBridge) + target_compile_features(${target} PRIVATE cxx_std_20) + target_compile_options(${target} PRIVATE ${steambridge_test_options}) + set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${steambridge_test_bin}") + if(WIN32) + add_dependencies(${target} SteamBridgeTestRuntime) + endif() +endfunction() + +steambridge_add_test_executable(SteamBridgeUnavailable Unavailable.cpp) add_test(NAME SteamBridge.Unavailable COMMAND SteamBridgeUnavailable) -foreach(kind Legacy Modern) - add_library(SteamBridgeMock${kind} SHARED MockRuntime.cpp ${kind}.def) - target_include_directories(SteamBridgeMock${kind} PRIVATE "${STEAMSDK_SOURCE_PATH}" "${PROJECT_SOURCE_DIR}/src") - target_compile_features(SteamBridgeMock${kind} PRIVATE cxx_std_20) - set_target_properties(SteamBridgeMock${kind} PROPERTIES OUTPUT_NAME steam_api RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${kind}" ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${kind}") -endforeach() -add_executable(SteamBridgeDispatch Dispatch.cpp) -target_link_libraries(SteamBridgeDispatch PRIVATE SteamAPIBridge) -target_compile_options(SteamBridgeDispatch PRIVATE /UNDEBUG) -add_custom_command(TARGET SteamBridgeDispatch POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "$" "$") -add_test(NAME SteamBridge.Legacy COMMAND SteamBridgeDispatch "$" legacy) -add_test(NAME SteamBridge.Modern COMMAND SteamBridgeDispatch "$" modern) -add_executable(SteamBridgeLoadSmoke LoadSmoke.cpp) -target_link_libraries(SteamBridgeLoadSmoke PRIVATE SteamAPIBridge) -add_custom_command(TARGET SteamBridgeLoadSmoke POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "$" "$") + +add_library(SteamBridgeMockHost SHARED MockHost.cpp) +target_include_directories(SteamBridgeMockHost PRIVATE "${STEAMSDK_SOURCE_PATH}") +target_compile_definitions(SteamBridgeMockHost PRIVATE STEAM_API_EXPORTS) +target_compile_features(SteamBridgeMockHost PRIVATE cxx_std_20) +steambridge_add_test_executable(SteamBridgeHost Host.cpp) +target_include_directories(SteamBridgeHost PRIVATE "${STEAMSDK_SOURCE_PATH}" "${PROJECT_SOURCE_DIR}/src") +target_link_libraries(SteamBridgeHost PRIVATE ${CMAKE_DL_LIBS}) +add_dependencies(SteamBridgeHost SteamBridgeMockHost) +add_test(NAME SteamBridge.Host COMMAND SteamBridgeHost "$" "${CMAKE_CURRENT_BINARY_DIR}/missing/${CMAKE_SHARED_LIBRARY_PREFIX}${steambridge_runtime_name}${CMAKE_SHARED_LIBRARY_SUFFIX}") + +if(WIN32) + # Plugin-mode fixtures find the runtime by its platform name. + set(steambridge_mock_kinds Modern) + if(CMAKE_SIZEOF_VOID_P EQUAL 4) + list(APPEND steambridge_mock_kinds Legacy) + endif() + foreach(kind IN LISTS steambridge_mock_kinds) + add_library(SteamBridgeMock${kind} SHARED MockRuntime.cpp ${kind}.def) + target_include_directories(SteamBridgeMock${kind} PRIVATE "${STEAMSDK_SOURCE_PATH}" "${PROJECT_SOURCE_DIR}/src") + target_compile_features(SteamBridgeMock${kind} PRIVATE cxx_std_20) + set_target_properties(SteamBridgeMock${kind} PROPERTIES OUTPUT_NAME ${steambridge_runtime_name} RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${kind}" ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${kind}") + endforeach() + steambridge_add_test_executable(SteamBridgeDispatch Dispatch.cpp) + foreach(kind IN LISTS steambridge_mock_kinds) + string(TOLOWER ${kind} mode) + add_test(NAME SteamBridge.${kind} COMMAND SteamBridgeDispatch "$" ${mode}) + endforeach() + steambridge_add_test_executable(SteamBridgeLoadSmoke LoadSmoke.cpp) +endif() +# Manual check against a real Steam client; see HostSmoke.cpp. +steambridge_add_test_executable(SteamBridgeHostSmoke HostSmoke.cpp) diff --git a/tests/Host.cpp b/tests/Host.cpp new file mode 100644 index 0000000..b549b0d --- /dev/null +++ b/tests/Host.cpp @@ -0,0 +1,234 @@ +#include "Platform.h" +#include "MockHost.h" +#include +#include +#include +#include +#include + +using SetIntFn = void(S_CALLTYPE*)(int); +using StatFn = int(S_CALLTYPE*)(int); +using ForwardedFn = const MockHostForwardedData*(S_CALLTYPE*)(); +using QueueFn = void(S_CALLTYPE*)(int, int, const void*, int); +namespace mock +{ +SetIntFn failInit, voiceResult; +StatFn stat; +ForwardedFn forwarded; +QueueFn queue; +} // namespace mock +using namespace mock; + +struct ClientEvents +{ + int count{}; + SteamBridgeClientEvent last{}; + bool shutdown{}; +}; +struct ServerEvents +{ + int count{}; + SteamBridgeServerEvent last{}; + bool shutdown{}; +}; +void STEAMBRIDGE_CALL OnClient(void* user, const SteamBridgeClientEvent* event) +{ + auto& e = *static_cast(user); + ++e.count; + e.last = *event; + if (e.shutdown) + { + SteamBridge_HostShutdown(); + // The bridge defers the shutdown until the dispatcher returns. + assert(SteamBridge_HostIsActive()); + } +} +void STEAMBRIDGE_CALL OnServer(void* user, const SteamBridgeServerEvent* event) +{ + auto& e = *static_cast(user); + ++e.count; + e.last = *event; + if (e.shutdown) SteamBridge_ServerShutdown(); +} +template void Queue(const T& payload, bool gameServer) { queue(T::k_iCallback, gameServer, &payload, int(sizeof(T))); } + +void Unavailable(const char* missing) +{ + assert(SB_UNAVAILABLE == SteamBridge_HostInit(missing, 1)); + assert(!SteamBridge_HostIsActive()); + uint32_t size = 9; + char ticket[8]; + assert(SB_UNAVAILABLE == SteamBridge_UserInitiateGameConnection(ticket, sizeof(ticket), 1, 2, 3, 0, &size)); + assert(0 == size); + assert(SB_UNAVAILABLE == SteamBridge_ServerInit(0, 27015, 27015, SB_SERVER_MODE_SECURE, "1.0")); + assert(0 == SteamBridge_VoiceGetOptimalSampleRate()); + SteamBridge_HostRunCallbacks(); + SteamBridge_HostShutdown(); +} +void Client(const char* mock) +{ + failInit(1); + assert(SB_FAILED == SteamBridge_HostInit(mock, 1)); + assert(!SteamBridge_HostIsActive()); + failInit(0); + ClientEvents events; + SteamBridge_HostSetClientCallback(OnClient, &events); + assert(SB_OK == SteamBridge_HostInit(mock, 1)); + assert(SB_INVALID_ARGUMENT == SteamBridge_HostInit(mock, 1)); + assert(SteamBridge_HostIsActive() && SteamBridge_HostIsClientActive()); + assert(3 == mock::stat(MOCK_HOST_CALLBACKS)); + + char ticket[8]{}; + uint32_t size{}; + assert(SB_OK == SteamBridge_UserInitiateGameConnection(ticket, sizeof(ticket), 90000000000000042, 0x7f000001, 27015, 1, &size)); + assert(4 == size && !std::memcmp(ticket, "tick", 4)); + assert(90000000000000042 == forwarded()->serverSteamID && 0x7f000001 == forwarded()->ip && 27015 == forwarded()->port && forwarded()->secure); + assert(SB_FAILED == SteamBridge_UserInitiateGameConnection(ticket, 2, 1, 2, 3, 0, &size)); + assert(0 == size); + assert(SB_OK == SteamBridge_UserTerminateGameConnection(0x0a000001, 27015)); + assert(0x0a000001 == forwarded()->terminated); + uint64_t id{}; + assert(SB_OK == SteamBridge_UserGetSteamID(&id)); + assert(76561198000000001 == id); + // The fixture exposes no SteamFriends/SteamApps; those calls report unavailability. + char name[4] = "x"; + assert(SB_UNAVAILABLE == SteamBridge_UserGetPersonaName(name, sizeof(name))); + assert(0 == name[0]); + uint32_t subscribed = 1; + assert(SB_UNAVAILABLE == SteamBridge_UserIsSubscribedApp(70, &subscribed)); + assert(0 == subscribed); + + assert(SB_OK == SteamBridge_VoiceStartRecording()); + uint32_t available{}; + assert(SB_OK == SteamBridge_VoiceGetAvailable(&available)); + assert(3 == available); + char voice[8]{}, pcm[8]{}; + uint32_t voiceBytes{}, pcmBytes{}; + assert(SB_OK == SteamBridge_VoiceGet(voice, sizeof(voice), &voiceBytes, nullptr, 0, &pcmBytes, 0)); + assert(3 == voiceBytes && 0 == pcmBytes && !forwarded()->pcmRequested); + assert(SB_OK == SteamBridge_VoiceGet(voice, sizeof(voice), &voiceBytes, pcm, sizeof(pcm), &pcmBytes, 11025)); + assert(3 == voiceBytes && 2 == pcmBytes && forwarded()->pcmRequested && 11025 == forwarded()->pcmRate); + short decoded[8]{}; + assert(SB_OK == SteamBridge_VoiceDecompress(voice, 3, decoded, sizeof(decoded), &pcmBytes, 11025)); + assert(6 == pcmBytes); + voiceResult(k_EVoiceResultNoData); + assert(SB_FAILED == SteamBridge_VoiceGet(voice, sizeof(voice), &voiceBytes, pcm, sizeof(pcm), &pcmBytes, 11025)); + assert(0 == voiceBytes && 0 == pcmBytes); + assert(SB_FAILED == SteamBridge_VoiceGetAvailable(&available)); + voiceResult(k_EVoiceResultOK); + assert(24000 == SteamBridge_VoiceGetOptimalSampleRate()); + assert(SB_OK == SteamBridge_VoiceStopRecording()); + + ClientGameServerDeny_t deny{}; + deny.m_unGameServerIP = 0x7f000001; + deny.m_usGameServerPort = 27015; + deny.m_bSecure = 1; + deny.m_uReason = 4; + Queue(deny, false); + GameServerChangeRequested_t change{}; + std::strcpy(change.m_rgchServer, "10.0.0.1:27015"); + std::strcpy(change.m_rgchPassword, "secret"); + Queue(change, false); + // Game server payloads are not dispatched by the client dispatcher. + Queue(GSPolicyResponse_t{1}, true); + SteamBridge_HostRunCallbacks(); + assert(2 == events.count && SB_CLIENT_GAMESERVER_CHANGE == events.last.kind); + assert(!std::strcmp("10.0.0.1:27015", events.last.server) && !std::strcmp("secret", events.last.password)); + assert(1 == mock::stat(MOCK_HOST_QUEUED)); + + GameOverlayActivated_t overlay{}; + overlay.m_bActive = 1; + Queue(overlay, false); + events.shutdown = true; + SteamBridge_HostRunCallbacks(); + assert(3 == events.count && SB_CLIENT_OVERLAY == events.last.kind && events.last.active); + assert(!SteamBridge_HostIsActive()); + assert(0 == mock::stat(MOCK_HOST_CALLBACKS) && 1 == mock::stat(MOCK_HOST_SHUTDOWNS)); + assert(SB_UNAVAILABLE == SteamBridge_UserGetSteamID(&id)); + SteamBridge_HostSetClientCallback(nullptr, nullptr); +} +void DedicatedServer(const char* mock) +{ + int shutdowns = mock::stat(MOCK_HOST_SHUTDOWNS); + assert(SB_OK == SteamBridge_HostInit(mock, 0)); + assert(SteamBridge_HostIsActive() && !SteamBridge_HostIsClientActive()); + uint64_t id{}; + assert(SB_UNAVAILABLE == SteamBridge_UserGetSteamID(&id)); + assert(SB_UNAVAILABLE == SteamBridge_ServerSetProduct("valve")); + assert(SB_INVALID_ARGUMENT == SteamBridge_ServerInit(0, 27015, 27015, 0, "1.0")); + assert(SB_OK == SteamBridge_ServerInit(0, 27015, 27015, SB_SERVER_MODE_SECURE, "1.0")); + assert(SB_SERVER_MODE_SECURE == forwarded()->mode); + assert(SB_INVALID_ARGUMENT == SteamBridge_ServerInit(0, 27015, 27015, SB_SERVER_MODE_SECURE, "1.0")); + assert(SteamBridge_ServerIsActive() && 6 == mock::stat(MOCK_HOST_CALLBACKS)); + assert(SB_OK == SteamBridge_ServerSetProduct("valve")); + assert(!std::strcmp("valve", forwarded()->product)); + assert(SB_OK == SteamBridge_ServerSetKeyValue("protocol", "48")); + assert(!std::strcmp("protocol", forwarded()->key) && !std::strcmp("48", forwarded()->value)); + assert(SteamBridge_ServerIsSecure()); + assert(90000000000000042 == SteamBridge_ServerGetSteamID()); + char ticket[4] = "abc"; + assert(SB_OK == SteamBridge_ServerSendUserConnectAndAuthenticate(0x0100007f, ticket, 3, &id)); + assert(76561198000000002 == id && 0x0100007f == forwarded()->authIP && 3 == forwarded()->authBytes); + assert(SB_FAILED == SteamBridge_ServerSendUserConnectAndAuthenticate(0x0100007f, ticket, 1, &id)); + char packet[4]{}; + uint32_t ip{}; + uint16_t port{}; + assert(2 == SteamBridge_ServerGetNextOutgoingPacket(packet, sizeof(packet), &ip, &port)); + assert(!std::memcmp(packet, "mp", 2) && 0x7f000001 == ip && 27010 == port); + assert(0 == SteamBridge_ServerGetNextOutgoingPacket(packet, 1, &ip, &port)); + + ServerEvents events; + SteamBridge_ServerSetCallback(OnServer, &events); + SteamServerConnectFailure_t failure{}; + failure.m_eResult = k_EResultNoConnection; + Queue(failure, true); + Queue(GSPolicyResponse_t{1}, true); + GSClientApprove_t approve{}; + approve.m_SteamID = CSteamID(uint64(76561198000000002)); + approve.m_OwnerSteamID = CSteamID(uint64(76561198000000003)); + Queue(approve, true); + GSClientDeny_t deny{}; + deny.m_SteamID = CSteamID(uint64(76561198000000002)); + deny.m_eDenyReason = k_EDenyNotLoggedOn; + std::strcpy(deny.m_rgchOptionalText, "denied"); + Queue(deny, true); + SteamBridge_ServerRunCallbacks(); + // The policy payload that the client dispatcher left queued arrives here too. + assert(5 == events.count && SB_SERVER_CLIENT_DENY == events.last.kind && 0 == mock::stat(MOCK_HOST_QUEUED)); + assert(76561198000000002 == events.last.steamID && k_EDenyNotLoggedOn == int(events.last.reason) && !std::strcmp("denied", events.last.text)); + + GSClientKick_t kick{}; + kick.m_SteamID = CSteamID(uint64(76561198000000002)); + kick.m_eDenyReason = k_EDenyCheater; + Queue(kick, true); + events.shutdown = true; + SteamBridge_ServerRunCallbacks(); + assert(6 == events.count && SB_SERVER_CLIENT_KICK == events.last.kind && k_EDenyCheater == int(events.last.reason)); + assert(!SteamBridge_ServerIsActive() && 0 == mock::stat(MOCK_HOST_CALLBACKS) && 1 == mock::stat(MOCK_HOST_SERVER_SHUTDOWNS)); + assert(SteamBridge_HostIsActive()); + SteamBridge_ServerSetCallback(nullptr, nullptr); + + // Host shutdown also shuts down an active game server; no client was initialized. + assert(SB_OK == SteamBridge_ServerInit(0, 27015, 27015, SB_SERVER_MODE_AUTHENTICATION, "1.0")); + SteamBridge_HostShutdown(); + assert(!SteamBridge_HostIsActive() && !SteamBridge_ServerIsActive()); + assert(2 == mock::stat(MOCK_HOST_SERVER_SHUTDOWNS) && shutdowns == mock::stat(MOCK_HOST_SHUTDOWNS) && 0 == mock::stat(MOCK_HOST_CALLBACKS)); +} + +int main(int argc, char** argv) +{ + assert(argc == 3); + // Hold a fixture reference so its counters persist across bridge sessions. + auto module = platform::LoadRuntime(argv[1]); + assert(module); + mock::failInit = platform::Resolve(module, "MockHostSetFailInit"); + mock::voiceResult = platform::Resolve(module, "MockHostSetVoiceResult"); + mock::stat = platform::Resolve(module, "MockHostStat"); + mock::forwarded = platform::Resolve(module, "MockHostForwarded"); + mock::queue = platform::Resolve(module, "MockHostQueue"); + assert(mock::failInit && mock::voiceResult && mock::stat && mock::forwarded && mock::queue); + Unavailable(argv[2]); + Client(argv[1]); + DedicatedServer(argv[1]); + platform::UnloadRuntime(module); +} diff --git a/tests/HostSmoke.cpp b/tests/HostSmoke.cpp new file mode 100644 index 0000000..3916c1f --- /dev/null +++ b/tests/HostSmoke.cpp @@ -0,0 +1,61 @@ +// Loader and authentication smoke check against a real Steam client. Not run by CTest: +// it needs a running, logged-in Steam client and steam_appid.txt in the working directory. +// Usage: SteamBridgeHostSmoke [seconds] +#include +#include +#include +#include +#include + +static bool approved, denied, loggedOn; +static void STEAMBRIDGE_CALL OnServer(void*, const SteamBridgeServerEvent* event) +{ + std::printf("server event %u result %d secure %u reason %u steamID %llu %s\n", event->kind, event->result, event->secure, event->reason, (unsigned long long)event->steamID, event->text); + loggedOn |= event->kind == SB_SERVER_LOGON_SUCCESS; + approved |= event->kind == SB_SERVER_CLIENT_APPROVE; + denied |= event->kind == SB_SERVER_CLIENT_DENY; +} +int main(int argc, char** argv) +{ + if (argc < 2) return 2; + int seconds = argc > 2 ? std::atoi(argv[2]) : 20; + if (SteamBridgeStatus status = SteamBridge_HostInit(argv[1], 1)) + { + std::printf("SteamBridge_HostInit failed: %d\n", status); + return 1; + } + uint64_t id{}; + char name[64]{}; + SteamBridge_UserGetSteamID(&id); + SteamBridge_UserGetPersonaName(name, sizeof(name)); + std::printf("client steamID %llu persona %s optimal voice rate %u\n", (unsigned long long)id, name, SteamBridge_VoiceGetOptimalSampleRate()); + SteamBridge_ServerSetCallback(OnServer, nullptr); + if (SteamBridge_ServerInit(0, 27115, 27115, SB_SERVER_MODE_AUTHENTICATION, "1.0.0.0") || SteamBridge_ServerSetProduct("valve") || SteamBridge_ServerSetModDir("valve") || SteamBridge_ServerSetGameDescription("Half-Life") || SteamBridge_ServerLogOnAnonymous()) + { + std::printf("game server initialization failed\n"); + SteamBridge_HostShutdown(); + return 1; + } + bool authenticated = false; + for (int tick = 0; tick < seconds * 10 && !approved && !denied; ++tick) + { + SteamBridge_HostRunCallbacks(); + SteamBridge_ServerRunCallbacks(); + if (loggedOn && !authenticated) + { + authenticated = true; + char ticket[2048]; + uint32_t size{}; + uint64_t serverID = SteamBridge_ServerGetSteamID(); + // 127.0.0.1 in host order for the client, network order for the server. + SteamBridgeStatus initiate = SteamBridge_UserInitiateGameConnection(ticket, sizeof(ticket), serverID, 0x7f000001, 27115, SteamBridge_ServerIsSecure(), &size); + uint64_t user{}; + SteamBridgeStatus connect = SteamBridge_ServerSendUserConnectAndAuthenticate(0x0100007f, ticket, size, &user); + std::printf("server steamID %llu ticket %u bytes (%d), connect %d user %llu\n", (unsigned long long)serverID, size, initiate, connect, (unsigned long long)user); + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + std::printf("logged on %d approved %d denied %d\n", loggedOn, approved, denied); + SteamBridge_HostShutdown(); + return approved ? 0 : 1; +} diff --git a/tests/HostStubs.h b/tests/HostStubs.h new file mode 100644 index 0000000..6da9365 --- /dev/null +++ b/tests/HostStubs.h @@ -0,0 +1,91 @@ +#pragma once +// Empty implementations of every SteamUser023 and SteamGameServer015 method, generated from +// the Steamworks SDK v1.65 declarations. Mocks override the methods they exercise. +#include +#include + +class StubUser : public ISteamUser +{ +public: + HSteamUser GetHSteamUser() override { return {}; } + bool BLoggedOn() override { return {}; } + CSteamID GetSteamID() override { return {}; } + int InitiateGameConnection_DEPRECATED(void* pAuthBlob, int cbMaxAuthBlob, CSteamID steamIDGameServer, uint32 unIPServer, uint16 usPortServer, bool bSecure) override { return {}; } + void TerminateGameConnection_DEPRECATED(uint32 unIPServer, uint16 usPortServer) override {} + void TrackAppUsageEvent(CGameID gameID, int eAppUsageEvent, const char* pchExtraInfo) override {} + bool GetUserDataFolder(char* pchBuffer, int cubBuffer) override { return {}; } + void StartVoiceRecording() override {} + void StopVoiceRecording() override {} + EVoiceResult GetAvailableVoice(uint32* pcbCompressed, uint32* pcbUncompressed_Deprecated, uint32 nUncompressedVoiceDesiredSampleRate_Deprecated) override { return {}; } + EVoiceResult GetVoice(bool bWantCompressed, void* pDestBuffer, uint32 cbDestBufferSize, uint32* nBytesWritten, bool bWantUncompressed_Deprecated, void* pUncompressedDestBuffer_Deprecated, uint32 cbUncompressedDestBufferSize_Deprecated, uint32* nUncompressBytesWritten_Deprecated, uint32 nUncompressedVoiceDesiredSampleRate_Deprecated) override { return {}; } + EVoiceResult DecompressVoice(const void* pCompressed, uint32 cbCompressed, void* pDestBuffer, uint32 cbDestBufferSize, uint32* nBytesWritten, uint32 nDesiredSampleRate) override { return {}; } + uint32 GetVoiceOptimalSampleRate() override { return {}; } + HAuthTicket GetAuthSessionTicket(void* pTicket, int cbMaxTicket, uint32* pcbTicket, const SteamNetworkingIdentity* pSteamNetworkingIdentity) override { return {}; } + HAuthTicket GetAuthTicketForWebApi(const char* pchIdentity) override { return {}; } + EBeginAuthSessionResult BeginAuthSession(const void* pAuthTicket, int cbAuthTicket, CSteamID steamID) override { return {}; } + void EndAuthSession(CSteamID steamID) override {} + void CancelAuthTicket(HAuthTicket hAuthTicket) override {} + EUserHasLicenseForAppResult UserHasLicenseForApp(CSteamID steamID, AppId_t appID) override { return {}; } + bool BIsBehindNAT() override { return {}; } + void AdvertiseGame(CSteamID steamIDGameServer, uint32 unIPServer, uint16 usPortServer) override {} + SteamAPICall_t RequestEncryptedAppTicket(void* pDataToInclude, int cbDataToInclude) override { return {}; } + bool GetEncryptedAppTicket(void* pTicket, int cbMaxTicket, uint32* pcbTicket) override { return {}; } + int GetGameBadgeLevel(int nSeries, bool bFoil) override { return {}; } + int GetPlayerSteamLevel() override { return {}; } + SteamAPICall_t RequestStoreAuthURL(const char* pchRedirectURL) override { return {}; } + bool BIsPhoneVerified() override { return {}; } + bool BIsTwoFactorEnabled() override { return {}; } + bool BIsPhoneIdentifying() override { return {}; } + bool BIsPhoneRequiringVerification() override { return {}; } + SteamAPICall_t GetMarketEligibility() override { return {}; } + SteamAPICall_t GetDurationControl() override { return {}; } + bool BSetDurationControlOnlineState(EDurationControlOnlineState eNewState) override { return {}; } +}; +class StubGameServer : public ISteamGameServer +{ +public: + bool InitGameServer(uint32 unIP, uint16 usGamePort, uint16 usQueryPort, uint32 unFlags, AppId_t nGameAppId, const char* pchVersionString) override { return {}; } + void SetProduct(const char* pszProduct) override {} + void SetGameDescription(const char* pszGameDescription) override {} + void SetModDir(const char* pszModDir) override {} + void SetDedicatedServer(bool bDedicated) override {} + void LogOn(const char* pszToken) override {} + void LogOnAnonymous() override {} + void LogOff() override {} + bool BLoggedOn() override { return {}; } + bool BSecure() override { return {}; } + CSteamID GetSteamID() override { return {}; } + bool WasRestartRequested() override { return {}; } + void SetMaxPlayerCount(int cPlayersMax) override {} + void SetBotPlayerCount(int cBotplayers) override {} + void SetServerName(const char* pszServerName) override {} + void SetMapName(const char* pszMapName) override {} + void SetPasswordProtected(bool bPasswordProtected) override {} + void SetSpectatorPort(uint16 unSpectatorPort) override {} + void SetSpectatorServerName(const char* pszSpectatorServerName) override {} + void ClearAllKeyValues() override {} + void SetKeyValue(const char* pKey, const char* pValue) override {} + void SetGameTags(const char* pchGameTags) override {} + void SetGameData(const char* pchGameData) override {} + void SetRegion(const char* pszRegion) override {} + void SetAdvertiseServerActive(bool bActive) override {} + HAuthTicket GetAuthSessionTicket(void* pTicket, int cbMaxTicket, uint32* pcbTicket, const SteamNetworkingIdentity* pSnid) override { return {}; } + EBeginAuthSessionResult BeginAuthSession(const void* pAuthTicket, int cbAuthTicket, CSteamID steamID) override { return {}; } + void EndAuthSession(CSteamID steamID) override {} + void CancelAuthTicket(HAuthTicket hAuthTicket) override {} + EUserHasLicenseForAppResult UserHasLicenseForApp(CSteamID steamID, AppId_t appID) override { return {}; } + bool RequestUserGroupStatus(CSteamID steamIDUser, CSteamID steamIDGroup) override { return {}; } + void GetGameplayStats() override {} + SteamAPICall_t GetServerReputation() override { return {}; } + SteamIPAddress_t GetPublicIP() override { return {}; } + bool HandleIncomingPacket(const void* pData, int cbData, uint32 srcIP, uint16 srcPort) override { return {}; } + int GetNextOutgoingPacket(void* pOut, int cbMaxOut, uint32* pNetAdr, uint16* pPort) override { return {}; } + SteamAPICall_t AssociateWithClan(CSteamID steamIDClan) override { return {}; } + SteamAPICall_t ComputeNewPlayerCompatibility(CSteamID steamIDNewPlayer) override { return {}; } + bool SendUserConnectAndAuthenticate_DEPRECATED(uint32 unIPClient, const void* pvAuthBlob, uint32 cubAuthBlobSize, CSteamID* pSteamIDUser) override { return {}; } + CSteamID CreateUnauthenticatedUserConnection() override { return {}; } + void SendUserDisconnect_DEPRECATED(CSteamID steamIDUser) override {} + bool BUpdateUserData(CSteamID steamIDUser, const char* pchPlayerName, uint32 uScore) override { return {}; } + void SetMasterServerHeartbeatInterval_DEPRECATED(int iHeartbeatInterval) override {} + void ForceMasterServerHeartbeat_DEPRECATED() override {} +}; diff --git a/tests/MockHost.cpp b/tests/MockHost.cpp new file mode 100644 index 0000000..bf11036 --- /dev/null +++ b/tests/MockHost.cpp @@ -0,0 +1,165 @@ +// Host-mode fixture runtime. It exports the modern entry points that SteamBridge_HostInit +// resolves, records forwarded arguments and dispatches queued callback payloads. +#include "HostStubs.h" +#include "MockHost.h" +#include +#include +#include + +namespace +{ +int failInit, voiceResult = k_EVoiceResultOK; +int shutdowns, serverShutdowns; +bool serverInitialized; +MockHostForwardedData forwarded; +std::vector callbacks; +struct Queued +{ + int id; + bool gameServer; + std::vector payload; +}; +std::vector queue; + +struct Peek : CCallbackBase +{ + static bool GameServer(CCallbackBase* callback) { return static_cast(callback)->m_nCallbackFlags & k_ECallbackFlagsGameServer; } +}; +void Dispatch(bool gameServer) +{ + auto pending = std::move(queue); + queue.clear(); + for (auto& item : pending) + { + if (item.gameServer != gameServer) + { + queue.push_back(std::move(item)); + continue; + } + auto snapshot = callbacks; + for (auto callback : snapshot) + if (std::find(callbacks.begin(), callbacks.end(), callback) != callbacks.end() && callback->GetICallback() == item.id && Peek::GameServer(callback) == gameServer) + callback->Run(item.payload.data()); + } +} + +class User final : public StubUser +{ +public: + CSteamID GetSteamID() override { return CSteamID(uint64(76561198000000001)); } + int InitiateGameConnection_DEPRECATED(void* blob, int max, CSteamID server, uint32 ip, uint16 port, bool secure) override + { + forwarded.serverSteamID = server.ConvertToUint64(); + forwarded.ip = ip; + forwarded.port = port; + forwarded.secure = secure; + if (max < 4) return 0; + std::memcpy(blob, "tick", 4); + return 4; + } + void TerminateGameConnection_DEPRECATED(uint32 ip, uint16) override { forwarded.terminated = ip; } + EVoiceResult GetAvailableVoice(uint32* bytes, uint32*, uint32) override + { + *bytes = 3; + return EVoiceResult(voiceResult); + } + EVoiceResult GetVoice(bool, void* dest, uint32 size, uint32* written, bool wantPCM, void* pcm, uint32 pcmSize, uint32* pcmWritten, uint32 rate) override + { + if (size < 3) return k_EVoiceResultBufferTooSmall; + std::memcpy(dest, "abc", 3); + *written = 3; + forwarded.pcmRequested = wantPCM; + forwarded.pcmRate = rate; + if (wantPCM && pcmSize >= 2) + { + std::memcpy(pcm, "pc", 2); + *pcmWritten = 2; + } + return EVoiceResult(voiceResult); + } + EVoiceResult DecompressVoice(const void*, uint32 bytes, void* dest, uint32 size, uint32* written, uint32 rate) override + { + forwarded.pcmRate = rate; + if (size < bytes * 2) return k_EVoiceResultBufferTooSmall; + std::memset(dest, 1, bytes * 2); + *written = bytes * 2; + return EVoiceResult(voiceResult); + } + uint32 GetVoiceOptimalSampleRate() override { return 24000; } +} user; + +class GameServer final : public StubGameServer +{ +public: + void SetProduct(const char* product) override { std::strncpy(forwarded.product, product, sizeof(forwarded.product) - 1); } + bool BSecure() override { return true; } + CSteamID GetSteamID() override { return CSteamID(uint64(90000000000000042)); } + void SetKeyValue(const char* key, const char* value) override + { + std::strncpy(forwarded.key, key, sizeof(forwarded.key) - 1); + std::strncpy(forwarded.value, value, sizeof(forwarded.value) - 1); + } + bool SendUserConnectAndAuthenticate_DEPRECATED(uint32 ip, const void*, uint32 bytes, CSteamID* id) override + { + forwarded.authIP = ip; + forwarded.authBytes = bytes; + *id = CSteamID(uint64(76561198000000002)); + return bytes != 1; + } + int GetNextOutgoingPacket(void* out, int max, uint32* ip, uint16* port) override + { + if (max < 2) return 0; + std::memcpy(out, "mp", 2); + *ip = 0x7f000001; + *port = 27010; + return 2; + } +} server; +} // namespace + +extern "C" +{ + S_API ESteamAPIInitResult S_CALLTYPE SteamAPI_InitFlat(SteamErrMsg*) { return failInit ? k_ESteamAPIInitResult_NoSteamClient : k_ESteamAPIInitResult_OK; } + S_API void S_CALLTYPE SteamAPI_Shutdown() { ++shutdowns; } + S_API void S_CALLTYPE SteamAPI_RunCallbacks() { Dispatch(false); } + S_API HSteamUser S_CALLTYPE SteamAPI_GetHSteamUser() { return 1; } + S_API void* S_CALLTYPE SteamInternal_FindOrCreateUserInterface(HSteamUser, const char* version) { return !std::strcmp(version, STEAMUSER_INTERFACE_VERSION) ? &user : nullptr; } + S_API ESteamAPIInitResult S_CALLTYPE SteamInternal_GameServer_Init_V2(uint32, uint16, uint16, EServerMode mode, const char*, const char* versions, SteamErrMsg*) + { + forwarded.mode = mode; + // The bridge must pass the interface list that SteamGameServer_InitEx would pass. + if (!versions || std::strcmp(versions, STEAMUTILS_INTERFACE_VERSION)) return k_ESteamAPIInitResult_VersionMismatch; + serverInitialized = true; + return k_ESteamAPIInitResult_OK; + } + S_API void S_CALLTYPE SteamGameServer_Shutdown() + { + serverInitialized = false; + ++serverShutdowns; + } + S_API void S_CALLTYPE SteamGameServer_RunCallbacks() { Dispatch(true); } + S_API HSteamUser S_CALLTYPE SteamGameServer_GetHSteamUser() { return 2; } + S_API void* S_CALLTYPE SteamInternal_FindOrCreateGameServerInterface(HSteamUser, const char* version) { return serverInitialized && !std::strcmp(version, STEAMGAMESERVER_INTERFACE_VERSION) ? &server : nullptr; } + S_API void S_CALLTYPE SteamAPI_RegisterCallback(CCallbackBase* callback, int) { callbacks.push_back(callback); } + S_API void S_CALLTYPE SteamAPI_UnregisterCallback(CCallbackBase* callback) { std::erase(callbacks, callback); } + + // Fixture control. + S_API void S_CALLTYPE MockHostSetFailInit(int value) { failInit = value; } + S_API void S_CALLTYPE MockHostSetVoiceResult(int value) { voiceResult = value; } + S_API int S_CALLTYPE MockHostStat(int which) + { + switch (which) + { + case MOCK_HOST_SHUTDOWNS: return shutdowns; + case MOCK_HOST_SERVER_SHUTDOWNS: return serverShutdowns; + case MOCK_HOST_CALLBACKS: return int(callbacks.size()); + default: return int(queue.size()); + } + } + S_API const void* S_CALLTYPE MockHostForwarded() { return &forwarded; } + S_API void S_CALLTYPE MockHostQueue(int id, int gameServer, const void* payload, int bytes) + { + auto data = static_cast(payload); + queue.push_back({id, gameServer != 0, std::vector(data, data + bytes)}); + } +} diff --git a/tests/MockHost.h b/tests/MockHost.h new file mode 100644 index 0000000..ea89291 --- /dev/null +++ b/tests/MockHost.h @@ -0,0 +1,27 @@ +#pragma once +#include + +// Arguments that MockHost.cpp records from the bridge. +struct MockHostForwardedData +{ + uint64_t serverSteamID; + uint32_t ip; + uint16_t port; + bool secure; + uint32_t terminated; + char product[64]; + char key[64]; + char value[64]; + uint32_t authIP; + uint32_t authBytes; + uint32_t pcmRate; + int mode; + uint32_t pcmRequested; +}; +enum +{ + MOCK_HOST_SHUTDOWNS = 0, + MOCK_HOST_SERVER_SHUTDOWNS = 1, + MOCK_HOST_CALLBACKS = 2, + MOCK_HOST_QUEUED = 3 +}; diff --git a/tests/Modern.def b/tests/Modern.def index 6b4e58a..d4f4268 100644 --- a/tests/Modern.def +++ b/tests/Modern.def @@ -1,4 +1,3 @@ -LIBRARY steam_api EXPORTS SteamAPI_GetHSteamUser=MockGetUser SteamAPI_GetHSteamPipe=MockGetPipe