Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
diff --git a/dlls/xgameruntime/Makefile.in b/dlls/xgameruntime/Makefile.in
index 7387467..e8f98cc 100644
--- a/dlls/xgameruntime/Makefile.in
+++ b/dlls/xgameruntime/Makefile.in
@@ -1,8 +1,11 @@
MODULE = xgameruntime.dll
-IMPORTS = combase
+EXTRAINCL = $(XML2_PE_CFLAGS)
+IMPORTS = bcrypt combase shlwapi winhttp wininet ws2_32 $(XML2_PE_LIBS)
SOURCES = \
main.c \
+ userprovider.idl \
+ util.c \
xaccessibility.c \
xaccessibility.idl \
xappcapture.c \
diff --git a/dlls/xgameruntime/main.c b/dlls/xgameruntime/main.c
index e56e580..56fdf8e 100644
--- a/dlls/xgameruntime/main.c
+++ b/dlls/xgameruntime/main.c
@@ -19,25 +19,75 @@
*/
#include <initguid.h>
+#include <libxml/parser.h>
+#include <shlwapi.h>
+#include <bcrypt.h>
#include "private.h"
WINE_DEFAULT_DEBUG_CHANNEL(xgameruntime);
+char *msaAppId = NULL;
+UINT32 titleId = 0;
+char *storeId = NULL;
+char *packageFamilyName = NULL;
+
+static char *compute_package_family_name( const char *name, const char *publisher )
+{
+ static const char alphabet[] = "0123456789abcdefghjkmnpqrstvwxyz";
+ UINT64 bits = 0;
+ BYTE hash[32];
+ WCHAR *wide;
+ char *pfn;
+ int len;
+
+ if (!(len = MultiByteToWideChar( CP_UTF8, 0, publisher, -1, NULL, 0 ))) return NULL;
+ if (!(wide = calloc( len, sizeof(WCHAR) ))) return NULL;
+ MultiByteToWideChar( CP_UTF8, 0, publisher, -1, wide, len );
+ if (BCryptHash( BCRYPT_SHA256_ALG_HANDLE, NULL, 0, (BYTE *)wide, (len - 1) * sizeof(WCHAR), hash, sizeof(hash) ))
+ {
+ free( wide );
+ return NULL;
+ }
+ free( wide );
+ for (int i = 0; i < 8; i++) bits = (bits << 8) | hash[i];
+ if (!(pfn = calloc( 1, strlen( name ) + 15 ))) return NULL;
+ strcpy( pfn, name );
+ strcat( pfn, "_" );
+ for (int i = 0; i < 13; i++)
+ {
+ int shift = 64 - 5 * (i + 1);
+ UINT32 value = shift >= 0 ? (bits >> shift) & 31 : (bits << -shift) & 31;
+ pfn[strlen( name ) + 1 + i] = alphabet[value];
+ }
+ return pfn;
+}
+BOOLEAN fullTrust = FALSE;
+BOOLEAN initializeCalled = FALSE;
+XTaskQueueHandle processQueue = NULL;
+CRITICAL_SECTION processQueueSection;
DWORD tlsIndex;
BOOL WINAPI DllMain( HINSTANCE hinst, DWORD reason, void *reserved )
{
+ XTaskQueueHandle queue;
+
TRACE( "hinst %p, reason %lu, reserved %p.\n", hinst, reason, reserved );
switch (reason)
{
case DLL_PROCESS_ATTACH:
if ((tlsIndex = TlsAlloc()) == TLS_OUT_OF_INDEXES) return FALSE;
+ InitializeCriticalSection( &processQueueSection );
+ if (SUCCEEDED(IXThreadingImpl_XTaskQueueCreate( x_threading_impl, XTaskQueueDispatchMode_ThreadPool, XTaskQueueDispatchMode_ThreadPool, &queue )))
+ IXThreadingImpl_XTaskQueueSetCurrentProcessTaskQueue( x_threading_impl, queue );
case DLL_THREAD_ATTACH:
TlsSetValue( tlsIndex, FALSE );
break;
case DLL_PROCESS_DETACH:
+ if (msaAppId) free( msaAppId );
TlsFree( tlsIndex );
+ IXThreadingImpl_XTaskQueueSetCurrentProcessTaskQueue( x_threading_impl, NULL );
+ DeleteCriticalSection( &processQueueSection );
break;
}
return TRUE;
@@ -52,8 +102,79 @@ struct initialize_options
HRESULT WINAPI InitializeApiImplEx2( ULONG gdkVer, ULONG gsVer, char mode, const struct initialize_options *options )
{
+ char filename[MAX_PATH + 1], *last;
+ xmlNodePtr child, root;
+ xmlDocPtr config;
+
TRACE( "gdkVer %ld, gsVer %ld, mode %d, options %p.\n", gdkVer, gsVer, mode, options );
+
+ if (initializeCalled) return S_OK;
+ initializeCalled = TRUE;
+
+ if (options)
+ {
+ if (options->isInline && !(config = xmlReadMemory( options->gameConfig, strlen( options->gameConfig ), NULL, NULL, 0 )))
+ return E_GAMERUNTIME_GAMECONFIG_BAD_FORMAT;
+ else if (!(config = xmlReadFile( options->gameConfig, NULL, 0 )))
+ return E_GAMERUNTIME_GAMECONFIG_BAD_FORMAT;
+ }
+ else
+ {
+ if (!GetModuleFileNameA( NULL, filename, MAX_PATH )) return HRESULT_FROM_WIN32( GetLastError() );
+ /* executable can be in a subdirectory, search up the tree until we find MicrosoftGame.config */
+ while ((last = strrchr( filename, '\\' )))
+ {
+ *(last + 1) = 0;
+ if (strlen( filename ) + strlen( "MicrosoftGame.config" ) < MAX_PATH)
+ strcat( filename, "MicrosoftGame.config" );
+ else return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+ if (PathFileExistsA( filename )) break;
+ *last = 0;
+ if (!strrchr( filename, '\\' )) return E_GAME_MISSING_GAME_CONFIG;
+ }
+ if (!(config = xmlReadFile( filename, NULL, 0 ))) return E_GAMERUNTIME_GAMECONFIG_BAD_FORMAT;
+ }
+
+ if (!(root = xmlDocGetRootElement( config ))) goto badconfig;
+ if (!strcmp( (char *)root->name, "Game" ))
+ {
+ for (child = root->children; child; child = child->next)
+ if (child->type == XML_ELEMENT_NODE)
+ {
+ if (!strcmp( (char *)child->name, "MSAAppId" ))
+ msaAppId = (char *)xmlNodeGetContent( child );
+ else if (!strcmp( (char *)child->name, "Identity" ))
+ {
+ char *name = (char *)xmlGetProp( child, (const xmlChar *)"Name" );
+ char *publisher = (char *)xmlGetProp( child, (const xmlChar *)"Publisher" );
+ if (name && publisher) packageFamilyName = compute_package_family_name( name, publisher );
+ free( name );
+ free( publisher );
+ }
+ else if (!strcmp( (char *)child->name, "StoreId" ))
+ storeId = (char *)xmlNodeGetContent( child );
+ else if (!strcmp( (char *)child->name, "TitleId" ))
+ {
+ char *value = (char *)xmlNodeGetContent( child );
+ titleId = strtoul( value, NULL, 16 );
+ free( value );
+ }
+ else if (!strcmp( (char *)child->name, "MSAFullTrust" ))
+ {
+ char *value = (char *)xmlNodeGetContent( child );
+ fullTrust = !strcmp( value, "true" ) || !strcmp( value, "1" );
+ free( value );
+ }
+ }
+ }
+ else goto badconfig;
+
+ xmlFreeDoc( config );
return S_OK;
+
+badconfig:
+ xmlFreeDoc( config );
+ return E_GAMERUNTIME_GAMECONFIG_BAD_FORMAT;
}
HRESULT WINAPI InitializeApiImplEx( ULONG gdkVer, ULONG gsVer, char mode )
@@ -61,6 +182,12 @@ HRESULT WINAPI InitializeApiImplEx( ULONG gdkVer, ULONG gsVer, char mode )
return InitializeApiImplEx2( gdkVer, gsVer, mode, NULL );
}
+HRESULT WINAPI UninitializeApiImpl( void )
+{
+ TRACE( "\n" );
+ return S_OK;
+}
+
HRESULT WINAPI InitializeApiImpl( ULONG gdkVer, ULONG gsVer )
{
return InitializeApiImplEx2( gdkVer, gsVer, 0, NULL );
@@ -119,5 +246,10 @@ HRESULT WINAPI QueryApiImpl( REFCLSID clsid, REFIID iid, void **out )
if (IsEqualGUID( clsid, &CLSID_XUserDeviceImpl ))
return IXUserDeviceImpl_QueryInterface( x_user_device_impl, iid, out );
+ /* A CLSID this runtime does not implement. Games cache this failure
+ * and silently take a degraded path; a WARN is the only way the gap
+ * becomes visible in a trace. */
+ WARN( "unknown clsid %s, iid %s -- no implementation in this runtime.\n",
+ debugstr_guid( clsid ), debugstr_guid( iid ) );
return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
}
diff --git a/dlls/xgameruntime/private.h b/dlls/xgameruntime/private.h
index c9a3d69..d893e90 100644
--- a/dlls/xgameruntime/private.h
+++ b/dlls/xgameruntime/private.h
@@ -57,12 +57,28 @@
#define WIDL_using_Windows_Foundation
#define WIDL_using_Windows_Foundation_Collections
#include <windows.foundation.h>
+#define WIDL_using_Windows_Data_Json
+#include "windows.data.json.h"
#define WIDL_using_Windows_Globalization
#include <windows.globalization.h>
#define WIDL_using_Windows_System_Profile
#include <windows.system.profile.h>
+extern char *msaAppId;
+extern UINT32 titleId;
+extern char *storeId;
+extern char *packageFamilyName;
+UINT64 xuser_get_xuid( XUserHandle user );
+HRESULT xuser_device_authorization( XUserHandle user, const char *relyingParty, char **auth );
+HRESULT xuser_signed_request( XUserHandle user, const char *method, const char *url, const char *auth, const char *extraHeaders,
+ const void *body, DWORD bodySize, DWORD *status, BYTE **buffer, SIZE_T *bufferSize );
+extern BOOLEAN fullTrust;
+HRESULT xodus_store_license_xml( const char *request, SIZE_T request_size, char **token );
+HRESULT xodus_store_license_body( const char **product_ids, SIZE_T count, const char *nonce, char **body );
+void xodus_store_license_note( const char *phase, HRESULT hr );
extern DWORD tlsIndex;
+extern XTaskQueueHandle processQueue;
+extern CRITICAL_SECTION processQueueSection;
extern IXAccessibilityImpl *x_accessibility_impl;
extern IXAppCaptureImpl *x_app_capture_impl;
diff --git a/dlls/xgameruntime/xerror.c b/dlls/xgameruntime/xerror.c
index 7a4d86a..6ad2d09 100644
--- a/dlls/xgameruntime/xerror.c
+++ b/dlls/xgameruntime/xerror.c
@@ -27,6 +27,10 @@ struct x_error
{
IXErrorImpl IXErrorImpl_iface;
LONG ref;
+ XErrorCallback *callback;
+ void *context;
+ XErrorOptions options_debugger_present;
+ XErrorOptions options_debugger_not_present;
};
static inline struct x_error *impl_from_IXErrorImpl( IXErrorImpl *iface )
@@ -76,12 +80,25 @@ static HRESULT WINAPI __PADDING__( IXErrorImpl *iface )
static void WINAPI x_error_XErrorSetCallback( IXErrorImpl *iface, XErrorCallback *callback, void *context )
{
- FIXME( "iface %p, callback %p, context %p stub!\n", iface, callback, context );
+ struct x_error *impl = impl_from_IXErrorImpl( iface );
+
+ TRACE( "iface %p, callback %p, context %p.\n", iface, callback, context );
+
+ /* Stored as given; this runtime reports errors through the game's own
+ * channels rather than raising XError events of its own. */
+ impl->callback = callback;
+ impl->context = context;
}
static void WINAPI x_error_XErrorSetOptions( IXErrorImpl *iface, XErrorOptions optionsDebuggerPresent, XErrorOptions optionsDebuggerNotPresent )
{
- FIXME( "iface %p, optionsDebuggerPresent %#x, optionsDebuggerNotPresent %#x stub!\n", iface, optionsDebuggerPresent, optionsDebuggerNotPresent );
+ struct x_error *impl = impl_from_IXErrorImpl( iface );
+
+ TRACE( "iface %p, optionsDebuggerPresent %#x, optionsDebuggerNotPresent %#x.\n",
+ iface, optionsDebuggerPresent, optionsDebuggerNotPresent );
+
+ impl->options_debugger_present = optionsDebuggerPresent;
+ impl->options_debugger_not_present = optionsDebuggerNotPresent;
}
static const struct IXErrorImplVtbl x_error_vtbl =
diff --git a/dlls/xgameruntime/xgame.c b/dlls/xgameruntime/xgame.c
index 7291f91..42c38bf 100644
--- a/dlls/xgameruntime/xgame.c
+++ b/dlls/xgameruntime/xgame.c
@@ -70,10 +70,12 @@ static ULONG WINAPI x_game_Release( IXGameImpl3 *iface )
return ref;
}
-static HRESULT WINAPI x_game_XGameGetXboxTitleId( IXGameImpl3 *iface, UINT32 *titleId )
+static HRESULT WINAPI x_game_XGameGetXboxTitleId( IXGameImpl3 *iface, UINT32 *out )
{
- FIXME( "iface %p, titleId %p stub!\n", iface, titleId );
- return E_NOTIMPL;
+ TRACE( "iface %p, out %p, titleId %#x.\n", iface, out, titleId );
+ if (!out) return E_POINTER;
+ if (!(*out = titleId)) return E_GAME_MISSING_GAME_CONFIG;
+ return S_OK;
}
static void WINAPI x_game_XLaunchNewGame( IXGameImpl3 *iface, const char *exePath, const char *args, XUserHandle defaultUser )
diff --git a/dlls/xgameruntime/xgameactivation.c b/dlls/xgameruntime/xgameactivation.c
index 21b2afc..ab78a97 100644
--- a/dlls/xgameruntime/xgameactivation.c
+++ b/dlls/xgameruntime/xgameactivation.c
@@ -68,10 +68,18 @@ static ULONG WINAPI x_game_activation_Release( IXGameActivationImpl *iface )
return ref;
}
+/* Registrations are accepted and counted, never raised. */
+static LONG64 game_activation_event_token;
+
static HRESULT WINAPI x_game_activation_XGameActivationRegisterForEvent( IXGameActivationImpl *iface, XTaskQueueHandle queue, void *context, XGameActivationCallback *callback, XTaskQueueRegistrationToken *token )
{
- FIXME( "iface %p, queue %p, context %p, callback %p, token %p stub!\n", iface, queue, context, callback, token );
- return E_NOTIMPL;
+ FIXME( "iface %p, queue %p, context %p, callback %p, token %p: accepted, no activation will be raised.\n",
+ iface, queue, context, callback, token );
+
+ if (!callback || !token) return E_INVALIDARG;
+
+ token->token = InterlockedIncrement64( &game_activation_event_token );
+ return S_OK;
}
static BOOLEAN WINAPI x_game_activation_XGameActivationUnregisterForEvent( IXGameActivationImpl *iface, XTaskQueueRegistrationToken token, BOOLEAN wait )
diff --git a/dlls/xgameruntime/xgameinvite.c b/dlls/xgameruntime/xgameinvite.c
index db9bc21..876183f 100644
--- a/dlls/xgameruntime/xgameinvite.c
+++ b/dlls/xgameruntime/xgameinvite.c
@@ -69,28 +69,44 @@ static ULONG WINAPI x_game_invite_Release( IXGameInviteImpl2 *iface )
return ref;
}
+/* Registrations are accepted and counted, never raised. */
+static LONG64 game_invite_event_token;
+
static HRESULT WINAPI x_game_invite_XGameInviteRegisterForEvent( IXGameInviteImpl2 *iface, XTaskQueueHandle queue, void *context, XGameInviteEventCallback *callback, XTaskQueueRegistrationToken *token )
{
- FIXME( "iface %p, queue %p, context %p, callback %p, token %p stub!\n", iface, queue, context, callback, token );
- return E_NOTIMPL;
+ FIXME( "iface %p, queue %p, context %p, callback %p, token %p: accepted, no invite will be raised.\n",
+ iface, queue, context, callback, token );
+
+ if (!callback || !token) return E_INVALIDARG;
+
+ /* Refusing left the caller's token untouched, and a title reads it back
+ * regardless and unregisters with it. Handing back a real token costs
+ * nothing -- no invite is raised either way. */
+ token->token = InterlockedIncrement64( &game_invite_event_token );
+ return S_OK;
}
static BOOLEAN WINAPI x_game_invite_XGameInviteUnregisterForEvent( IXGameInviteImpl2 *iface, XTaskQueueRegistrationToken token, BOOLEAN wait )
{
- FIXME( "iface %p, token %p, wait %d stub!\n", iface, &token, wait );
+ TRACE( "iface %p, token %I64d, wait %d.\n", iface, token.token, wait );
return TRUE;
}
static HRESULT WINAPI x_game_invite_XGameInviteRegisterForPendingEvent( IXGameInviteImpl2 *iface, XTaskQueueHandle queue, void *context, XGameInviteEventCallback *callback, XTaskQueueRegistrationToken *token )
{
- FIXME( "iface %p, queue %p, context %p, callback %p, token %p stub!\n", iface, queue, context, callback, token );
- return E_NOTIMPL;
+ FIXME( "iface %p, queue %p, context %p, callback %p, token %p: accepted, no invite will be raised.\n",
+ iface, queue, context, callback, token );
+
+ if (!callback || !token) return E_INVALIDARG;
+
+ token->token = InterlockedIncrement64( &game_invite_event_token );
+ return S_OK;
}
static BOOLEAN WINAPI x_game_invite_XGameInviteUnregisterForPendingEvent( IXGameInviteImpl2 *iface, XTaskQueueRegistrationToken token, BOOLEAN wait )
{
- FIXME( "iface %p, token %p, wait %d stub!\n", iface, &token, wait );
- return FALSE;
+ TRACE( "iface %p, token %I64d, wait %d.\n", iface, token.token, wait );
+ return TRUE;
}
static HRESULT WINAPI x_game_invite_XGameInviteAcceptPendingInvite( IXGameInviteImpl2 *iface, const char *inviteUri )
diff --git a/dlls/xgameruntime/xgameprotocol.c b/dlls/xgameruntime/xgameprotocol.c
index 2db84e4..2cf0fe3 100644
--- a/dlls/xgameruntime/xgameprotocol.c
+++ b/dlls/xgameruntime/xgameprotocol.c
@@ -68,10 +68,20 @@ static ULONG WINAPI x_game_protocol_Release( IXGameProtocolImpl *iface )
return ref;
}
+/* Protocol activation is how a title gets launched from a URI. Nothing here
+ * delivers such launches yet, but refusing the registration reads as a broken
+ * runtime rather than as "no URI launches will arrive". */
+static LONG64 protocol_activation_token;
+
static HRESULT WINAPI x_game_protocol_XGameProtocolRegisterForActivation( IXGameProtocolImpl *iface, XTaskQueueHandle queue, void *context, XGameProtocolActivationCallback *callback, XTaskQueueRegistrationToken *token )
{
- FIXME( "iface %p, queue %p, context %p, callback %p, token %p stub!\n", iface, queue, context, callback, token );
- return E_NOTIMPL;
+ FIXME( "iface %p, queue %p, context %p, callback %p, token %p: accepted, no activations will be raised.\n",
+ iface, queue, context, callback, token );
+
+ if (!callback || !token) return E_INVALIDARG;
+
+ token->token = InterlockedIncrement64( &protocol_activation_token );
+ return S_OK;
}
static BOOLEAN WINAPI x_game_protocol_XGameProtocolUnregisterForActivation( IXGameProtocolImpl *iface, XTaskQueueRegistrationToken token, BOOLEAN wait )
diff --git a/dlls/xgameruntime/xgameruntime.spec b/dlls/xgameruntime/xgameruntime.spec
index fd92f16..354cf9d 100644
--- a/dlls/xgameruntime/xgameruntime.spec
+++ b/dlls/xgameruntime/xgameruntime.spec
@@ -3,5 +3,5 @@
@ stdcall -private InitializeApiImplEx(long long long)
@ stdcall -private InitializeApiImplEx2(long long long ptr)
@ stdcall -private QueryApiImpl(ptr ptr ptr)
-@ stub -private UninitializeApiImpl()
+@ stdcall -private UninitializeApiImpl()
@ stub -private XErrorReport(long str)
diff --git a/dlls/xgameruntime/xgamesave.c b/dlls/xgameruntime/xgamesave.c
index 3182a44..062b3ce 100644
--- a/dlls/xgameruntime/xgamesave.c
+++ b/dlls/xgameruntime/xgamesave.c
@@ -19,7 +19,10 @@
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
+#include <ctype.h>
+#include <stdio.h>
#include "private.h"
+#include "util.h"
struct x_game_save
{
@@ -43,7 +46,8 @@ static HRESULT WINAPI x_game_save_QueryInterface( IXGameSaveImpl3 *iface, REFIID
if (IsEqualGUID( iid, &IID_IUnknown ) ||
IsEqualGUID( iid, &IID_IXGameSaveImpl ) ||
IsEqualGUID( iid, &IID_IXGameSaveImpl2 ) ||
- IsEqualGUID( iid, &IID_IXGameSaveImpl3 ))
+ IsEqualGUID( iid, &IID_IXGameSaveImpl3 ) ||
+ IsEqualGUID( iid, &IID_IXGameSaveImpl4 ))
{
IXGameSaveImpl_AddRef( *out = &impl->IXGameSaveImpl3_iface );
return S_OK;
@@ -70,163 +74,1753 @@ static ULONG WINAPI x_game_save_Release( IXGameSaveImpl3 *iface )
return ref;
}
+#define E_GS_INVALID_CONTAINER_NAME ((HRESULT)0x80830001)
+#define E_GS_PROVIDED_BUFFER_TOO_SMALL ((HRESULT)0x80830007)
+#define E_GS_BLOB_NOT_FOUND ((HRESULT)0x80830008)
+#define E_GS_NO_SERVICE_CONFIGURATION ((HRESULT)0x80830009)
+#define E_GS_CONTAINER_NOT_IN_SYNC ((HRESULT)0x8083000A)
+#define E_GS_UPDATE_TOO_BIG ((HRESULT)0x80830005)
+
+#define SAVE_QUOTA (256 * 1024 * 1024)
+
+struct blob_entry
+{
+ char *name;
+ UINT32 size;
+ char atom[48];
+};
+
+struct container_state
+{
+ char *name;
+ char *display;
+ UINT64 time;
+ char remote[48];
+ BOOL dirty;
+ UINT32 count;
+ struct blob_entry *blobs;
+};
+
+struct XGameSaveProvider
+{
+ XUserHandle user;
+ char *scid;
+ char root[MAX_PATH];
+ char base[512];
+ char *auth;
+ BOOL cloud;
+ BOOL locked;
+ INT64 quota;
+ UINT32 downloaded;
+ UINT32 uploaded;
+ CRITICAL_SECTION cs;
+};
+
+struct XGameSaveContainer
+{
+ struct XGameSaveProvider *provider;
+ char *name;
+};
+
+struct update_op
+{
+ char *name;
+ BYTE *data;
+ SIZE_T size;
+ BOOL remove;
+};
+
+struct XGameSaveUpdate
+{
+ struct XGameSaveContainer *container;
+ char *display;
+ UINT32 count;
+ UINT32 capacity;
+ struct update_op *ops;
+};
+
+static char *hex_encode( const char *str )
+{
+ static const char digits[] = "0123456789abcdef";
+ SIZE_T len = strlen( str );
+ char *out = calloc( 1, len * 2 + 1 );
+ if (!out) return NULL;
+ for (SIZE_T i = 0; i < len; i++)
+ {
+ out[2 * i] = digits[(BYTE)str[i] >> 4];
+ out[2 * i + 1] = digits[(BYTE)str[i] & 15];
+ }
+ return out;
+}
+
+static char *hex_decode( const char *hex )
+{
+ SIZE_T len = strlen( hex ) / 2;
+ char *out = calloc( 1, len + 1 );
+ if (!out) return NULL;
+ for (SIZE_T i = 0; i < len; i++)
+ {
+ char pair[3] = { hex[2 * i], hex[2 * i + 1], 0 };
+ out[i] = (char)strtoul( pair, NULL, 16 );
+ }
+ return out;
+}
+
+static char *url_encode( const char *str )
+{
+ static const char digits[] = "0123456789ABCDEF";
+ char *out = calloc( 1, strlen( str ) * 3 + 1 ), *p = out;
+ if (!out) return NULL;
+ for (; *str; str++)
+ {
+ BYTE c = *str;
+ if (isalnum( c ) || c == '-' || c == '.' || c == '_' || c == '~') *p++ = c;
+ else
+ {
+ *p++ = '%';
+ *p++ = digits[c >> 4];
+ *p++ = digits[c & 15];
+ }
+ }
+ return out;
+}
+
+static char *json_escape( const char *str )
+{
+ char *out = calloc( 1, strlen( str ) * 6 + 1 ), *p = out;
+ if (!out) return NULL;
+ for (; *str; str++)
+ {
+ BYTE c = *str;
+ if (c == '"' || c == '\\') { *p++ = '\\'; *p++ = c; }
+ else if (c < 0x20) p += sprintf( p, "\\u%04x", c );
+ else *p++ = c;
+ }
+ return out;
+}
+
+static const char *json_ws( const char *p )
+{
+ while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++;
+ return p;
+}
+
+static const char *json_string( const char *p, char **out )
+{
+ char *buf, *q;
+ const char *start;
+
+ if (*p != '"') return NULL;
+ start = ++p;
+ while (*p && *p != '"') p += (*p == '\\' && p[1]) ? 2 : 1;
+ if (!*p || !(buf = calloc( 1, p - start + 1 ))) return NULL;
+ for (q = buf, p = start; *p != '"'; p++)
+ {
+ if (*p != '\\') { *q++ = *p; continue; }
+ switch (*++p)
+ {
+ case 'n': *q++ = '\n'; break;
+ case 't': *q++ = '\t'; break;
+ case 'r': *q++ = '\r'; break;
+ case 'b': *q++ = '\b'; break;
+ case 'f': *q++ = '\f'; break;
+ case 'u':
+ {
+ char hex[5] = { 0 };
+ WCHAR wc;
+ memcpy( hex, p + 1, 4 );
+ wc = (WCHAR)strtoul( hex, NULL, 16 );
+ q += WideCharToMultiByte( CP_UTF8, 0, &wc, 1, q, 4, NULL, NULL );
+ p += 4;
+ break;
+ }
+ default: *q++ = *p; break;
+ }
+ }
+ *out = buf;
+ return p + 1;
+}
+
+static const char *json_skip( const char *p )
+{
+ int depth = 0;
+ char *tmp;
+
+ p = json_ws( p );
+ do
+ {
+ if (!*p) return NULL;
+ if (*p == '"')
+ {
+ if (!(p = json_string( p, &tmp ))) return NULL;
+ free( tmp );
+ continue;
+ }
+ if (*p == '{' || *p == '[') depth++;
+ else if (*p == '}' || *p == ']') depth--;
+ else if (!depth && (*p == ',')) return p;
+ p++;
+ } while (depth > 0 || (*p && *p != ',' && *p != '}' && *p != ']'));
+ return p;
+}
+
+static BOOL json_object_next( const char **p, char **key, const char **value )
+{
+ const char *q = json_ws( *p );
+
+ if (*q == '{' || *q == ',') q = json_ws( q + 1 );
+ if (*q != '"') return FALSE;
+ if (!(q = json_string( q, key ))) return FALSE;
+ q = json_ws( q );
+ if (*q != ':')
+ {
+ free( *key );
+ return FALSE;
+ }
+ *value = json_ws( q + 1 );
+ if (!(q = json_skip( *value )))
+ {
+ free( *key );
+ return FALSE;
+ }
+ *p = q;
+ return TRUE;
+}
+
+static const char *json_find( const char *object, const char *name )
+{
+ const char *p = object, *value;
+ char *key;
+
+ while (json_object_next( &p, &key, &value ))
+ {
+ BOOL match = !strcmp( key, name );
+ free( key );
+ if (match) return value;
+ }
+ return NULL;
+}
+
+static char *json_find_string( const char *object, const char *name )
+{
+ const char *value = json_find( object, name );
+ char *out = NULL;
+ if (value && *value == '"') json_string( value, &out );
+ return out;
+}
+
+static UINT64 filetime_to_unix( const FILETIME *ft )
+{
+ ULARGE_INTEGER li = { .LowPart = ft->dwLowDateTime, .HighPart = ft->dwHighDateTime };
+ return li.QuadPart / 10000000 - 11644473600ULL;
+}
+
+static UINT64 parse_iso_time( const char *str )
+{
+ SYSTEMTIME st = { 0 };
+ FILETIME ft;
+ if (!str || sscanf( str, "%hu-%hu-%huT%hu:%hu:%hu", &st.wYear, &st.wMonth, &st.wDay, &st.wHour, &st.wMinute, &st.wSecond ) != 6) return 0;
+ if (!SystemTimeToFileTime( &st, &ft )) return 0;
+ return filetime_to_unix( &ft );
+}
+
+static void format_iso_time( UINT64 unixTime, char *out, SIZE_T size )
+{
+ ULARGE_INTEGER li = { .QuadPart = (unixTime + 11644473600ULL) * 10000000 };
+ FILETIME ft = { li.LowPart, li.HighPart };
+ SYSTEMTIME st;
+ FileTimeToSystemTime( &ft, &st );
+ snprintf( out, size, "%04u-%02u-%02uT%02u:%02u:%02u.0000000Z", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond );
+}
+
+static UINT64 unix_now( void )
+{
+ FILETIME ft;
+ GetSystemTimeAsFileTime( &ft );
+ return filetime_to_unix( &ft );
+}
+
+static HRESULT read_file( const char *path, BYTE **data, SIZE_T *size )
+{
+ HANDLE file = CreateFileA( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
+ LARGE_INTEGER li;
+ DWORD read;
+
+ *data = NULL;
+ *size = 0;
+ if (file == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32( GetLastError() );
+ if (!GetFileSizeEx( file, &li ) || !(*data = calloc( 1, li.QuadPart + 1 )))
+ {
+ CloseHandle( file );
+ return E_OUTOFMEMORY;
+ }
+ if (li.QuadPart && (!ReadFile( file, *data, li.QuadPart, &read, NULL ) || read != li.QuadPart))
+ {
+ CloseHandle( file );
+ free( *data );
+ *data = NULL;
+ return HRESULT_FROM_WIN32( GetLastError() );
+ }
+ CloseHandle( file );
+ *size = li.QuadPart;
+ return S_OK;
+}
+
+static HRESULT write_file( const char *path, const void *data, SIZE_T size )
+{
+ char tmp[MAX_PATH + 8];
+ HANDLE file;
+ DWORD written;
+ BOOL ok;
+
+ snprintf( tmp, sizeof(tmp), "%s.tmp", path );
+ file = CreateFileA( tmp, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL );
+ if (file == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32( GetLastError() );
+ ok = (!size || (WriteFile( file, data, size, &written, NULL ) && written == size)) && FlushFileBuffers( file );
+ CloseHandle( file );
+ if (!ok || !MoveFileExA( tmp, path, MOVEFILE_REPLACE_EXISTING ))
+ {
+ DeleteFileA( tmp );
+ return HRESULT_FROM_WIN32( GetLastError() );
+ }
+ return S_OK;
+}
+
+static void create_directories( const char *path )
+{
+ char buf[MAX_PATH];
+ lstrcpynA( buf, path, sizeof(buf) );
+ for (char *p = buf + 3; *p; p++)
+ if (*p == '\\')
+ {
+ *p = 0;
+ CreateDirectoryA( buf, NULL );
+ *p = '\\';
+ }
+ CreateDirectoryA( buf, NULL );
+}
+
+static void delete_directory( const char *path )
+{
+ char pattern[MAX_PATH], child[MAX_PATH];
+ WIN32_FIND_DATAA data;
+ HANDLE find;
+
+ snprintf( pattern, sizeof(pattern), "%s\\*", path );
+ if ((find = FindFirstFileA( pattern, &data )) != INVALID_HANDLE_VALUE)
+ {
+ do
+ {
+ if (!strcmp( data.cFileName, "." ) || !strcmp( data.cFileName, ".." )) continue;
+ snprintf( child, sizeof(child), "%s\\%s", path, data.cFileName );
+ if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) delete_directory( child );
+ else DeleteFileA( child );
+ } while (FindNextFileA( find, &data ));
+ FindClose( find );
+ }
+ RemoveDirectoryA( path );
+}
+
+static BOOL container_dir( struct XGameSaveProvider *provider, const char *name, char *out, SIZE_T size )
+{
+ char *hex = hex_encode( name );
+ if (!hex) return FALSE;
+ snprintf( out, size, "%s\\%s", provider->root, hex );
+ free( hex );
+ return TRUE;
+}
+
+static BOOL blob_path( struct XGameSaveProvider *provider, const char *container, const char *blob, char *out, SIZE_T size )
+{
+ char dir[MAX_PATH], *hex = hex_encode( blob );
+ BOOL ok = hex && container_dir( provider, container, dir, sizeof(dir) );
+ if (ok) snprintf( out, size, "%s\\b_%s", dir, hex );
+ free( hex );
+ return ok;
+}
+
+static void free_state( struct container_state *state )
+{
+ for (UINT32 i = 0; i < state->count; i++) free( state->blobs[i].name );
+ free( state->blobs );
+ free( state->name );
+ free( state->display );
+ memset( state, 0, sizeof(*state) );
+}
+
+static struct blob_entry *find_blob( struct container_state *state, const char *name )
+{
+ for (UINT32 i = 0; i < state->count; i++)
+ if (!strcmp( state->blobs[i].name, name )) return &state->blobs[i];
+ return NULL;
+}
+
+static struct blob_entry *add_blob( struct container_state *state, const char *name )
+{
+ struct blob_entry *blobs, *entry;
+ if ((entry = find_blob( state, name ))) return entry;
+ if (!(blobs = realloc( state->blobs, (state->count + 1) * sizeof(*blobs) ))) return NULL;
+ state->blobs = blobs;
+ entry = &blobs[state->count];
+ memset( entry, 0, sizeof(*entry) );
+ if (!(entry->name = strdup( name ))) return NULL;
+ state->count++;
+ return entry;
+}
+
+static void remove_blob( struct container_state *state, const char *name )
+{
+ struct blob_entry *entry = find_blob( state, name );
+ if (!entry) return;
+ free( entry->name );
+ memmove( entry, entry + 1, (state->blobs + state->count - entry - 1) * sizeof(*entry) );
+ state->count--;
+}
+
+static UINT64 state_total_size( const struct container_state *state )
+{
+ UINT64 total = 0;
+ for (UINT32 i = 0; i < state->count; i++) total += state->blobs[i].size;
+ return total;
+}
+
+static HRESULT load_state( struct XGameSaveProvider *provider, const char *name, struct container_state *state )
+{
+ char dir[MAX_PATH], path[MAX_PATH];
+ char *line, *next, *text;
+ SIZE_T size;
+ BYTE *data;
+ HRESULT hr;
+
+ memset( state, 0, sizeof(*state) );
+ if (!(state->name = strdup( name ))) return E_OUTOFMEMORY;
+ if (!container_dir( provider, name, dir, sizeof(dir) )) return E_OUTOFMEMORY;
+ snprintf( path, sizeof(path), "%s\\index", dir );
+ if (FAILED(hr = read_file( path, &data, &size ))) return hr;
+ text = (char *)data;
+ for (line = text; line && *line; line = next)
+ {
+ char a[128] = { 0 }, b[128] = { 0 };
+ unsigned int blobSize = 0;
+ if ((next = strchr( line, '\n' ))) *next++ = 0;
+ if (!strncmp( line, "display ", 8 )) state->display = hex_decode( line + 8 );
+ else if (!strncmp( line, "time ", 5 )) state->time = _strtoui64( line + 5, NULL, 10 );
+ else if (!strncmp( line, "remote ", 7 )) lstrcpynA( state->remote, strcmp( line + 7, "-" ) ? line + 7 : "", sizeof(state->remote) );
+ else if (!strncmp( line, "dirty ", 6 )) state->dirty = atoi( line + 6 );
+ else if (sscanf( line, "blob %127s %u %127s", a, &blobSize, b ) == 3)
+ {
+ char *blobName = hex_decode( a );
+ struct blob_entry *entry = blobName ? add_blob( state, blobName ) : NULL;
+ free( blobName );
+ if (!entry) continue;
+ entry->size = blobSize;
+ lstrcpynA( entry->atom, strcmp( b, "-" ) ? b : "", sizeof(entry->atom) );
+ }
+ }
+ free( data );
+ return S_OK;
+}
+
+static HRESULT save_state( struct XGameSaveProvider *provider, const struct container_state *state )
+{
+ char dir[MAX_PATH], path[MAX_PATH], *hex, *text;
+ SIZE_T size = 256 + (state->display ? strlen( state->display ) * 2 : 0), len = 0;
+ HRESULT hr;
+
+ for (UINT32 i = 0; i < state->count; i++) size += strlen( state->blobs[i].name ) * 2 + 80;
+ if (!container_dir( provider, state->name, dir, sizeof(dir) )) return E_OUTOFMEMORY;
+ create_directories( dir );
+ if (!(text = calloc( 1, size ))) return E_OUTOFMEMORY;
+ hex = hex_encode( state->display ? state->display : "" );
+ len += snprintf( text + len, size - len, "display %s\ntime %I64u\nremote %s\ndirty %d\n", hex ? hex : "", state->time, state->remote[0] ? state->remote : "-", state->dirty );
+ free( hex );
+ for (UINT32 i = 0; i < state->count; i++)
+ {
+ hex = hex_encode( state->blobs[i].name );
+ len += snprintf( text + len, size - len, "blob %s %u %s\n", hex ? hex : "", state->blobs[i].size, state->blobs[i].atom[0] ? state->blobs[i].atom : "-" );
+ free( hex );
+ }
+ snprintf( path, sizeof(path), "%s\\index", dir );
+ hr = write_file( path, text, len );
+ free( text );
+ return hr;
+}
+
+typedef BOOL (*container_callback)( struct XGameSaveProvider *provider, const char *name, void *context );
+
+static void enumerate_local( struct XGameSaveProvider *provider, container_callback callback, void *context )
+{
+ char pattern[MAX_PATH], index[MAX_PATH];
+ WIN32_FIND_DATAA data;
+ HANDLE find;
+
+ snprintf( pattern, sizeof(pattern), "%s\\*", provider->root );
+ if ((find = FindFirstFileA( pattern, &data )) == INVALID_HANDLE_VALUE) return;
+ do
+ {
+ char *name;
+ BOOL more;
+ if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || data.cFileName[0] == '.') continue;
+ snprintf( index, sizeof(index), "%s\\%s\\index", provider->root, data.cFileName );
+ if (GetFileAttributesA( index ) == INVALID_FILE_ATTRIBUTES) continue;
+ if (!(name = hex_decode( data.cFileName ))) continue;
+ more = callback( provider, name, context );
+ free( name );
+ if (!more) break;
+ } while (FindNextFileA( find, &data ));
+ FindClose( find );
+}
+
+static HRESULT cloud_request( struct XGameSaveProvider *provider, const char *method, const char *path, const char *extraHeaders,
+ const void *body, DWORD bodySize, DWORD *status, BYTE **buffer, SIZE_T *bufferSize )
+{
+ char url[2048], headers[1024];
+ HRESULT hr;
+
+ snprintf( url, sizeof(url), "%s%s", provider->base, path );
+ snprintf( headers, sizeof(headers), "x-xbl-contract-version: 107\r\nx-xbl-pfn: %s\r\n%s", packageFamilyName, extraHeaders ? extraHeaders : "" );
+ hr = xuser_signed_request( provider->user, method, url, provider->auth, headers, body, bodySize, status, buffer, bufferSize );
+ TRACE( "%s %s -> hr %#lx, status %lu.\n", method, debugstr_a( path ), hr, *status );
+ if (SUCCEEDED(hr) && *status >= 400)
+ WARN( "%s %s failed with status %lu: %s\n", method, debugstr_a( path ), *status, debugstr_an( (char *)*buffer, min( *bufferSize, 300 ) ) );
+ return hr;
+}
+
+static BOOL cloud_lock( struct XGameSaveProvider *provider )
+{
+ const char *quota;
+ SIZE_T size;
+ BYTE *buffer;
+ DWORD status;
+ HRESULT hr;
+
+ hr = cloud_request( provider, "PUT", "/lock?friendlyName=Xodus", "x-xbl-lock-ver: 1\r\nContent-Type: application/json\r\n", NULL, 0, &status, &buffer, &size );
+ if (FAILED(hr)) return FALSE;
+ if (status == 200 || status == 201)
+ {
+ if ((quota = json_find( (char *)buffer, "quotaBytes" ))) provider->quota = _strtoi64( quota, NULL, 10 );
+ provider->locked = TRUE;
+ }
+ else WARN( "could not acquire the cloud save lock (status %lu), another device may be using it.\n", status );
+ free( buffer );
+ return provider->locked;
+}
+
+static void cloud_unlock( struct XGameSaveProvider *provider, BOOL uploaded )
+{
+ SIZE_T size;
+ BYTE *buffer;
+ DWORD status;
+
+ if (!provider->locked) return;
+ if (SUCCEEDED(cloud_request( provider, "DELETE", uploaded ? "/lock?newSavesUploaded=true" : "/lock?newSavesUploaded=false", NULL, NULL, 0, &status, &buffer, &size )))
+ free( buffer );
+ provider->locked = FALSE;
+}
+
+static void cloud_disable( struct XGameSaveProvider *provider )
+{
+ provider->cloud = FALSE;
+ ERR( "cloud saves disabled for this session, continuing with local saves only.\n" );
+}
+
+static HRESULT cloud_download( struct XGameSaveProvider *provider, const char *name, const char *display, const char *remoteTime )
+{
+ struct container_state state = { 0 };
+ char path[1024], dir[MAX_PATH], blob[MAX_PATH], *enc, *key;
+ SIZE_T size, dataSize;
+ BYTE *buffer, *data;
+ const char *atoms, *value;
+ DWORD status;
+ HRESULT hr;
+
+ TRACE( "provider %p, name %s.\n", provider, debugstr_a( name ) );
+
+ if (!(enc = url_encode( name ))) return E_OUTOFMEMORY;
+ snprintf( path, sizeof(path), "/%s,savedgame", enc );
+ free( enc );
+ if (FAILED(hr = cloud_request( provider, "GET", path, NULL, NULL, 0, &status, &buffer, &size ))) return hr;
+ if (status != 200 || !(atoms = json_find( (char *)buffer, "atoms" )) || *atoms != '{')
+ {
+ free( buffer );
+ return E_FAIL;
+ }
+
+ if (!container_dir( provider, name, dir, sizeof(dir) )) hr = E_OUTOFMEMORY;
+ else
+ {
+ delete_directory( dir );
+ create_directories( dir );
+ }
+ if (!(state.name = strdup( name ))) hr = E_OUTOFMEMORY;
+ state.display = strdup( display ? display : name );
+ state.time = parse_iso_time( remoteTime );
+ lstrcpynA( state.remote, remoteTime ? remoteTime : "", sizeof(state.remote) );
+
+ while (SUCCEEDED(hr) && json_object_next( &atoms, &key, &value ))
+ {
+ char *atom = NULL;
+ struct blob_entry *entry;
+ if (*value == '"') json_string( value, &atom );
+ if (!atom || !(entry = add_blob( &state, key )))
+ {
+ free( atom );
+ free( key );
+ hr = E_OUTOFMEMORY;
+ break;
+ }
+ snprintf( path, sizeof(path), "/%s", atom );
+ if (SUCCEEDED(hr = cloud_request( provider, "GET", path, NULL, NULL, 0, &status, &data, &dataSize )) && status == 200)
+ {
+ blob_path( provider, name, key, blob, sizeof(blob) );
+ hr = write_file( blob, data, dataSize );
+ entry->size = dataSize;
+ lstrcpynA( entry->atom, atom, sizeof(entry->atom) );
+ }
+ else if (SUCCEEDED(hr)) hr = E_FAIL;
+ free( data );
+ free( atom );
+ free( key );
+ }
+ free( buffer );
+ if (SUCCEEDED(hr)) hr = save_state( provider, &state );
+ TRACE( "downloaded %s, %u blobs, hr %#lx.\n", debugstr_a( name ), state.count, hr );
+ free_state( &state );
+ return hr;
+}
+
+#define LARGE_BLOB_SIZE (4 * 1024 * 1024)
+
+static HRESULT upload_large_atom( struct XGameSaveProvider *provider, const char *atom, const BYTE *data, SIZE_T size )
+{
+ char path[128], body[64], *blobUri = NULL, *commit = NULL, *p;
+ UINT32 blocks = (size + LARGE_BLOB_SIZE - 1) / LARGE_BLOB_SIZE;
+ SIZE_T responseSize, commitSize;
+ BYTE *response;
+ DWORD status;
+ HRESULT hr;
+
+ TRACE( "atom %s, size %Iu, blocks %u.\n", debugstr_a( atom ), size, blocks );
+
+ snprintf( path, sizeof(path), "/atoms/%.36s", atom );
+ snprintf( body, sizeof(body), "{\"size\":%Iu}", size );
+ if (FAILED(hr = cloud_request( provider, "POST", path, "Content-Type: application/json\r\nAccept: application/json\r\n", body, strlen( body ), &status, &response, &responseSize ))) return hr;
+ if (status == 200) blobUri = json_find_string( (char *)response, "blobUri" );
+ free( response );
+ if (!blobUri) return E_FAIL;
+
+ commitSize = 64 + blocks * 24;
+ if (!(commit = calloc( 1, commitSize )))
+ {
+ free( blobUri );
+ return E_OUTOFMEMORY;
+ }
+ p = commit + sprintf( commit, "{\"blockIds\":[" );
+
+ for (UINT32 i = 0; i < blocks && SUCCEEDED(hr); i++)
+ {
+ char id[16], encoded[32], *url;
+ WCHAR *urlW;
+ SIZE_T chunk = min( LARGE_BLOB_SIZE, size - (SIZE_T)i * LARGE_BLOB_SIZE ), urlSize;
+ int len;
+
+ snprintf( id, sizeof(id), "%08u", i );
+ encode_base64( 8, (const BYTE *)id, sizeof(encoded) - 1, encoded, TRUE );
+ encoded[12] = 0;
+ p += sprintf( p, "%s\"%s\"", i ? "," : "", encoded );
+
+ urlSize = strlen( blobUri ) + 64;
+ if (!(url = calloc( 1, urlSize )))
+ {
+ hr = E_OUTOFMEMORY;
+ break;
+ }
+ {
+ char *q = url + snprintf( url, urlSize, "%s&comp=block&blockid=", blobUri );
+ for (const char *c = encoded; *c; c++) q += (*c == '=') ? sprintf( q, "%%3D" ) : (*q = *c, 1);
+ *q = 0;
+ }
+ len = MultiByteToWideChar( CP_UTF8, 0, url, -1, NULL, 0 );
+ if (!(urlW = calloc( len, sizeof(WCHAR) )))
+ {
+ free( url );
+ hr = E_OUTOFMEMORY;
+ break;
+ }
+ MultiByteToWideChar( CP_UTF8, 0, url, -1, urlW, len );
+ hr = http_request_raw( L"PUT", urlW, L"x-ms-version: 2015-04-05\r\n", data + (SIZE_T)i * LARGE_BLOB_SIZE, chunk, &status, &response, &responseSize );
+ if (SUCCEEDED(hr) && status != 201)
+ {
+ WARN( "block %u upload failed with status %lu: %s\n", i, status, debugstr_an( (char *)response, min( responseSize, 300 ) ) );
+ hr = E_FAIL;
+ }
+ free( response );
+ free( urlW );
+ free( url );
+ }
+ free( blobUri );
+
+ if (SUCCEEDED(hr))
+ {
+ sprintf( p, "],\"size\":%Iu}", size );
+ snprintf( path, sizeof(path), "/atoms/%.36s?commit=true", atom );
+ hr = cloud_request( provider, "POST", path, "Content-Type: application/json\r\nAccept: application/json\r\n", commit, strlen( commit ), &status, &response, &responseSize );
+ free( response );
+ if (SUCCEEDED(hr) && (status < 200 || status >= 300)) hr = E_FAIL;
+ }
+ free( commit );
+ TRACE( "atom %s upload hr %#lx.\n", debugstr_a( atom ), hr );
+ return hr;
+}
+
+static HRESULT cloud_upload( struct XGameSaveProvider *provider, struct container_state *state )
+{
+ char path[2048], blob[MAX_PATH], timestamp[48], *enc, *encDisplay, *json, *p;
+ SIZE_T size, jsonSize = 32;
+ BYTE *buffer, *data;
+ DWORD status;
+ HRESULT hr = S_OK;
+
+ TRACE( "provider %p, name %s.\n", provider, debugstr_a( state->name ) );
+
+ if (!provider->cloud) return S_FALSE;
+ if (!cloud_lock( provider )) return E_FAIL;
+
+ for (UINT32 i = 0; i < state->count && SUCCEEDED(hr); i++)
+ {
+ struct blob_entry *entry = &state->blobs[i];
+ GUID guid;
+ if (entry->atom[0]) continue;
+ if (!blob_path( provider, state->name, entry->name, blob, sizeof(blob) ))
+ {
+ hr = E_OUTOFMEMORY;
+ break;
+ }
+ if (FAILED(hr = read_file( blob, &data, &size ))) break;
+ CoCreateGuid( &guid );
+ snprintf( entry->atom, sizeof(entry->atom), "%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X,binary",
+ guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
+ guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7] );
+ if (size > LARGE_BLOB_SIZE)
+ {
+ hr = upload_large_atom( provider, entry->atom, data, size );
+ free( data );
+ }
+ else
+ {
+ snprintf( path, sizeof(path), "/%s", entry->atom );
+ hr = cloud_request( provider, "PUT", path, "Content-Type: application/octet-stream\r\n", data, size, &status, &buffer, &size );
+ free( data );
+ free( buffer );
+ if (SUCCEEDED(hr) && (status < 200 || status >= 300)) hr = E_FAIL;
+ }
+ if (FAILED(hr)) entry->atom[0] = 0;
+ }
+ if (FAILED(hr))
+ {
+ cloud_unlock( provider, FALSE );
+ return hr;
+ }
+
+ for (UINT32 i = 0; i < state->count; i++) jsonSize += strlen( state->blobs[i].name ) * 6 + strlen( state->blobs[i].atom ) + 8;
+ if (!(json = calloc( 1, jsonSize )))
+ {
+ cloud_unlock( provider, FALSE );
+ return E_OUTOFMEMORY;
+ }
+ p = json + sprintf( json, "{\"atoms\":{" );
+ for (UINT32 i = 0; i < state->count; i++)
+ {
+ char *escaped = json_escape( state->blobs[i].name );
+ p += sprintf( p, "%s\"%s\":\"%s\"", i ? "," : "", escaped ? escaped : "", state->blobs[i].atom );
+ free( escaped );
+ }
+ strcpy( p, "}}" );
+
+ format_iso_time( state->time ? state->time : unix_now(), timestamp, sizeof(timestamp) );
+ enc = url_encode( state->name );
+ encDisplay = url_encode( state->display ? state->display : state->name );
+ snprintf( path, sizeof(path), "/%s,savedgame?clientFileTime=%s&displayName=%s", enc ? enc : "", timestamp, encDisplay ? encDisplay : "" );
+ free( enc );
+ free( encDisplay );
+ hr = cloud_request( provider, "PUT", path, "Content-Type: application/json\r\n", json, strlen( json ), &status, &buffer, &size );
+ free( json );
+ free( buffer );
+ if (SUCCEEDED(hr) && (status < 200 || status >= 300)) hr = E_FAIL;
+ if (SUCCEEDED(hr))
+ {
+ state->dirty = FALSE;
+ lstrcpynA( state->remote, timestamp, sizeof(state->remote) );
+ }
+ cloud_unlock( provider, SUCCEEDED(hr) );
+ TRACE( "uploaded %s, hr %#lx.\n", debugstr_a( state->name ), hr );
+ return hr;
+}
+
+static HRESULT cloud_delete( struct XGameSaveProvider *provider, const char *name )
+{
+ char path[1024], *enc = url_encode( name );
+ SIZE_T size;
+ BYTE *buffer;
+ DWORD status;
+ HRESULT hr;
+
+ if (!provider->cloud)
+ {
+ free( enc );
+ return S_FALSE;
+ }
+ if (!enc) return E_OUTOFMEMORY;
+ if (!cloud_lock( provider ))
+ {
+ free( enc );
+ return E_FAIL;
+ }
+ snprintf( path, sizeof(path), "/%s,savedgame", enc );
+ free( enc );
+ hr = cloud_request( provider, "DELETE", path, NULL, NULL, 0, &status, &buffer, &size );
+ free( buffer );
+ cloud_unlock( provider, SUCCEEDED(hr) );
+ if (SUCCEEDED(hr) && status != 200 && status != 204 && status != 404) hr = E_FAIL;
+ return hr;
+}
+
+struct remote_container
+{
+ char *name;
+ char *display;
+ char *time;
+};
+
+enum sync_mode
+{
+ SYNC_AUTO,
+ SYNC_DOWNLOAD,
+ SYNC_UPLOAD,
+};
+
+static enum sync_mode sync_mode( void )
+{
+ char value[32];
+ if (!GetEnvironmentVariableA( "XODUS_SAVE_SYNC", value, sizeof(value) )) return SYNC_AUTO;
+ if (!_stricmp( value, "download" )) return SYNC_DOWNLOAD;
+ if (!_stricmp( value, "upload" )) return SYNC_UPLOAD;
+ return SYNC_AUTO;
+}
+
+static void force_upload( struct XGameSaveProvider *provider, struct container_state *state );
+
+static BOOL sync_local_callback( struct XGameSaveProvider *provider, const char *name, void *context )
+{
+ struct remote_container *remote = context;
+ struct container_state state;
+ char dir[MAX_PATH];
+
+ for (; remote->name; remote++) if (!strcmp( remote->name, name )) return TRUE;
+ if (FAILED(load_state( provider, name, &state )))
+ {
+ free_state( &state );
+ return TRUE;
+ }
+ if (sync_mode() == SYNC_UPLOAD) force_upload( provider, &state );
+ else if (state.dirty || !state.remote[0])
+ {
+ if (SUCCEEDED(cloud_upload( provider, &state )))
+ {
+ save_state( provider, &state );
+ provider->uploaded++;
+ }
+ }
+ else if (container_dir( provider, name, dir, sizeof(dir) ))
+ {
+ TRACE( "container %s was deleted in the cloud, removing local copy.\n", debugstr_a( name ) );
+ delete_directory( dir );
+ }
+ free_state( &state );
+ return TRUE;
+}
+
+static void force_upload( struct XGameSaveProvider *provider, struct container_state *state )
+{
+ for (UINT32 i = 0; i < state->count; i++) state->blobs[i].atom[0] = 0;
+ state->dirty = TRUE;
+ save_state( provider, state );
+ if (SUCCEEDED(cloud_upload( provider, state ))) provider->uploaded++;
+ save_state( provider, state );
+}
+
+static HRESULT cloud_sync( struct XGameSaveProvider *provider )
+{
+ struct remote_container *remote = NULL;
+ enum sync_mode mode;
+ const char *blobs, *item;
+ UINT32 count = 0, capacity = 0;
+ SIZE_T size;
+ BYTE *buffer;
+ DWORD status;
+ HRESULT hr;
+
+ if (FAILED(hr = xuser_device_authorization( provider->user, "http://xboxlive.com", &provider->auth ))) return hr;
+
+ if (FAILED(hr = cloud_request( provider, "GET", "", NULL, NULL, 0, &status, &buffer, &size ))) return hr;
+ if (status == 404)
+ {
+ free( buffer );
+ buffer = (BYTE *)strdup( "{\"blobs\":[]}" );
+ status = 200;
+ }
+ if (status != 200 || !buffer || !(blobs = json_find( (char *)buffer, "blobs" )) || *blobs != '[')
+ {
+ free( buffer );
+ return E_FAIL;
+ }
+ for (item = json_ws( blobs + 1 ); *item == '{'; item = json_ws( item ))
+ {
+ const char *end = json_skip( item );
+ char *fileName = json_find_string( item, "fileName" ), *comma;
+ struct remote_container *tmp;
+ if (!end) break;
+ if (fileName && (comma = strstr( fileName, ",savedgame" )) && !comma[10])
+ {
+ *comma = 0;
+ if (count + 1 >= capacity)
+ {
+ capacity = capacity ? capacity * 2 : 16;
+ if (!(tmp = realloc( remote, capacity * sizeof(*remote) ))) break;
+ remote = tmp;
+ }
+ remote[count].name = fileName;
+ remote[count].display = json_find_string( item, "displayName" );
+ remote[count].time = json_find_string( item, "clientFileTime" );
+ remote[++count].name = NULL;
+ fileName = NULL;
+ }
+ free( fileName );
+ item = json_ws( end );
+ if (*item == ',') item++;
+ }
+ free( buffer );
+
+ mode = sync_mode();
+ for (UINT32 i = 0; i < count; i++)
+ {
+ struct container_state state;
+ BOOL exists = SUCCEEDED(load_state( provider, remote[i].name, &state ));
+ BOOL remoteChanged = !exists || strcmp( state.remote, remote[i].time ? remote[i].time : "" );
+ if (mode == SYNC_UPLOAD)
+ {
+ if (exists) force_upload( provider, &state );
+ }
+ else if (mode == SYNC_DOWNLOAD || !exists || (remoteChanged && !state.dirty) || (remoteChanged && state.dirty && parse_iso_time( remote[i].time ) > state.time))
+ {
+ if (SUCCEEDED(cloud_download( provider, remote[i].name, remote[i].display, remote[i].time ))) provider->downloaded++;
+ }
+ else if (state.dirty && SUCCEEDED(cloud_upload( provider, &state )))
+ {
+ save_state( provider, &state );
+ provider->uploaded++;
+ }
+ free_state( &state );
+ }
+ if (remote)
+ {
+ enumerate_local( provider, sync_local_callback, remote );
+ for (UINT32 i = 0; i < count; i++)
+ {
+ free( remote[i].name );
+ free( remote[i].display );
+ free( remote[i].time );
+ }
+ free( remote );
+ }
+ else
+ {
+ struct remote_container empty = { 0 };
+ enumerate_local( provider, sync_local_callback, &empty );
+ }
+ return S_OK;
+}
+
+static HRESULT initialize_provider( XUserHandle user, const char *configurationId, XGameSaveProviderHandle *out )
+{
+ struct XGameSaveProvider *provider;
+ char localAppData[MAX_PATH], scid[128];
+ UINT64 xuid;
+ HRESULT hr;
+
+ TRACE( "user %p, configurationId %s, pfn %s.\n", user, debugstr_a( configurationId ), debugstr_a( packageFamilyName ) );
+
+ if (!user || !configurationId || !out) return E_INVALIDARG;
+ if (!(provider = calloc( 1, sizeof(*provider) ))) return E_OUTOFMEMORY;
+ InitializeCriticalSection( &provider->cs );
+ provider->quota = SAVE_QUOTA;
+ if (FAILED(hr = IXUserImpl_XUserDuplicateHandle( x_user_impl, user, &provider->user )) || !(provider->scid = strdup( configurationId )))
+ {
+ DeleteCriticalSection( &provider->cs );
+ free( provider );
+ return FAILED(hr) ? hr : E_OUTOFMEMORY;
+ }
+ xuid = xuser_get_xuid( user );
+ lstrcpynA( scid, configurationId, sizeof(scid) );
+ for (char *p = scid; *p; p++) if (!isalnum( (BYTE)*p ) && *p != '-') *p = '_';
+ if (!GetEnvironmentVariableA( "LOCALAPPDATA", localAppData, sizeof(localAppData) )) strcpy( localAppData, "C:\\users\\Public\\AppData\\Local" );
+ snprintf( provider->root, sizeof(provider->root), "%s\\XodusGameSave\\%I64u\\%s", localAppData, xuid, scid );
+ create_directories( provider->root );
+ snprintf( provider->base, sizeof(provider->base), "https://titlestorage.xboxlive.com/connectedstorage/users/xuid(%I64u)/scids/%s", xuid, configurationId );
+
+ provider->cloud = packageFamilyName != NULL;
+ if (provider->cloud && FAILED(hr = cloud_sync( provider )))
+ {
+ ERR( "cloud sync failed, hr %#lx.\n", hr );
+ cloud_disable( provider );
+ }
+
+ TRACE( "provider %p, root %s, cloud %d, downloaded %u, uploaded %u.\n", provider, debugstr_a( provider->root ), provider->cloud, provider->downloaded, provider->uploaded );
+ if (GetEnvironmentVariableA( "XODUS_SAVE_SYNC", NULL, 0 ))
+ MESSAGE( "xodus-savesync: cloud %d downloaded %u uploaded %u\n", provider->cloud, provider->downloaded, provider->uploaded );
+ *out = provider;
+ return S_OK;
+}
+
+static void close_provider( struct XGameSaveProvider *provider )
+{
+ if (!provider) return;
+ cloud_unlock( provider, FALSE );
+ IXUserImpl_XUserCloseHandle( x_user_impl, provider->user );
+ DeleteCriticalSection( &provider->cs );
+ free( provider->auth );
+ free( provider->scid );
+ free( provider );
+}
+
+struct usage_context
+{
+ UINT64 total;
+};
+
+static BOOL usage_callback( struct XGameSaveProvider *provider, const char *name, void *context )
+{
+ struct usage_context *usage = context;
+ struct container_state state;
+ if (SUCCEEDED(load_state( provider, name, &state ))) usage->total += state_total_size( &state );
+ free_state( &state );
+ return TRUE;
+}
+
+static INT64 remaining_quota( struct XGameSaveProvider *provider )
+{
+ struct usage_context usage = { 0 };
+ enumerate_local( provider, usage_callback, &usage );
+ return max( 0, provider->quota - (INT64)usage.total );
+}
+
+static HRESULT delete_container( struct XGameSaveProvider *provider, const char *name )
+{
+ char dir[MAX_PATH];
+ HRESULT hr;
+
+ if (!provider || !name || !*name) return E_INVALIDARG;
+ EnterCriticalSection( &provider->cs );
+ if (!container_dir( provider, name, dir, sizeof(dir) )) hr = E_OUTOFMEMORY;
+ else
+ {
+ delete_directory( dir );
+ hr = cloud_delete( provider, name );
+ if (FAILED(hr)) WARN( "cloud delete of %s failed, hr %#lx.\n", debugstr_a( name ), hr );
+ hr = S_OK;
+ }
+ LeaveCriticalSection( &provider->cs );
+ return hr;
+}
+
+struct info_context
+{
+ const char *prefix;
+ const char *exact;
+ void *context;
+ XGameSaveContainerInfoCallback *callback;
+ BOOL found;
+};
+
+static BOOL info_callback( struct XGameSaveProvider *provider, const char *name, void *context )
+{
+ struct info_context *ctx = context;
+ struct container_state state;
+ XGameSaveContainerInfo info;
+ BOOL more;
+
+ if (ctx->exact && strcmp( ctx->exact, name )) return TRUE;
+ if (ctx->prefix && strncmp( ctx->prefix, name, strlen( ctx->prefix ) )) return TRUE;
+ if (FAILED(load_state( provider, name, &state )))
+ {
+ free_state( &state );
+ return TRUE;
+ }
+ info.name = state.name;
+ info.displayName = state.display ? state.display : state.name;
+ info.blobCount = state.count;
+ info.totalSize = state_total_size( &state );
+ info.lastModifiedTime = state.time;
+ info.needsSync = FALSE;
+ ctx->found = TRUE;
+ more = ctx->callback( &info, ctx->context );
+ free_state( &state );
+ return more && !ctx->exact;
+}
+
+static HRESULT enumerate_containers( struct XGameSaveProvider *provider, const char *prefix, const char *exact, void *context, XGameSaveContainerInfoCallback *callback )
+{
+ struct info_context ctx = { prefix, exact, context, callback, FALSE };
+ if (!provider || !callback) return E_INVALIDARG;
+ EnterCriticalSection( &provider->cs );
+ enumerate_local( provider, info_callback, &ctx );
+ LeaveCriticalSection( &provider->cs );
+ return S_OK;
+}
+
+static HRESULT enumerate_blobs( struct XGameSaveContainer *container, const char *prefix, void *context, XGameSaveBlobInfoCallback *callback )
+{
+ struct container_state state;
+ HRESULT hr;
+
+ if (!container || !callback) return E_INVALIDARG;
+ EnterCriticalSection( &container->provider->cs );
+ if (SUCCEEDED(hr = load_state( container->provider, container->name, &state )))
+ {
+ for (UINT32 i = 0; i < state.count; i++)
+ {
+ XGameSaveBlobInfo info = { state.blobs[i].name, state.blobs[i].size };
+ if (prefix && strncmp( prefix, info.name, strlen( prefix ) )) continue;
+ if (!callback( &info, context )) break;
+ }
+ }
+ free_state( &state );
+ LeaveCriticalSection( &container->provider->cs );
+ return hr == HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND ) || hr == HRESULT_FROM_WIN32( ERROR_PATH_NOT_FOUND ) ? S_OK : hr;
+}
+
+struct read_request
+{
+ struct XGameSaveContainer *container;
+ char **names;
+ UINT32 count;
+ UINT32 *countOut;
+ BYTE *prepared;
+ SIZE_T preparedSize;
+ UINT32 preparedCount;
+};
+
+static HRESULT prepare_read( struct read_request *req )
+{
+ struct container_state state;
+ char path[MAX_PATH];
+ SIZE_T size = 0, offset;
+ UINT32 count;
+ HRESULT hr;
+
+ EnterCriticalSection( &req->container->provider->cs );
+ if (FAILED(hr = load_state( req->container->provider, req->container->name, &state )))
+ {
+ free_state( &state );
+ LeaveCriticalSection( &req->container->provider->cs );
+ return req->names ? E_GS_BLOB_NOT_FOUND : (req->preparedCount = 0, req->preparedSize = 0, S_OK);
+ }
+ count = req->names ? req->count : state.count;
+ for (UINT32 i = 0; i < count; i++)
+ {
+ struct blob_entry *entry = req->names ? find_blob( &state, req->names[i] ) : &state.blobs[i];
+ if (!entry)
+ {
+ free_state( &state );
+ LeaveCriticalSection( &req->container->provider->cs );
+ return E_GS_BLOB_NOT_FOUND;
+ }
+ size += sizeof(XGameSaveBlob) + strlen( entry->name ) + 1 + entry->size;
+ }
+ if (!(req->prepared = calloc( 1, size + 1 ))) hr = E_OUTOFMEMORY;
+ offset = count * sizeof(XGameSaveBlob);
+ for (UINT32 i = 0; SUCCEEDED(hr) && i < count; i++)
+ {
+ struct blob_entry *entry = req->names ? find_blob( &state, req->names[i] ) : &state.blobs[i];
+ XGameSaveBlob *blob = (XGameSaveBlob *)req->prepared + i;
+ SIZE_T dataSize;
+ BYTE *data;
+ blob->info.name = (const char *)(ULONG_PTR)offset;
+ strcpy( (char *)req->prepared + offset, entry->name );
+ offset += strlen( entry->name ) + 1;
+ blob_path( req->container->provider, req->container->name, entry->name, path, sizeof(path) );
+ if (FAILED(hr = read_file( path, &data, &dataSize ))) break;
+ blob->info.size = min( dataSize, entry->size );
+ blob->data = (UINT8 *)(ULONG_PTR)offset;
+ memcpy( req->prepared + offset, data, blob->info.size );
+ offset += entry->size;
+ free( data );
+ }
+ free_state( &state );
+ LeaveCriticalSection( &req->container->provider->cs );
+ req->preparedSize = size;
+ req->preparedCount = count;
+ return hr;
+}
+
+static void layout_read( struct read_request *req, void *buffer )
+{
+ memcpy( buffer, req->prepared, req->preparedSize );
+ for (UINT32 i = 0; i < req->preparedCount; i++)
+ {
+ XGameSaveBlob *blob = (XGameSaveBlob *)buffer + i;
+ blob->info.name = (const char *)buffer + (ULONG_PTR)blob->info.name;
+ blob->data = (UINT8 *)buffer + (ULONG_PTR)blob->data;
+ }
+}
+
+static void free_read_request( struct read_request *req )
+{
+ if (!req) return;
+ for (UINT32 i = 0; req->names && i < req->count; i++) free( req->names[i] );
+ free( req->names );
+ free( req->prepared );
+ free( req );
+}
+
+static struct read_request *create_read_request( struct XGameSaveContainer *container, const char **names, UINT32 count )
+{
+ struct read_request *req = calloc( 1, sizeof(*req) );
+ if (!req) return NULL;
+ req->container = container;
+ req->count = count;
+ if (names && count)
+ {
+ if (!(req->names = calloc( count, sizeof(char *) )))
+ {
+ free( req );
+ return NULL;
+ }
+ for (UINT32 i = 0; i < count; i++)
+ if (!(req->names[i] = strdup( names[i] )))
+ {
+ free_read_request( req );
+ return NULL;
+ }
+ }
+ return req;
+}
+
+static HRESULT submit_update( struct XGameSaveUpdate *update )
+{
+ struct XGameSaveProvider *provider = update->container->provider;
+ struct container_state state;
+ char path[MAX_PATH];
+ UINT64 total = 0;
+ HRESULT hr = S_OK;
+
+ for (UINT32 i = 0; i < update->count; i++) total += update->ops[i].size;
+ if (total > 16 * 1024 * 1024) return E_GS_UPDATE_TOO_BIG;
+
+ EnterCriticalSection( &provider->cs );
+ if (FAILED(load_state( provider, update->container->name, &state )))
+ {
+ free_state( &state );
+ if (!(state.name = strdup( update->container->name ))) hr = E_OUTOFMEMORY;
+ }
+ if (update->display)
+ {
+ free( state.display );
+ state.display = strdup( update->display );
+ }
+ else if (!state.display) state.display = strdup( update->container->name );
+ if (SUCCEEDED(hr))
+ {
+ char dir[MAX_PATH];
+ container_dir( provider, state.name, dir, sizeof(dir) );
+ create_directories( dir );
+ }
+
+ for (UINT32 i = 0; SUCCEEDED(hr) && i < update->count; i++)
+ {
+ struct update_op *op = &update->ops[i];
+ if (!blob_path( provider, state.name, op->name, path, sizeof(path) ))
+ {
+ hr = E_OUTOFMEMORY;
+ break;
+ }
+ if (op->remove)
+ {
+ DeleteFileA( path );
+ remove_blob( &state, op->name );
+ }
+ else
+ {
+ struct blob_entry *entry;
+ if (FAILED(hr = write_file( path, op->data, op->size ))) break;
+ if (!(entry = add_blob( &state, op->name )))
+ {
+ hr = E_OUTOFMEMORY;
+ break;
+ }
+ entry->size = op->size;
+ entry->atom[0] = 0;
+ }
+ }
+ if (SUCCEEDED(hr))
+ {
+ state.time = unix_now();
+ state.dirty = TRUE;
+ hr = save_state( provider, &state );
+ }
+ if (SUCCEEDED(hr) && provider->cloud)
+ {
+ HRESULT cloud = cloud_upload( provider, &state );
+ if (FAILED(cloud)) WARN( "cloud upload of %s failed, hr %#lx, it will be retried at next launch.\n", debugstr_a( state.name ), cloud );
+ save_state( provider, &state );
+ }
+ free_state( &state );
+ LeaveCriticalSection( &provider->cs );
+ TRACE( "update of %s, %u ops, hr %#lx.\n", debugstr_a( update->container->name ), update->count, hr );
+ return hr;
+}
+
+enum async_kind
+{
+ ASYNC_INITIALIZE,
+ ASYNC_QUOTA,
+ ASYNC_DELETE,
+ ASYNC_READ,
+ ASYNC_SUBMIT,
+};
+
+struct save_async
+{
+ enum async_kind kind;
+ XUserHandle user;
+ char *text;
+ struct XGameSaveProvider *provider;
+ struct read_request *read;
+ struct XGameSaveUpdate *update;
+ XGameSaveProviderHandle result;
+ INT64 quota;
+};
+
+static HRESULT WINAPI save_async_provider( XAsyncOp op, const XAsyncProviderData *data )
+{
+ struct save_async *ctx = data->context;
+ IXThreadingImpl *xthreading;
+ SIZE_T size = 0;
+ HRESULT hr;
+
+ TRACE( "op %d, kind %d.\n", op, ctx->kind );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ switch (op)
+ {
+ case XAsyncOp_Begin:
+ hr = IXThreadingImpl_XAsyncSchedule( xthreading, data->async, 0 );
+ break;
+
+ case XAsyncOp_DoWork:
+ switch (ctx->kind)
+ {
+ case ASYNC_INITIALIZE:
+ hr = initialize_provider( ctx->user, ctx->text, &ctx->result );
+ size = sizeof(XGameSaveProviderHandle);
+ break;
+ case ASYNC_QUOTA:
+ EnterCriticalSection( &ctx->provider->cs );
+ ctx->quota = remaining_quota( ctx->provider );
+ LeaveCriticalSection( &ctx->provider->cs );
+ hr = S_OK;
+ size = sizeof(INT64);
+ break;
+ case ASYNC_DELETE:
+ hr = delete_container( ctx->provider, ctx->text );
+ break;
+ case ASYNC_READ:
+ hr = prepare_read( ctx->read );
+ size = max( ctx->read->preparedSize, 1 );
+ break;
+ case ASYNC_SUBMIT:
+ hr = submit_update( ctx->update );
+ break;
+ }
+ IXThreadingImpl_XAsyncComplete( xthreading, data->async, hr, SUCCEEDED(hr) ? size : 0 );
+ hr = S_OK;
+ break;
+
+ case XAsyncOp_GetResult:
+ switch (ctx->kind)
+ {
+ case ASYNC_INITIALIZE:
+ memcpy( data->buffer, &ctx->result, sizeof(ctx->result) );
+ ctx->result = NULL;
+ break;
+ case ASYNC_QUOTA:
+ memcpy( data->buffer, &ctx->quota, sizeof(ctx->quota) );
+ break;
+ case ASYNC_READ:
+ layout_read( ctx->read, data->buffer );
+ if (ctx->read->countOut) *ctx->read->countOut = ctx->read->preparedCount;
+ break;
+ default:
+ break;
+ }
+ break;
+
+ case XAsyncOp_Cleanup:
+ if (ctx->result) close_provider( ctx->result );
+ if (ctx->user) IXUserImpl_XUserCloseHandle( x_user_impl, ctx->user );
+ free_read_request( ctx->read );
+ free( ctx->text );
+ free( ctx );
+ break;
+
+ case XAsyncOp_Cancel:
+ break;
+ }
+ IXThreadingImpl_Release( xthreading );
+ return hr;
+}
+
+static HRESULT begin_save_async( struct save_async *ctx, XAsyncBlock *async, const char *name )
+{
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ if (!async)
+ {
+ free( ctx );
+ return E_INVALIDARG;
+ }
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading )))
+ {
+ free( ctx );
+ return hr;
+ }
+ hr = IXThreadingImpl_XAsyncBegin( xthreading, async, ctx, begin_save_async, name, save_async_provider );
+ IXThreadingImpl_Release( xthreading );
+ return hr;
+}
+
+static HRESULT get_save_result( XAsyncBlock *async, SIZE_T size, void *buffer )
+{
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResult( xthreading, async, begin_save_async, size, buffer, NULL );
+ IXThreadingImpl_Release( xthreading );
+ TRACE( "async %p, size %Iu -> hr %#lx.\n", async, size, hr );
+ return hr;
+}
+
static HRESULT WINAPI x_game_save_XGameSaveInitializeProvider( IXGameSaveImpl3 *iface, XUserHandle requestingUser, const char *configurationId, BOOLEAN syncOnDemand, XGameSaveProviderHandle *provider )
{
- FIXME( "iface %p, requestingUser %p, configurationId %s, syncOnDemand %d, provider %p stub!\n", iface, requestingUser, debugstr_a( configurationId ), syncOnDemand, provider );
- return E_NOTIMPL;
+ TRACE( "iface %p, requestingUser %p, configurationId %s, syncOnDemand %d, provider %p.\n", iface, requestingUser, debugstr_a( configurationId ), syncOnDemand, provider );
+ return initialize_provider( requestingUser, configurationId, provider );
}
static HRESULT WINAPI x_game_save_XGameSaveInitializeProviderAsync( IXGameSaveImpl3 *iface, XUserHandle requestingUser, const char *configurationId, BOOLEAN syncOnDemand, XAsyncBlock *async )
{
- FIXME( "iface %p, requestingUser %p, configurationId %s, syncOnDemand %d, async %p stub!\n", iface, requestingUser, debugstr_a( configurationId ), syncOnDemand, async );
- return E_NOTIMPL;
+ struct save_async *ctx;
+ HRESULT hr;
+
+ TRACE( "iface %p, requestingUser %p, configurationId %s, syncOnDemand %d, async %p.\n", iface, requestingUser, debugstr_a( configurationId ), syncOnDemand, async );
+
+ if (!requestingUser || !configurationId) return E_INVALIDARG;
+ if (!(ctx = calloc( 1, sizeof(*ctx) ))) return E_OUTOFMEMORY;
+ ctx->kind = ASYNC_INITIALIZE;
+ if (!(ctx->text = strdup( configurationId )) || FAILED(hr = IXUserImpl_XUserDuplicateHandle( x_user_impl, requestingUser, &ctx->user )))
+ {
+ free( ctx->text );
+ free( ctx );
+ return E_OUTOFMEMORY;
+ }
+ return begin_save_async( ctx, async, "XGameSaveInitializeProviderAsync" );
}
static HRESULT WINAPI x_game_save_XGameSaveInitializeProviderResult( IXGameSaveImpl3 *iface, XAsyncBlock *async, XGameSaveProviderHandle *provider )
{
- FIXME( "iface %p, async %p, provider %p stub!\n", iface, async, provider );
- return E_NOTIMPL;
+ TRACE( "iface %p, async %p, provider %p.\n", iface, async, provider );
+ if (!provider) return E_INVALIDARG;
+ return get_save_result( async, sizeof(*provider), provider );
}
static void WINAPI x_game_save_XGameSaveCloseProvider( IXGameSaveImpl3 *iface, XGameSaveProviderHandle provider )
{
- FIXME( "iface %p, provider %p stub!\n", iface, provider );
+ TRACE( "iface %p, provider %p.\n", iface, provider );
+ close_provider( provider );
}
static HRESULT WINAPI x_game_save_XGameSaveGetRemainingQuota( IXGameSaveImpl3 *iface, XGameSaveProviderHandle provider, INT64 *remainingQuota )
{
- FIXME( "iface %p, provider %p, remainingQuota %p stub!\n", iface, provider, remainingQuota );
- return E_NOTIMPL;
+ TRACE( "iface %p, provider %p, remainingQuota %p.\n", iface, provider, remainingQuota );
+ if (!provider || !remainingQuota) return E_INVALIDARG;
+ EnterCriticalSection( &provider->cs );
+ *remainingQuota = remaining_quota( provider );
+ LeaveCriticalSection( &provider->cs );
+ return S_OK;
}
static HRESULT WINAPI x_game_save_XGameSaveGetRemainingQuotaAsync( IXGameSaveImpl3 *iface, XGameSaveProviderHandle provider, XAsyncBlock *async )
{
- FIXME( "iface %p, provider %p, async %p stub!\n", iface, provider, async );
- return E_NOTIMPL;
+ struct save_async *ctx;
+
+ TRACE( "iface %p, provider %p, async %p.\n", iface, provider, async );
+
+ if (!provider) return E_INVALIDARG;
+ if (!(ctx = calloc( 1, sizeof(*ctx) ))) return E_OUTOFMEMORY;
+ ctx->kind = ASYNC_QUOTA;
+ ctx->provider = provider;
+ return begin_save_async( ctx, async, "XGameSaveGetRemainingQuotaAsync" );
}
static HRESULT WINAPI x_game_save_XGameSaveGetRemainingQuotaResult( IXGameSaveImpl3 *iface, XAsyncBlock *async, INT64 *remainingQuota )
{
- FIXME( "iface %p, async %p, remainingQuota %p stub!\n", iface, async, remainingQuota );
- return E_NOTIMPL;
+ TRACE( "iface %p, async %p, remainingQuota %p.\n", iface, async, remainingQuota );
+ if (!remainingQuota) return E_INVALIDARG;
+ return get_save_result( async, sizeof(*remainingQuota), remainingQuota );
}
static HRESULT WINAPI x_game_save_XGameSaveDeleteContainer( IXGameSaveImpl3 *iface, XGameSaveProviderHandle provider, const char *containerName )
{
- FIXME( "iface %p, provider %p, containerName %s stub!\n", iface, provider, debugstr_a( containerName ) );
- return E_NOTIMPL;
+ TRACE( "iface %p, provider %p, containerName %s.\n", iface, provider, debugstr_a( containerName ) );
+ return delete_container( provider, containerName );
}
static HRESULT WINAPI x_game_save_XGameSaveDeleteContainerAsync( IXGameSaveImpl3 *iface, XGameSaveProviderHandle provider, const char *containerName, XAsyncBlock *async )
{
- FIXME( "iface %p, provider %p, containerName %s, async %p stub!\n", iface, provider, debugstr_a( containerName ), async );
- return E_NOTIMPL;
+ struct save_async *ctx;
+
+ TRACE( "iface %p, provider %p, containerName %s, async %p.\n", iface, provider, debugstr_a( containerName ), async );
+
+ if (!provider || !containerName) return E_INVALIDARG;
+ if (!(ctx = calloc( 1, sizeof(*ctx) ))) return E_OUTOFMEMORY;
+ ctx->kind = ASYNC_DELETE;
+ ctx->provider = provider;
+ if (!(ctx->text = strdup( containerName )))
+ {
+ free( ctx );
+ return E_OUTOFMEMORY;
+ }
+ return begin_save_async( ctx, async, "XGameSaveDeleteContainerAsync" );
}
static HRESULT WINAPI x_game_save_XGameSaveDeleteContainerResult( IXGameSaveImpl3 *iface, XAsyncBlock *async )
{
- FIXME( "iface %p, async %p stub!\n", iface, async );
- return E_NOTIMPL;
+ TRACE( "iface %p, async %p.\n", iface, async );
+ return get_save_result( async, 0, NULL );
}
static HRESULT WINAPI x_game_save_XGameSaveGetContainerInfo( IXGameSaveImpl3 *iface, XGameSaveProviderHandle provider, const char *containerName, void *context, XGameSaveContainerInfoCallback *callback )
{
- FIXME( "iface %p, provider %p, containerName %s, context %p, callback %p stub!\n", iface, provider, debugstr_a( containerName ), context, callback );
- return E_NOTIMPL;
+ TRACE( "iface %p, provider %p, containerName %s, context %p, callback %p.\n", iface, provider, debugstr_a( containerName ), context, callback );
+ if (!containerName) return E_INVALIDARG;
+ return enumerate_containers( provider, NULL, containerName, context, callback );
}
static HRESULT WINAPI x_game_save_XGameSaveEnumerateContainerInfo( IXGameSaveImpl3 *iface, XGameSaveProviderHandle provider, void *context, XGameSaveContainerInfoCallback *callback )
{
- FIXME( "iface %p, provider %p, context %p, callback %p stub!\n", iface, provider, context, callback );
- return E_NOTIMPL;
+ TRACE( "iface %p, provider %p, context %p, callback %p.\n", iface, provider, context, callback );
+ return enumerate_containers( provider, NULL, NULL, context, callback );
}
static HRESULT WINAPI x_game_save_XGameSaveEnumerateContainerInfoByName( IXGameSaveImpl3 *iface, XGameSaveProviderHandle provider, const char *containerNamePrefix, void *context, XGameSaveContainerInfoCallback *callback )
{
- FIXME( "iface %p, provider %p, containerNamePrefix %s, context %p, callback %p stub!\n", iface, provider, debugstr_a( containerNamePrefix ), context, callback );
- return E_NOTIMPL;
+ TRACE( "iface %p, provider %p, containerNamePrefix %s, context %p, callback %p.\n", iface, provider, debugstr_a( containerNamePrefix ), context, callback );
+ return enumerate_containers( provider, containerNamePrefix, NULL, context, callback );
}
static HRESULT WINAPI x_game_save_XGameSaveCreateContainer( IXGameSaveImpl3 *iface, XGameSaveProviderHandle provider, const char *containerName, XGameSaveContainerHandle *containerContext )
{
- FIXME( "iface %p, provider %p, containerName %s, containerContext %p stub!\n", iface, provider, debugstr_a( containerName ), containerContext );
- return E_NOTIMPL;
+ struct XGameSaveContainer *container;
+
+ TRACE( "iface %p, provider %p, containerName %s, containerContext %p.\n", iface, provider, debugstr_a( containerName ), containerContext );
+
+ if (!provider || !containerContext) return E_INVALIDARG;
+ if (!containerName || !*containerName || strlen( containerName ) > 256) return E_GS_INVALID_CONTAINER_NAME;
+ if (!(container = calloc( 1, sizeof(*container) ))) return E_OUTOFMEMORY;
+ container->provider = provider;
+ if (!(container->name = strdup( containerName )))
+ {
+ free( container );
+ return E_OUTOFMEMORY;
+ }
+ *containerContext = container;
+ return S_OK;
}
static void WINAPI x_game_save_XGameSaveCloseContainer( IXGameSaveImpl3 *iface, XGameSaveContainerHandle context )
{
- FIXME( "iface %p, context %p stub!\n", iface, context );
+ TRACE( "iface %p, context %p.\n", iface, context );
+ if (!context) return;
+ free( context->name );
+ free( context );
}
static HRESULT WINAPI x_game_save_XGameSaveEnumerateBlobInfo( IXGameSaveImpl3 *iface, XGameSaveContainerHandle container, void *context, XGameSaveBlobInfoCallback *callback )
{
- FIXME( "iface %p, container %p, context %p, callback %p stub!\n", iface, container, context, callback );
- return E_NOTIMPL;
+ TRACE( "iface %p, container %p, context %p, callback %p.\n", iface, container, context, callback );
+ return enumerate_blobs( container, NULL, context, callback );
}
static HRESULT WINAPI x_game_save_XGameSaveEnumerateBlobInfoByName( IXGameSaveImpl3 *iface, XGameSaveContainerHandle container, const char *blobNamePrefix, void *context, XGameSaveBlobInfoCallback *callback )
{
- FIXME( "iface %p, container %p, blobNamePrefix %s, context %p, callback %p stub!\n", iface, container, debugstr_a( blobNamePrefix ), context, callback );
- return E_NOTIMPL;
+ TRACE( "iface %p, container %p, blobNamePrefix %s, context %p, callback %p.\n", iface, container, debugstr_a( blobNamePrefix ), context, callback );
+ return enumerate_blobs( container, blobNamePrefix, context, callback );
}
static HRESULT WINAPI x_game_save_XGameSaveReadBlobData( IXGameSaveImpl3 *iface, XGameSaveContainerHandle container, const char **blobNames, UINT32 *countOfBlobs, SIZE_T blobsSize, XGameSaveBlob *blobData )
{
- FIXME( "iface %p, container %p, blobNames %p, countOfBlobs %p, blobsSize %Iu, provider %p stub!\n", iface, container, blobNames, countOfBlobs, blobsSize, blobData );
- return E_NOTIMPL;
+ struct read_request *req;
+ HRESULT hr;
+
+ TRACE( "iface %p, container %p, blobNames %p, countOfBlobs %p, blobsSize %Iu, blobData %p.\n", iface, container, blobNames, countOfBlobs, blobsSize, blobData );
+
+ if (!container || !countOfBlobs || (!blobData && blobsSize)) return E_INVALIDARG;
+ if (!(req = create_read_request( container, blobNames, blobNames ? *countOfBlobs : 0 ))) return E_OUTOFMEMORY;
+ if (SUCCEEDED(hr = prepare_read( req )))
+ {
+ if (blobsSize < req->preparedSize) hr = E_GS_PROVIDED_BUFFER_TOO_SMALL;
+ else
+ {
+ layout_read( req, blobData );
+ *countOfBlobs = req->preparedCount;
+ }
+ }
+ free_read_request( req );
+ return hr;
}
static HRESULT WINAPI x_game_save_XGameSaveReadBlobDataAsync( IXGameSaveImpl3 *iface, XGameSaveContainerHandle container, const char **blobNames, UINT32 countOfBlobs, XAsyncBlock *async )
{
- FIXME( "iface %p, container %p, blobNames %p, countOfBlobs %u, async %p stub!\n", iface, container, blobNames, countOfBlobs, async );
- return E_NOTIMPL;
+ struct save_async *ctx;
+
+ TRACE( "iface %p, container %p, blobNames %p, countOfBlobs %u, async %p.\n", iface, container, blobNames, countOfBlobs, async );
+
+ if (!container) return E_INVALIDARG;
+ if (!(ctx = calloc( 1, sizeof(*ctx) ))) return E_OUTOFMEMORY;
+ ctx->kind = ASYNC_READ;
+ if (!(ctx->read = create_read_request( container, blobNames, blobNames ? countOfBlobs : 0 )))
+ {
+ free( ctx );
+ return E_OUTOFMEMORY;
+ }
+ return begin_save_async( ctx, async, "XGameSaveReadBlobDataAsync" );
}
static HRESULT WINAPI x_game_save_XGameSaveReadBlobDataResult( IXGameSaveImpl3 *iface, XAsyncBlock *async, SIZE_T blobsSize, XGameSaveBlob *blobData, UINT32 *countOfBlobs )
{
- FIXME( "iface %p, async %p, blobsSize %Iu, blobData %p, countOfBlobs %p stub!\n", iface, async, blobsSize, blobData, countOfBlobs );
- return E_NOTIMPL;
+ struct save_async *ctx;
+
+ TRACE( "iface %p, async %p, blobsSize %Iu, blobData %p, countOfBlobs %p.\n", iface, async, blobsSize, blobData, countOfBlobs );
+
+ if (!async || !countOfBlobs || !async->internal[0]) return E_INVALIDARG;
+ *countOfBlobs = 0;
+ ctx = ((XAsyncProviderData *)async->internal[0])->context;
+ if (ctx && ctx->read) ctx->read->countOut = countOfBlobs;
+ return get_save_result( async, blobsSize, blobData );
}
static HRESULT WINAPI x_game_save_XGameSaveCreateUpdate( IXGameSaveImpl3 *iface, XGameSaveContainerHandle container, const char *containerDisplayName, XGameSaveUpdateHandle *updateContext )
{
- FIXME( "iface %p, container %p, containerDisplayName %s, updateContext %p stub!\n", iface, container, debugstr_a( containerDisplayName ), updateContext );
- return E_NOTIMPL;
+ struct XGameSaveUpdate *update;
+
+ TRACE( "iface %p, container %p, containerDisplayName %s, updateContext %p.\n", iface, container, debugstr_a( containerDisplayName ), updateContext );
+
+ if (!container || !updateContext) return E_INVALIDARG;
+ if (!(update = calloc( 1, sizeof(*update) ))) return E_OUTOFMEMORY;
+ update->container = container;
+ if (containerDisplayName && !(update->display = strdup( containerDisplayName )))
+ {
+ free( update );
+ return E_OUTOFMEMORY;
+ }
+ *updateContext = update;
+ return S_OK;
}
static void WINAPI x_game_save_XGameSaveCloseUpdate( IXGameSaveImpl3 *iface, XGameSaveUpdateHandle context )
{
- FIXME( "iface %p, context %p stub!\n", iface, context );
+ TRACE( "iface %p, context %p.\n", iface, context );
+ if (!context) return;
+ for (UINT32 i = 0; i < context->count; i++)
+ {
+ free( context->ops[i].name );
+ free( context->ops[i].data );
+ }
+ free( context->ops );
+ free( context->display );
+ free( context );
+}
+
+static HRESULT add_update_op( struct XGameSaveUpdate *update, const char *name, const UINT8 *data, SIZE_T size, BOOL remove )
+{
+ struct update_op *op;
+
+ if (!update || !name || !*name) return E_INVALIDARG;
+ for (UINT32 i = 0; i < update->count; i++)
+ if (!strcmp( update->ops[i].name, name )) return E_INVALIDARG;
+ if (update->count == update->capacity)
+ {
+ UINT32 capacity = update->capacity ? update->capacity * 2 : 8;
+ if (!(op = realloc( update->ops, capacity * sizeof(*op) ))) return E_OUTOFMEMORY;
+ update->ops = op;
+ update->capacity = capacity;
+ }
+ op = &update->ops[update->count];
+ memset( op, 0, sizeof(*op) );
+ if (!(op->name = strdup( name ))) return E_OUTOFMEMORY;
+ op->remove = remove;
+ if (!remove)
+ {
+ if (!(op->data = malloc( max( size, 1 ) )))
+ {
+ free( op->name );
+ return E_OUTOFMEMORY;
+ }
+ if (size) memcpy( op->data, data, size );
+ op->size = size;
+ }
+ update->count++;
+ return S_OK;
}
static HRESULT WINAPI x_game_save_XGameSaveSubmitBlobWrite( IXGameSaveImpl3 *iface, XGameSaveUpdateHandle updateContext, const char *blobName, UINT8 *data, SIZE_T byteCount )
{
- FIXME( "iface %p, updateContext %p, blobName %s, data %p, byteCount %Iu stub!\n", iface, updateContext, debugstr_a( blobName ), data, byteCount );
- return E_NOTIMPL;
+ TRACE( "iface %p, updateContext %p, blobName %s, data %p, byteCount %Iu.\n", iface, updateContext, debugstr_a( blobName ), data, byteCount );
+ if (!data && byteCount) return E_INVALIDARG;
+ return add_update_op( updateContext, blobName, data, byteCount, FALSE );
}
static HRESULT WINAPI x_game_save_XGameSaveSubmitBlobDelete( IXGameSaveImpl3 *iface, XGameSaveUpdateHandle updateContext, const char *blobName )
{
- FIXME( "iface %p, updateContext %p, blobName %s stub!\n", iface, updateContext, debugstr_a( blobName ) );
- return E_NOTIMPL;
+ TRACE( "iface %p, updateContext %p, blobName %s.\n", iface, updateContext, debugstr_a( blobName ) );
+ return add_update_op( updateContext, blobName, NULL, 0, TRUE );
}
static HRESULT WINAPI x_game_save_XGameSaveSubmitUpdate( IXGameSaveImpl3 *iface, XGameSaveUpdateHandle updateContext )
{
- FIXME( "iface %p, updateContext %p stub!\n", iface, updateContext );
- return E_NOTIMPL;
+ TRACE( "iface %p, updateContext %p.\n", iface, updateContext );
+ if (!updateContext) return E_INVALIDARG;
+ return submit_update( updateContext );
}
static HRESULT WINAPI x_game_save_XGameSaveSubmitUpdateAsync( IXGameSaveImpl3 *iface, XGameSaveUpdateHandle updateContext, XAsyncBlock *async )
{
- FIXME( "iface %p, updateContext %p, async %p stub!\n", iface, updateContext, async );
- return E_NOTIMPL;
+ struct save_async *ctx;
+
+ TRACE( "iface %p, updateContext %p, async %p.\n", iface, updateContext, async );
+
+ if (!updateContext) return E_INVALIDARG;
+ if (!(ctx = calloc( 1, sizeof(*ctx) ))) return E_OUTOFMEMORY;
+ ctx->kind = ASYNC_SUBMIT;
+ ctx->update = updateContext;
+ return begin_save_async( ctx, async, "XGameSaveSubmitUpdateAsync" );
}
static HRESULT WINAPI x_game_save_XGameSaveSubmitUpdateResult( IXGameSaveImpl3 *iface, XAsyncBlock *async )
{
- FIXME( "iface %p, async %p stub!\n", iface, async );
- return E_NOTIMPL;
+ TRACE( "iface %p, async %p.\n", iface, async );
+ return get_save_result( async, 0, NULL );
}
static HRESULT WINAPI x_game_save_XGameSaveFilesGetFolderWithUiAsync( IXGameSaveImpl3 *iface, XUserHandle requestingUser, const char *configurationId, XAsyncBlock *async )
@@ -247,7 +1841,21 @@ static HRESULT WINAPI x_game_save_XGameSaveFilesGetRemainingQuota( IXGameSaveImp
return E_NOTIMPL;
}
-static const struct IXGameSaveImpl3Vtbl x_game_save_vtbl =
+#define UNKNOWN_SLOT(n) \
+static HRESULT WINAPI x_game_save_unknown##n( void *iface, void *a, void *b, void *c, void *d ) \
+{ \
+ FIXME( "unknown IXGameSaveImpl4 method %d called, iface %p, args %p %p %p %p.\n", n, iface, a, b, c, d ); \
+ return E_NOTIMPL; \
+}
+UNKNOWN_SLOT(0) UNKNOWN_SLOT(1) UNKNOWN_SLOT(2) UNKNOWN_SLOT(3) UNKNOWN_SLOT(4) UNKNOWN_SLOT(5) UNKNOWN_SLOT(6) UNKNOWN_SLOT(7)
+UNKNOWN_SLOT(8) UNKNOWN_SLOT(9) UNKNOWN_SLOT(10) UNKNOWN_SLOT(11) UNKNOWN_SLOT(12) UNKNOWN_SLOT(13) UNKNOWN_SLOT(14) UNKNOWN_SLOT(15)
+
+static const struct
+{
+ struct IXGameSaveImpl3Vtbl base;
+ void *extra[16];
+} x_game_save_vtbl_ext =
+{
{
x_game_save_QueryInterface,
x_game_save_AddRef,
@@ -284,11 +1892,18 @@ static const struct IXGameSaveImpl3Vtbl x_game_save_vtbl =
x_game_save_XGameSaveFilesGetFolderWithUiAsync,
x_game_save_XGameSaveFilesGetFolderWithUiResult,
x_game_save_XGameSaveFilesGetRemainingQuota,
+},
+{
+ x_game_save_unknown0, x_game_save_unknown1, x_game_save_unknown2, x_game_save_unknown3,
+ x_game_save_unknown4, x_game_save_unknown5, x_game_save_unknown6, x_game_save_unknown7,
+ x_game_save_unknown8, x_game_save_unknown9, x_game_save_unknown10, x_game_save_unknown11,
+ x_game_save_unknown12, x_game_save_unknown13, x_game_save_unknown14, x_game_save_unknown15,
+}
};
static struct x_game_save x_game_save =
{
- {&x_game_save_vtbl},
+ {&x_game_save_vtbl_ext.base},
0,
};
diff --git a/dlls/xgameruntime/xgamesave.idl b/dlls/xgameruntime/xgamesave.idl
index e065e10..bbc055b 100644
--- a/dlls/xgameruntime/xgamesave.idl
+++ b/dlls/xgameruntime/xgamesave.idl
@@ -118,6 +118,15 @@ interface IXGameSaveImpl3 : IXGameSaveImpl2
{
}
+[
+ local,
+ object,
+ uuid(ab4ae4fb-6508-4950-a032-45fd4bf8c43b)
+]
+interface IXGameSaveImpl4 : IXGameSaveImpl3
+{
+}
+
[
uuid(704c3f58-e629-4cc2-b197-30511b996fe2)
]
diff --git a/dlls/xgameruntime/xnetworking.c b/dlls/xgameruntime/xnetworking.c
index 81830c9..7c7d6c1 100644
--- a/dlls/xgameruntime/xnetworking.c
+++ b/dlls/xgameruntime/xnetworking.c
@@ -75,28 +75,77 @@ static HRESULT WINAPI x_networking_XNetworkingQueryPreferredLocalUdpMultiplayerP
return E_NOTIMPL;
}
+/* The platform has no actual port preference on this runtime; completing
+ * with 0 lets the caller's socket bind choose freely, which is what native
+ * GDK reports when no preference applies. */
+static HRESULT WINAPI XNetworkingPreferredPortProvider( XAsyncOp op, const XAsyncProviderData *data )
+{
+ IXThreadingImpl *threading;
+ HRESULT hr;
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&threading ))) return hr;
+ switch (op)
+ {
+ case XAsyncOp_Begin:
+ hr = IXThreadingImpl_XAsyncSchedule( threading, data->async, 0 );
+ break;
+ case XAsyncOp_DoWork:
+ IXThreadingImpl_XAsyncComplete( threading, data->async, S_OK, sizeof(UINT16) );
+ hr = S_OK;
+ break;
+ case XAsyncOp_GetResult:
+ if (!data->buffer || data->bufferSize < sizeof(UINT16)) hr = HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+ else { *(UINT16 *)data->buffer = 0; hr = S_OK; }
+ break;
+ default:
+ hr = S_OK;
+ break;
+ }
+ IXThreadingImpl_Release( threading );
+ return hr;
+}
+
static HRESULT WINAPI x_networking_XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync( IXNetworkingImpl2 *iface, XAsyncBlock *asyncBlock )
{
- FIXME( "iface %p, asyncBlock %p stub!\n", iface, asyncBlock );
- return E_NOTIMPL;
+ IXThreadingImpl *threading;
+ HRESULT hr;
+
+ TRACE( "iface %p, asyncBlock %p.\n", iface, asyncBlock );
+
+ if (!asyncBlock) return E_INVALIDARG;
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&threading ))) return hr;
+ hr = IXThreadingImpl_XAsyncBegin( threading, asyncBlock, NULL, NULL, "XNetworkingQueryPreferredLocalUdpMultiplayerPort", XNetworkingPreferredPortProvider );
+ IXThreadingImpl_Release( threading );
+ return hr;
}
static HRESULT WINAPI x_networking_XNetworkingQueryPreferredLocalUdpMultiplayerPortAsyncResult( IXNetworkingImpl2 *iface, XAsyncBlock *asyncBlock, UINT16 *preferredLocalUdpMultiplayerPort )
{
- FIXME( "iface %p, asyncBlock %p, preferredLocalUdpMultiplayerPort %p stub!\n", iface, asyncBlock, preferredLocalUdpMultiplayerPort );
- return E_NOTIMPL;
+ IXThreadingImpl *threading;
+ HRESULT hr;
+
+ TRACE( "iface %p, asyncBlock %p, preferredLocalUdpMultiplayerPort %p.\n", iface, asyncBlock, preferredLocalUdpMultiplayerPort );
+
+ if (!preferredLocalUdpMultiplayerPort) return E_INVALIDARG;
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&threading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResult( threading, asyncBlock, NULL, sizeof(UINT16), preferredLocalUdpMultiplayerPort, NULL );
+ IXThreadingImpl_Release( threading );
+ return hr;
}
static HRESULT WINAPI x_networking_XNetworkingRegisterPreferredLocalUdpMultiplayerPortChanged( IXNetworkingImpl2 *iface, XTaskQueueHandle queue, void *context, XNetworkingPreferredLocalUdpMultiplayerPortChangedCallback *callback, XTaskQueueRegistrationToken *token )
{
- FIXME( "iface %p, queue %p, context %p, callback %p, token %p stub!\n", iface, queue, context, callback, token );
- return E_NOTIMPL;
+ static LONG64 next_token;
+ TRACE( "iface %p, queue %p, context %p, callback %p, token %p.\n", iface, queue, context, callback, token );
+ if (!callback || !token) return E_POINTER;
+ token->token = InterlockedIncrement64( &next_token );
+ return S_OK;
}
static BOOLEAN WINAPI x_networking_XNetworkingUnregisterPreferredLocalUdpMultiplayerPortChanged( IXNetworkingImpl2 *iface, XTaskQueueRegistrationToken token, BOOLEAN wait )
{
- FIXME( "iface %p, token %p, wait %d stub!\n", iface, &token, wait );
- return FALSE;
+ TRACE( "iface %p, token %p, wait %d.\n", iface, &token, wait );
+ return TRUE;
}
static HRESULT WINAPI x_networking_XNetworkingQuerySecurityInformationForUrlAsync( IXNetworkingImpl2 *iface, const char *url, XAsyncBlock *asyncBlock )
@@ -143,20 +192,31 @@ static HRESULT WINAPI x_networking_XNetworkingVerifyServerCertificate( IXNetwork
static HRESULT WINAPI x_networking_XNetworkingGetConnectivityHint( IXNetworkingImpl2 *iface, XNetworkingConnectivityHint *connectivityHint )
{
- FIXME( "iface %p, connectivityHint %p stub!\n", iface, connectivityHint );
- return E_NOTIMPL;
+ TRACE( "iface %p, connectivityHint %p.\n", iface, connectivityHint );
+ if (!connectivityHint) return E_POINTER;
+ connectivityHint->connectivityLevel = XNetworkingConnectivityLevelHint_InternetAccess;
+ connectivityHint->connectivityCost = XNetworkingConnectivityCostHint_Unrestricted;
+ connectivityHint->ianaInterfaceType = 6;
+ connectivityHint->networkInitialized = TRUE;
+ connectivityHint->approachingDataLimit = FALSE;
+ connectivityHint->overDataLimit = FALSE;
+ connectivityHint->roaming = FALSE;
+ return S_OK;
}
static HRESULT WINAPI x_networking_XNetworkingRegisterConnectivityHintChanged( IXNetworkingImpl2 *iface, XTaskQueueHandle queue, void *context, XNetworkingConnectivityHintChangedCallback *callback, XTaskQueueRegistrationToken *token )
{
- FIXME( "iface %p, queue %p, context %p, callback %p, token %p stub!\n", iface, queue, context, callback, token );
- return E_NOTIMPL;
+ static LONG64 next_token;
+ TRACE( "iface %p, queue %p, context %p, callback %p, token %p.\n", iface, queue, context, callback, token );
+ if (!callback || !token) return E_POINTER;
+ token->token = InterlockedIncrement64( &next_token );
+ return S_OK;
}
static BOOLEAN WINAPI x_networking_XNetworkingUnregisterConnectivityHintChanged( IXNetworkingImpl2 *iface, XTaskQueueRegistrationToken token, BOOLEAN wait )
{
- FIXME( "iface %p, token %p, wait %d stub!\n", iface, &token, wait );
- return FALSE;
+ TRACE( "iface %p, token %p, wait %d.\n", iface, &token, wait );
+ return TRUE;
}
static HRESULT WINAPI x_networking_XNetworkingQueryConfigurationSetting( IXNetworkingImpl2 *iface, XNetworkingConfigurationSetting configurationSetting, UINT64 *value )
diff --git a/dlls/xgameruntime/xpackage.c b/dlls/xgameruntime/xpackage.c
index fa25a33..004d2e2 100644
--- a/dlls/xgameruntime/xpackage.c
+++ b/dlls/xgameruntime/xpackage.c
@@ -20,32 +20,34 @@
*/
#include "private.h"
+#include <string.h>
WINE_DEFAULT_DEBUG_CHANNEL(gdkc);
struct x_package
{
- IXPackageImpl3 IXPackageImpl3_iface;
+ IXPackageImpl4 IXPackageImpl4_iface;
LONG ref;
};
-static inline struct x_package *impl_from_IXPackageImpl3( IXPackageImpl3 *iface )
+static inline struct x_package *impl_from_IXPackageImpl4( IXPackageImpl4 *iface )
{
- return CONTAINING_RECORD( iface, struct x_package, IXPackageImpl3_iface );
+ return CONTAINING_RECORD( iface, struct x_package, IXPackageImpl4_iface );
}
-static HRESULT WINAPI x_package_QueryInterface( IXPackageImpl3 *iface, REFIID iid, void **out )
+static HRESULT WINAPI x_package_QueryInterface( IXPackageImpl4 *iface, REFIID iid, void **out )
{
- struct x_package *impl = impl_from_IXPackageImpl3( iface );
+ struct x_package *impl = impl_from_IXPackageImpl4( iface );
TRACE( "iface %p, iid %s, out %p.\n", iface, debugstr_guid( iid ), out );
if (IsEqualGUID( iid, &IID_IUnknown ) ||
IsEqualGUID( iid, &IID_IXPackageImpl ) ||
IsEqualGUID( iid, &IID_IXPackageImpl2 ) ||
- IsEqualGUID( iid, &IID_IXPackageImpl3 ))
+ IsEqualGUID( iid, &IID_IXPackageImpl3 ) ||
+ IsEqualGUID( iid, &IID_IXPackageImpl4 ))
{
- IXPackageImpl_AddRef( *out = &impl->IXPackageImpl3_iface );
+ IXPackageImpl_AddRef( *out = &impl->IXPackageImpl4_iface );
return S_OK;
}
@@ -54,248 +56,455 @@ static HRESULT WINAPI x_package_QueryInterface( IXPackageImpl3 *iface, REFIID ii
return E_NOINTERFACE;
}
-static ULONG WINAPI x_package_AddRef( IXPackageImpl3 *iface )
+static ULONG WINAPI x_package_AddRef( IXPackageImpl4 *iface )
{
- struct x_package *impl = impl_from_IXPackageImpl3( iface );
+ struct x_package *impl = impl_from_IXPackageImpl4( iface );
ULONG ref = InterlockedIncrement( &impl->ref );
TRACE( "iface %p increasing refcount to %lu.\n", iface, ref );
return ref;
}
-static ULONG WINAPI x_package_Release( IXPackageImpl3 *iface )
+static ULONG WINAPI x_package_Release( IXPackageImpl4 *iface )
{
- struct x_package *impl = impl_from_IXPackageImpl3( iface );
+ struct x_package *impl = impl_from_IXPackageImpl4( iface );
ULONG ref = InterlockedDecrement( &impl->ref );
TRACE( "iface %p decreasing refcount to %lu.\n", iface, ref );
return ref;
}
-static HRESULT WINAPI x_package_XPackageGetCurrentProcessPackageIdentifier( IXPackageImpl3 *iface, SIZE_T bufferSize, char *buffer )
+/* The package's own identifier, taken from the layout file beside it.
+ *
+ * Every package ships a layout_<guid>.xml at its root, and that guid without
+ * its dashes is the 32 characters a caller asks for here -- titles pass a
+ * bufferSize of 33, which is those characters and a terminator.
+ *
+ * Refusing left the buffer untouched, so titles built monitors for a package
+ * identified as "" and died (the engine's GDKPackageChunkInstall raises a
+ * LowLevelFatalError on this failure).
+ *
+ * The root is not always where the executable is -- Unreal ships its binary
+ * several directories down -- so walk up until the layout turns up, the same
+ * way the game config is found. */
+static HRESULT package_identifier( char *buffer, SIZE_T bufferSize )
{
- FIXME( "iface %p, bufferSize %Iu, buffer %p stub!\n", iface, bufferSize, buffer );
- return E_NOTIMPL;
+ WCHAR path[MAX_PATH];
+ WCHAR *sep;
+
+ if (!GetModuleFileNameW( NULL, path, ARRAY_SIZE(path) )) return E_FAIL;
+ if (!(sep = wcsrchr( path, '\\' ))) return E_FAIL;
+ *sep = 0;
+
+ for (;;)
+ {
+ WCHAR pattern[MAX_PATH];
+ WIN32_FIND_DATAW data;
+ HANDLE find;
+
+ if (wcslen( path ) + ARRAY_SIZE(L"\\layout_*.xml") > ARRAY_SIZE(pattern)) return E_FAIL;
+ wcscpy( pattern, path );
+ wcscat( pattern, L"\\layout_*.xml" );
+
+ if ((find = FindFirstFileW( pattern, &data )) != INVALID_HANDLE_VALUE)
+ {
+ const WCHAR *guid = data.cFileName + ARRAY_SIZE(L"layout_") - 1;
+ SIZE_T used = 0;
+
+ for (; *guid && *guid != '.'; guid++)
+ {
+ if (*guid == '-') continue;
+ if (used + 1 >= bufferSize) { FindClose( find ); return E_NOT_SUFFICIENT_BUFFER; }
+ buffer[used++] = (char)*guid;
+ }
+ buffer[used] = 0;
+ FindClose( find );
+ return used ? S_OK : E_FAIL;
+ }
+
+ if (!(sep = wcsrchr( path, '\\' ))) return E_FAIL;
+ *sep = 0;
+ }
}
-static BOOLEAN WINAPI x_package_XPackageIsPackagedProcess( IXPackageImpl3 *iface )
+static HRESULT WINAPI x_package_XPackageGetCurrentProcessPackageIdentifier( IXPackageImpl4 *iface, SIZE_T bufferSize, char *buffer )
{
- FIXME( "iface %p stub!\n", iface );
- return FALSE;
+ HRESULT hr;
+
+ TRACE( "iface %p, bufferSize %Iu, buffer %p.\n", iface, bufferSize, buffer );
+
+ if (!buffer || !bufferSize) return E_INVALIDARG;
+ if (FAILED(hr = package_identifier( buffer, bufferSize )))
+ FIXME( "no layout file to take a package identifier from: %#lx.\n", hr );
+ return hr;
}
-static HRESULT WINAPI x_package_XPackageCreateInstallationMonitor( IXPackageImpl3 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors, UINT32 minimumUpdateIntervalMs, XTaskQueueHandle queue, XPackageInstallationMonitorHandle *installationMonitor )
+static BOOLEAN WINAPI x_package_XPackageIsPackagedProcess( IXPackageImpl4 *iface )
{
- FIXME( "iface %p, packageIdentifier %s, selectorCount %u, selectors %p, minimumUpdateIntervalMs %u, queue %p, installationMonitor %p stub!\n", iface, debugstr_a( packageIdentifier ), selectorCount, selectors, minimumUpdateIntervalMs, queue, installationMonitor );
- return E_NOTIMPL;
+ TRACE( "iface %p.\n", iface );
+
+ /* Everything reaching this runtime came out of an MSIX package and is run
+ * beside the appxmanifest and MicrosoftGame.config that describe it.
+ * Answering FALSE sends a title down its unpackaged path (Deep Rock
+ * Galactic asked twice and then put up its own crash dialog). */
+ return TRUE;
}
-static void WINAPI x_package_XPackageCloseInstallationMonitorHandle( IXPackageImpl3 *iface, XPackageInstallationMonitorHandle installationMonitor )
+/* A monitor over a title that is already fully installed.
+ *
+ * Xodus extracts a package in full before it can be launched, so there is never
+ * a partial install to watch: every monitor reports complete from the moment it
+ * is made. Refusing to make one is not a soft failure -- a title treats it as
+ * fatal (Deep Rock Galactic put up "Failed to create installation monitor.
+ * 0x80004001" before opening a window). */
+struct installation_monitor
+{
+ UINT64 bytes;
+};
+
+static HRESULT WINAPI x_package_XPackageCreateInstallationMonitor( IXPackageImpl4 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors, UINT32 minimumUpdateIntervalMs, XTaskQueueHandle queue, XPackageInstallationMonitorHandle *installationMonitor )
{
- FIXME( "iface %p, installationMonitor %p stub!\n", iface, installationMonitor );
+ struct installation_monitor *impl;
+
+ TRACE( "iface %p, packageIdentifier %s, selectorCount %u, selectors %p, "
+ "minimumUpdateIntervalMs %u, queue %p, installationMonitor %p.\n",
+ iface, debugstr_a( packageIdentifier ), selectorCount, selectors,
+ minimumUpdateIntervalMs, queue, installationMonitor );
+
+ if (!installationMonitor) return E_INVALIDARG;
+ if (!(impl = calloc( 1, sizeof(*impl) ))) return E_OUTOFMEMORY;
+
+ /* Byte counts are left at zero. They are only there for a progress bar,
+ * and there is no progress to draw: what a title actually reads is
+ * completed and launchable, both of which are true from the start. */
+ *installationMonitor = (XPackageInstallationMonitorHandle)impl;
+ return S_OK;
}
-static void WINAPI x_package_XPackageGetInstallationProgress( IXPackageImpl3 *iface, XPackageInstallationMonitorHandle installationMonitor, XPackageInstallationProgress *progress )
+static void WINAPI x_package_XPackageCloseInstallationMonitorHandle( IXPackageImpl4 *iface, XPackageInstallationMonitorHandle installationMonitor )
{
- FIXME( "iface %p, installationMonitor %p, progress %p stub!\n", iface, installationMonitor, progress );
+ TRACE( "iface %p, installationMonitor %p.\n", iface, installationMonitor );
+ free( installationMonitor );
+}
+
+static void WINAPI x_package_XPackageGetInstallationProgress( IXPackageImpl4 *iface, XPackageInstallationMonitorHandle installationMonitor, XPackageInstallationProgress *progress )
+{
+ struct installation_monitor *impl = (struct installation_monitor *)installationMonitor;
+
+ TRACE( "iface %p, installationMonitor %p, progress %p.\n", iface, installationMonitor, progress );
+
+ if (!progress) return;
+
+ /* Installed in full, and therefore launchable and complete. */
+ progress->totalBytes = impl ? impl->bytes : 0;
+ progress->installedBytes = progress->totalBytes;
+ progress->launchBytes = progress->totalBytes;
+ progress->launchable = TRUE;
+ progress->completed = TRUE;
}
-static BOOLEAN WINAPI x_package_XPackageUpdateInstallationMonitor( IXPackageImpl3 *iface, XPackageInstallationMonitorHandle installationMonitor )
+static BOOLEAN WINAPI x_package_XPackageUpdateInstallationMonitor( IXPackageImpl4 *iface, XPackageInstallationMonitorHandle installationMonitor )
{
FIXME( "iface %p, installationMonitor %p stub!\n", iface, installationMonitor );
return TRUE;
}
-static HRESULT WINAPI x_package_XPackageRegisterInstallationProgressChanged( IXPackageImpl3 *iface, XPackageInstallationMonitorHandle installationMonitor, void *context, XPackageInstallationProgressCallback *callback, XTaskQueueRegistrationToken *token )
+static LONG64 installation_progress_token;
+
+static HRESULT WINAPI x_package_XPackageRegisterInstallationProgressChanged( IXPackageImpl4 *iface, XPackageInstallationMonitorHandle installationMonitor, void *context, XPackageInstallationProgressCallback *callback, XTaskQueueRegistrationToken *token )
{
- FIXME( "iface %p, installationMonitor %p, context %p, callback %p, token %p stub!\n", iface, installationMonitor, context, callback, token );
- return E_NOTIMPL;
+ FIXME( "iface %p, installationMonitor %p, context %p, callback %p, token %p: accepted, "
+ "progress never changes.\n", iface, installationMonitor, context, callback, token );
+
+ if (!token) return E_INVALIDARG;
+
+ /* Nothing will ever be raised -- the package is already complete -- but the
+ * caller still gets a token it can hold and unregister, rather than reading
+ * back whatever was on its stack. */
+ token->token = InterlockedIncrement64( &installation_progress_token );
+ return S_OK;
}
-static BOOLEAN WINAPI x_package_XPackageUnregisterInstallationProgressChanged( IXPackageImpl3 *iface, XPackageInstallationMonitorHandle installationMonitor, XTaskQueueRegistrationToken token, BOOLEAN wait )
+static BOOLEAN WINAPI x_package_XPackageUnregisterInstallationProgressChanged( IXPackageImpl4 *iface, XPackageInstallationMonitorHandle installationMonitor, XTaskQueueRegistrationToken token, BOOLEAN wait )
{
FIXME( "iface %p, installationMonitor %p, token %p, wait %d stub!\n", iface, installationMonitor, &token, wait );
return TRUE;
}
-static HRESULT WINAPI x_package_XPackageGetUserLocale( IXPackageImpl3 *iface, SIZE_T localeSize, char *locale )
+static HRESULT WINAPI x_package_XPackageGetUserLocale( IXPackageImpl4 *iface, SIZE_T localeSize, char *locale )
{
- FIXME( "iface %p, localeSize %Iu, locale %p stub!\n", iface, localeSize, locale );
- return E_NOTIMPL;
+ char requested[LOCALE_NAME_MAX_LENGTH];
+ WCHAR user_locale[LOCALE_NAME_MAX_LENGTH];
+ DWORD length;
+ INT converted;
+
+ TRACE( "iface %p, localeSize %Iu, locale %p.\n", iface, localeSize, locale );
+ if (!locale || !localeSize) return E_INVALIDARG;
+
+ /* The launcher selects a locale declared by the installed package. */
+ length = GetEnvironmentVariableA( "XODUS_PACKAGE_LOCALE", requested, sizeof(requested) );
+ if (length >= sizeof(requested)) return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+ if (length)
+ {
+ if (length + 1 > localeSize) return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+ memcpy( locale, requested, length + 1 );
+ return S_OK;
+ }
+
+ if (!GetUserDefaultLocaleName( user_locale, ARRAY_SIZE(user_locale) ))
+ return HRESULT_FROM_WIN32( GetLastError() );
+ converted = WideCharToMultiByte( CP_UTF8, 0, user_locale, -1, NULL, 0, NULL, NULL );
+ if (!converted) return HRESULT_FROM_WIN32( GetLastError() );
+ if ((SIZE_T)converted > localeSize) return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+ if (!WideCharToMultiByte( CP_UTF8, 0, user_locale, -1, locale, converted, NULL, NULL ))
+ return HRESULT_FROM_WIN32( GetLastError() );
+ return S_OK;
}
-static HRESULT WINAPI x_package_XPackageFindChunkAvailability( IXPackageImpl3 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors, XPackageChunkAvailability *availability )
+/* Everything a title can ask about is already on disk.
+ *
+ * Chunks are how a package is installed in pieces, so a title can start before
+ * the rest arrives and wait on what it still needs. Xodus extracts a package in
+ * full before it can be launched, so every chunk is Ready and always was.
+ * Refusing to say so leaves a title waiting for content that is already there:
+ * Resident Evil 2 plays its publisher logos and then sits on a black screen. */
+static HRESULT WINAPI x_package_XPackageFindChunkAvailability( IXPackageImpl4 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors, XPackageChunkAvailability *availability )
{
- FIXME( "iface %p, packageIdentifier %s, selectorCount %u, selectors %p, availability %p stub!\n", iface, packageIdentifier, selectorCount, selectors, availability );
- return E_NOTIMPL;
+ TRACE( "iface %p, packageIdentifier %s, selectorCount %u, selectors %p, availability %p.\n",
+ iface, debugstr_a( packageIdentifier ), selectorCount, selectors, availability );
+
+ if (!availability) return E_INVALIDARG;
+ *availability = XPackageChunkAvailability_Ready;
+ return S_OK;
}
-static HRESULT WINAPI x_package_XPackageEnumerateChunkAvailability( IXPackageImpl3 *iface, const char *packageIdentifier, XPackageChunkSelectorType type, void *context, XPackageChunkAvailabilityCallback *callback )
+static HRESULT WINAPI x_package_XPackageEnumerateChunkAvailability( IXPackageImpl4 *iface, const char *packageIdentifier, XPackageChunkSelectorType type, void *context, XPackageChunkAvailabilityCallback *callback )
{
- FIXME( "iface %p, packageIdentifier %s, type %d, context %p, callback %p stub!\n", iface, debugstr_a( packageIdentifier ), type, context, callback );
- return E_NOTIMPL;
+ TRACE( "iface %p, packageIdentifier %s, type %d, context %p, callback %p.\n",
+ iface, debugstr_a( packageIdentifier ), type, context, callback );
+
+ if (!callback) return E_INVALIDARG;
+
+ /* A package installed in one piece has no chunks to enumerate, and an
+ * enumeration that visits nothing is the true answer rather than a
+ * failure. What a title actually waits on is the availability above. */
+ return S_OK;
}
-static HRESULT WINAPI x_package_XPackageChangeChunkInstallOrder( IXPackageImpl3 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors )
+static HRESULT WINAPI x_package_XPackageChangeChunkInstallOrder( IXPackageImpl4 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors )
{
FIXME( "iface %p, packageIdentifier %s, selectorCount %u, selectors %p stub!\n", iface, debugstr_a( packageIdentifier ), selectorCount, selectors );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageInstallChunks( IXPackageImpl3 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors, UINT32 minimumUpdateIntervalMs, BOOLEAN suppressUserConfirmation, XTaskQueueHandle queue, XPackageInstallationMonitorHandle *installationMonitor )
+static HRESULT WINAPI x_package_XPackageInstallChunks( IXPackageImpl4 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors, UINT32 minimumUpdateIntervalMs, BOOLEAN suppressUserConfirmation, XTaskQueueHandle queue, XPackageInstallationMonitorHandle *installationMonitor )
{
FIXME( "iface %p, packageIdentifier %s, selectorCount %u, selectors %p, minimumUpdateIntervalMs %u, suppressUserConfirmation %d, queue %p, installationMonitor %p stub!\n", iface, debugstr_a( packageIdentifier ), selectorCount, selectors, minimumUpdateIntervalMs, suppressUserConfirmation, queue, installationMonitor );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageInstallChunksAsync( IXPackageImpl3 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors, UINT32 minimumUpdateIntervalMs, BOOLEAN suppressUserConfirmation, XAsyncBlock *asyncBlock )
+static HRESULT WINAPI x_package_XPackageInstallChunksAsync( IXPackageImpl4 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors, UINT32 minimumUpdateIntervalMs, BOOLEAN suppressUserConfirmation, XAsyncBlock *asyncBlock )
{
FIXME( "iface %p, packageIdentifier %s, selectorCount %u, selectors %p, minimumUpdateIntervalMs %u, suppressUserConfirmation %d, asyncBlock %p stub!\n", iface, packageIdentifier, selectorCount, selectors, minimumUpdateIntervalMs, suppressUserConfirmation, asyncBlock );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageInstallChunksResult( IXPackageImpl3 *iface, XAsyncBlock *asyncBlock, XPackageInstallationMonitorHandle *installationMonitor )
+static HRESULT WINAPI x_package_XPackageInstallChunksResult( IXPackageImpl4 *iface, XAsyncBlock *asyncBlock, XPackageInstallationMonitorHandle *installationMonitor )
{
FIXME( "iface %p, asyncBlock %p, installationMonitor %p stub!\n", iface, asyncBlock, installationMonitor );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageEstimateDownloadSize( IXPackageImpl3 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors, UINT64 *downloadSize, BOOLEAN *shouldPresentUserConfirmation )
+static HRESULT WINAPI x_package_XPackageEstimateDownloadSize( IXPackageImpl4 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors, UINT64 *downloadSize, BOOLEAN *shouldPresentUserConfirmation )
{
FIXME( "iface %p, packageIdentifier %s, selectorCount %u, selectors %p, downloadSize %p, shouldPresentUserConfirmation %p stub!\n", iface, packageIdentifier, selectorCount, selectors, downloadSize, shouldPresentUserConfirmation );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageUninstallChunks( IXPackageImpl3 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors )
+static HRESULT WINAPI x_package_XPackageUninstallChunks( IXPackageImpl4 *iface, const char *packageIdentifier, UINT32 selectorCount, XPackageChunkSelector *selectors )
{
FIXME( "iface %p, packageIdentifier %s, selectorCount %u, selectores %p stub!\n", iface, packageIdentifier, selectorCount, selectors );
return E_NOTIMPL;
}
-static HRESULT WINAPI __PADDING__( IXPackageImpl3 *iface )
+static HRESULT WINAPI __PADDING__( IXPackageImpl4 *iface )
{
WARN( "iface %p padding function called! It's unknown what this function does.\n", iface );
return E_NOTIMPL;
}
-static HRESULT WINAPI __PADDING_2__( IXPackageImpl3 *iface )
+static HRESULT WINAPI __PADDING_2__( IXPackageImpl4 *iface )
{
WARN( "iface %p padding function called! It's unknown what this function does.\n", iface );
return E_NOTIMPL;
}
-static BOOLEAN WINAPI x_package_XPackageUnregisterPackageInstalled( IXPackageImpl3 *iface, XTaskQueueRegistrationToken token, BOOLEAN wait )
+static BOOLEAN WINAPI x_package_XPackageUnregisterPackageInstalled( IXPackageImpl4 *iface, XTaskQueueRegistrationToken token, BOOLEAN wait )
{
FIXME( "iface %p, token %p, wait %d stub!\n", iface, &token, wait );
return TRUE;
}
-static HRESULT WINAPI __PADDING_3__( IXPackageImpl3 *iface )
+static HRESULT WINAPI __PADDING_3__( IXPackageImpl4 *iface )
{
WARN( "iface %p padding function called! It's unknown what this function does.\n", iface );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageGetMountPathSize( IXPackageImpl3 *iface, XPackageMountHandle mount, SIZE_T *pathSize )
+static HRESULT WINAPI x_package_XPackageGetMountPathSize( IXPackageImpl4 *iface, XPackageMountHandle mount, SIZE_T *pathSize )
{
FIXME( "iface %p, mount %p, pathSize %p stub!\n", iface, mount, pathSize );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageGetMountPath( IXPackageImpl3 *iface, XPackageMountHandle mount, SIZE_T pathSize, char *path )
+static HRESULT WINAPI x_package_XPackageGetMountPath( IXPackageImpl4 *iface, XPackageMountHandle mount, SIZE_T pathSize, char *path )
{
FIXME( "iface %p, mount %p, pathSize %Iu, path %p stub!\n", iface, mount, pathSize, path );
return E_NOTIMPL;
}
-static void WINAPI x_package_XPackageCloseMountHandle( IXPackageImpl3 *iface, XPackageMountHandle mount )
+static void WINAPI x_package_XPackageCloseMountHandle( IXPackageImpl4 *iface, XPackageMountHandle mount )
{
FIXME( "iface %p, mount %p stub!\n", iface, mount );
}
-static HRESULT WINAPI __PADDING_4__( IXPackageImpl3 *iface )
+static HRESULT WINAPI __PADDING_4__( IXPackageImpl4 *iface )
{
WARN( "iface %p padding function called! It's unknown what this function does.\n", iface );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageEnumeratePackages( IXPackageImpl3 *iface, XPackageKind kind, XPackageEnumerationScope scope, void *context, XPackageEnumerationCallback *callback )
+/* The one package this process runs from: Xodus extracts a single MSIX
+ * package in full, so an enumeration either visits that package (when the
+ * caller asks for its kind) or visits nothing. Fields we have no data for
+ * are empty rather than invented; installing is FALSE because there is
+ * nothing left to install. */
+static HRESULT enumerate_current_package( XPackageKind kind, XPackageEnumerationScope scope, void *context, XPackageEnumerationCallback *callback )
{
- FIXME( "iface %p, kind %d, scope %d, context %p, callback %p stub!\n", iface, kind, scope, context, callback );
- return E_NOTIMPL;
+ char identifier[33]; /* 32 characters and a terminator, as titles ask for. */
+ XPackageDetails details;
+ HRESULT hr;
+
+ if (!callback) return E_INVALIDARG;
+ if (kind != XPackageKind_Game) return S_OK;
+ if (FAILED(hr = package_identifier( identifier, sizeof(identifier) ))) return hr;
+
+ memset( &details, 0, sizeof(details) );
+ details.packageIdentifier = identifier;
+ details.kind = XPackageKind_Game;
+ details.installing = FALSE;
+ details.index = 0;
+ details.count = 1;
+ callback( context, &details );
+ return S_OK;
+}
+
+static HRESULT WINAPI x_package_XPackageEnumeratePackages( IXPackageImpl4 *iface, XPackageKind kind, XPackageEnumerationScope scope, void *context, XPackageEnumerationCallback *callback )
+{
+ TRACE( "iface %p, kind %d, scope %d, context %p, callback %p.\n", iface, kind, scope, context, callback );
+ return enumerate_current_package( kind, scope, context, callback );
}
-static HRESULT WINAPI x_package_XPackageRegisterPackageInstalled( IXPackageImpl3 *iface, XTaskQueueHandle queue, void *context, XPackageInstalledCallback *callback, XTaskQueueRegistrationToken *token )
+static HRESULT WINAPI x_package_XPackageRegisterPackageInstalled( IXPackageImpl4 *iface, XTaskQueueHandle queue, void *context, XPackageInstalledCallback *callback, XTaskQueueRegistrationToken *token )
{
FIXME( "iface %p, queue %p, context %p, callback %p, token %p stub!\n", iface, queue, context, callback, token );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageGetWriteStats( IXPackageImpl3 *iface, XPackageWriteStats *writeStats )
+static HRESULT WINAPI x_package_XPackageGetWriteStats( IXPackageImpl4 *iface, XPackageWriteStats *writeStats )
{
FIXME( "iface %p, writeStats %p stub!\n", iface, writeStats );
return E_NOTIMPL;
}
-static HRESULT WINAPI __PADDING_5__( IXPackageImpl3 *iface )
+static HRESULT WINAPI __PADDING_5__( IXPackageImpl4 *iface )
{
WARN( "iface %p padding function called! It's unknown what this function does.\n", iface );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageUninstallUWPInstance( IXPackageImpl3 *iface, const char *packageName )
+static HRESULT WINAPI x_package_XPackageUninstallUWPInstance( IXPackageImpl4 *iface, const char *packageName )
{
FIXME( "iface %p, packageName %s stub!\n", iface, debugstr_a( packageName ) );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageEnumerateFeatures( IXPackageImpl3 *iface, const char *packageIdentifier, void *context, XPackageFeatureEnumerationCallback *callback )
+static HRESULT WINAPI x_package_XPackageEnumerateFeatures( IXPackageImpl4 *iface, const char *packageIdentifier, void *context, XPackageFeatureEnumerationCallback *callback )
{
- FIXME( "iface %p, packageIdentifier %s, context %p, callback %p stub!\n", iface, packageIdentifier, context, callback );
- return E_NOTIMPL;
+ TRACE( "iface %p, packageIdentifier %s, context %p, callback %p.\n",
+ iface, debugstr_a( packageIdentifier ), context, callback );
+
+ if (!callback) return E_INVALIDARG;
+
+ /* Optional features are declared in MicrosoftGame.config, and nothing
+ * installed here declares any: an enumeration that visits nothing is the
+ * true answer, not a failure. Refusing was enough to end Deep Rock
+ * Galactic, which put up a crash dialog carrying no message at all. */
+ return S_OK;
}
-static BOOLEAN WINAPI x_package_XPackageUninstallPackage( IXPackageImpl3 *iface, const char *packageIdentifier )
+static BOOLEAN WINAPI x_package_XPackageUninstallPackage( IXPackageImpl4 *iface, const char *packageIdentifier )
{
FIXME( "iface %p, packageIdentifier %s", iface, debugstr_a( packageIdentifier ) );
return FALSE;
}
-static HRESULT WINAPI x_package_XPackageEnumeratePackages2( IXPackageImpl3 *iface, XPackageKind kind, XPackageEnumerationScope scope, void *context, XPackageEnumerationCallback *callback )
+static HRESULT WINAPI x_package_XPackageEnumeratePackages2( IXPackageImpl4 *iface, XPackageKind kind, XPackageEnumerationScope scope, void *context, XPackageEnumerationCallback *callback )
{
- FIXME( "iface %p, kind %d, scope %d, context %p, callback %p stub!\n", iface, kind, scope, context, callback );
- return E_NOTIMPL;
+ TRACE( "iface %p, kind %d, scope %d, context %p, callback %p.\n", iface, kind, scope, context, callback );
+ return enumerate_current_package( kind, scope, context, callback );
}
-static HRESULT WINAPI x_package_XPackageRegisterPackageInstalled2( IXPackageImpl3 *iface, XTaskQueueHandle queue, void *context, XPackageInstalledCallback *callback, XTaskQueueRegistrationToken *token )
+static HRESULT WINAPI x_package_XPackageRegisterPackageInstalled2( IXPackageImpl4 *iface, XTaskQueueHandle queue, void *context, XPackageInstalledCallback *callback, XTaskQueueRegistrationToken *token )
{
FIXME( "iface %p, queue %p, context %p, callback %p, token %p stub!\n", iface, queue, context, callback, token );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageMountWithUiAsync( IXPackageImpl3 *iface, const char *packageIdentifier, XAsyncBlock *async )
+static HRESULT WINAPI x_package_XPackageMountWithUiAsync( IXPackageImpl4 *iface, const char *packageIdentifier, XAsyncBlock *async )
{
FIXME( "iface %p, packageIdentifier %s, async %p stub!\n", iface, debugstr_a( packageIdentifier ), async );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageMountWithUiResult( IXPackageImpl3 *iface, XAsyncBlock *async, XPackageMountHandle *mount )
+static HRESULT WINAPI x_package_XPackageMountWithUiResult( IXPackageImpl4 *iface, XAsyncBlock *async, XPackageMountHandle *mount )
{
FIXME( "iface %p, async %p, mount %p stub!\n", iface, async, mount );
return E_NOTIMPL;
}
-static HRESULT WINAPI x_package_XPackageEnumeratePackages3( IXPackageImpl3 *iface, XPackageKind kind, XPackageEnumerationScope scope, void *context, XPackageEnumerationCallback *callback )
+static HRESULT WINAPI x_package_XPackageEnumeratePackages3( IXPackageImpl4 *iface, XPackageKind kind, XPackageEnumerationScope scope, void *context, XPackageEnumerationCallback *callback )
{
- FIXME( "iface %p, kind %d, scope %d, context %p, callback %p stub!\n", iface, kind, scope, context, callback );
- return E_NOTIMPL;
+ TRACE( "iface %p, kind %d, scope %d, context %p, callback %p.\n", iface, kind, scope, context, callback );
+ return enumerate_current_package( kind, scope, context, callback );
}
-static HRESULT WINAPI x_package_XPackageRegisterPackageInstalled3( IXPackageImpl3 *iface, XTaskQueueHandle queue, void *context, XPackageInstalledCallback *callback, XTaskQueueRegistrationToken *token )
+static LONG64 package_installed_token;
+
+static HRESULT WINAPI x_package_XPackageRegisterPackageInstalled3( IXPackageImpl4 *iface, XTaskQueueHandle queue, void *context, XPackageInstalledCallback *callback, XTaskQueueRegistrationToken *token )
{
- FIXME( "iface %p, queue %p, context %p, callback %p, token %p stub!\n", iface, queue, context, callback, token );
- return E_NOTIMPL;
+ FIXME( "iface %p, queue %p, context %p, callback %p, token %p: accepted, nothing will be raised -- "
+ "packages are fully installed before they can run.\n", iface, queue, context, callback, token );
+
+ if (!token) return E_INVALIDARG;
+
+ token->token = InterlockedIncrement64( &package_installed_token );
+ return S_OK;
+}
+
+static HRESULT WINAPI x_package_XPackageGetPackageKind( IXPackageImpl4 *iface, const char *packageIdentifier, XPackageKind *kind )
+{
+ TRACE( "iface %p, packageIdentifier %s, kind %p.\n", iface, debugstr_a( packageIdentifier ), kind );
+
+ if (!packageIdentifier || !kind) return E_INVALIDARG;
+
+ /* This runtime only ever runs game packages extracted by Xodus; there is
+ * no package database that could honestly answer for related content or
+ * publisher packages, so the kind of the package a title asks about --
+ * in every observed call its own -- is Game. */
+ *kind = XPackageKind_Game;
+ return S_OK;
}
-static const struct IXPackageImpl3Vtbl x_package_vtbl =
+static const struct IXPackageImpl4Vtbl x_package_vtbl =
{
x_package_QueryInterface,
x_package_AddRef,
@@ -341,6 +550,8 @@ static const struct IXPackageImpl3Vtbl x_package_vtbl =
/* IXPackageImpl3 methods */
x_package_XPackageEnumeratePackages3,
x_package_XPackageRegisterPackageInstalled3,
+ /* IXPackageImpl4 methods */
+ x_package_XPackageGetPackageKind,
};
static struct x_package x_package =
@@ -349,4 +560,4 @@ static struct x_package x_package =
0,
};
-IXPackageImpl *x_package_impl = (IXPackageImpl *)&x_package.IXPackageImpl3_iface;
+IXPackageImpl *x_package_impl = (IXPackageImpl *)&x_package.IXPackageImpl4_iface;
diff --git a/dlls/xgameruntime/xpackage.idl b/dlls/xgameruntime/xpackage.idl
index d77bbbb..3aef28d 100644
--- a/dlls/xgameruntime/xpackage.idl
+++ b/dlls/xgameruntime/xpackage.idl
@@ -51,6 +51,7 @@ cpp_quote("enum class XPackageKind : UINT32")
cpp_quote("{ ")
cpp_quote(" Game, ")
cpp_quote(" Content, ")
+cpp_quote(" PublisherContent, ")
cpp_quote("}; ")
cpp_quote("#elif defined(__WINESRC__)")
@@ -82,6 +83,7 @@ typedef enum XPackageKind
{
XPackageKind_Game,
XPackageKind_Content,
+ XPackageKind_PublisherContent,
} XPackageKind;
cpp_quote("#endif")
@@ -223,12 +225,22 @@ interface IXPackageImpl3 : IXPackageImpl2
HRESULT XPackageRegisterPackageInstalled( [in] XTaskQueueHandle queue, [in, optional] void *context, [in] XPackageInstalledCallback *callback, [out] XTaskQueueRegistrationToken *token );
}
+[
+ local,
+ object,
+ uuid(0b9d556e-ab70-43f4-baa0-9999ac4cb040)
+]
+interface IXPackageImpl4 : IXPackageImpl3
+{
+ HRESULT XPackageGetKind( [in, string] const char *packageIdentifier, [out] XPackageKind *kind );
+}
+
[
uuid(af406016-e850-4aa8-a88d-2f3dcb9dac7e)
]
coclass XPackageImpl
{
- [default] interface IXPackageImpl3;
+ [default] interface IXPackageImpl4;
}
cpp_quote("#endif")
diff --git a/dlls/xgameruntime/xpersistentlocalstorage.c b/dlls/xgameruntime/xpersistentlocalstorage.c
index 3583366..46e7cd0 100644
--- a/dlls/xgameruntime/xpersistentlocalstorage.c
+++ b/dlls/xgameruntime/xpersistentlocalstorage.c
@@ -70,22 +70,61 @@ static ULONG WINAPI x_persistent_local_storage_Release( IXPersistentLocalStorage
return ref;
}
+static void get_storage_path( char *path, SIZE_T size )
+{
+ char localAppData[MAX_PATH], name[16];
+
+ if (!GetEnvironmentVariableA( "LOCALAPPDATA", localAppData, sizeof(localAppData) )) strcpy( localAppData, "C:\\users\\Public\\AppData\\Local" );
+ snprintf( name, sizeof(name), "%08X", titleId );
+ snprintf( path, size, "%s\\XodusPersistentLocalStorage", localAppData );
+ CreateDirectoryA( path, NULL );
+ snprintf( path, size, "%s\\XodusPersistentLocalStorage\\%s", localAppData, packageFamilyName ? packageFamilyName : name );
+ CreateDirectoryA( path, NULL );
+}
+
static HRESULT WINAPI x_persistent_local_storage_XPersistentLocalStorageGetPath( IXPersistentLocalStorageImpl3 *iface, SIZE_T pathSize, char *path, SIZE_T *pathUsed )
{
- FIXME( "iface %p, pathSize %Iu, path %p, pathUsed %p stub!\n", iface, pathSize, path, pathUsed );
- return E_NOTIMPL;
+ char buffer[MAX_PATH];
+ SIZE_T len;
+
+ TRACE( "iface %p, pathSize %Iu, path %p, pathUsed %p.\n", iface, pathSize, path, pathUsed );
+
+ if (!path) return E_POINTER;
+ get_storage_path( buffer, sizeof(buffer) );
+ len = strlen( buffer ) + 1;
+ if (pathSize < len) return E_NOT_SUFFICIENT_BUFFER;
+ memcpy( path, buffer, len );
+ if (pathUsed) *pathUsed = len;
+ return S_OK;
}
static HRESULT WINAPI x_persistent_local_storage_XPersistentLocalStorageGetPathSize( IXPersistentLocalStorageImpl3 *iface, SIZE_T *pathSize )
{
- FIXME( "iface %p, pathSize %p stub!\n", iface, pathSize );
- return E_NOTIMPL;
+ char buffer[MAX_PATH];
+
+ TRACE( "iface %p, pathSize %p.\n", iface, pathSize );
+
+ if (!pathSize) return E_POINTER;
+ get_storage_path( buffer, sizeof(buffer) );
+ *pathSize = strlen( buffer ) + 1;
+ return S_OK;
}
static HRESULT WINAPI x_persistent_local_storage_XPersistentLocalStorageGetSpaceInfo( IXPersistentLocalStorageImpl3 *iface, XPersistentLocalStorageSpaceInfo *info )
{
- FIXME( "iface %p, info %p stub!\n", iface, info );
- return E_NOTIMPL;
+ ULARGE_INTEGER available, total, free;
+ char buffer[MAX_PATH];
+
+ TRACE( "iface %p, info %p.\n", iface, info );
+
+ if (!info) return E_POINTER;
+ get_storage_path( buffer, sizeof(buffer) );
+ if (!GetDiskFreeSpaceExA( buffer, &available, &total, &free )) return HRESULT_FROM_WIN32( GetLastError() );
+ info->availableFreeBytes = available.QuadPart;
+ info->totalFreeBytes = free.QuadPart;
+ info->usedBytes = 0;
+ info->totalBytes = total.QuadPart;
+ return S_OK;
}
static HRESULT WINAPI x_persistent_local_storage_XPersistentLocalStorageMountForPackage( IXPersistentLocalStorageImpl3 *iface, const char *packageIdentifier, XPackageMountHandle *mountHandle )
diff --git a/dlls/xgameruntime/xstore.c b/dlls/xgameruntime/xstore.c
index 982dd97..a5e21f4 100644
--- a/dlls/xgameruntime/xstore.c
+++ b/dlls/xgameruntime/xstore.c
@@ -75,13 +75,16 @@ static ULONG WINAPI x_store_Release( IXStoreImpl6 *iface )
static HRESULT WINAPI x_store_XStoreCreateContext( IXStoreImpl6 *iface, const XUserHandle user, XStoreContextHandle *storeContextHandle )
{
- FIXME( "iface %p, user %p, storeContextHandle %p stub!\n", iface, user, storeContextHandle );
- return E_NOTIMPL;
+ TRACE( "iface %p, user %p, storeContextHandle %p.\n", iface, user, storeContextHandle );
+ if (!storeContextHandle) return E_POINTER;
+ if (!(*storeContextHandle = calloc( 1, sizeof(LONG) ))) return E_OUTOFMEMORY;
+ return S_OK;
}
static void WINAPI x_store_XStoreCloseContextHandle( IXStoreImpl6 *iface, XStoreContextHandle storeContextHandle )
{
- FIXME( "iface %p, storeContextHandle %p stub!\n", iface, storeContextHandle );
+ TRACE( "iface %p, storeContextHandle %p.\n", iface, storeContextHandle );
+ free( storeContextHandle );
}
static HRESULT WINAPI x_store_XStoreQueryAssociatedProductsAsync( IXStoreImpl6 *iface, const XStoreContextHandle storeContextHandle, XStoreProductKind productKinds, UINT32 maxItemsToRetrievePerPage, XAsyncBlock *async )
@@ -220,16 +223,69 @@ static HRESULT WINAPI x_store_XStoreCanAcquireLicenseForPackageResult( IXStoreIm
return E_NOTIMPL;
}
+static HRESULT WINAPI XStoreQueryGameLicenseProvider( XAsyncOp op, const XAsyncProviderData *data )
+{
+ XStoreGameLicense *license;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "op %d, data %p.\n", op, data );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+
+ switch (op)
+ {
+ case XAsyncOp_Begin:
+ hr = IXThreadingImpl_XAsyncSchedule( xthreading, data->async, 0 );
+ break;
+
+ case XAsyncOp_DoWork:
+ IXThreadingImpl_XAsyncComplete( xthreading, data->async, S_OK, sizeof(XStoreGameLicense) );
+ break;
+
+ case XAsyncOp_GetResult:
+ license = data->buffer;
+ memset( license, 0, sizeof(*license) );
+ if (storeId) snprintf( license->skuStoreId, sizeof(license->skuStoreId), "%s/0010", storeId );
+ license->isActive = TRUE;
+ license->expirationDate = 4102444800;
+ break;
+
+ case XAsyncOp_Cleanup:
+ case XAsyncOp_Cancel:
+ break;
+ }
+
+ IXThreadingImpl_Release( xthreading );
+ return hr;
+}
+
static HRESULT WINAPI x_store_XStoreQueryGameLicenseAsync( IXStoreImpl6 *iface, const XStoreContextHandle storeContextHandle, XAsyncBlock *async )
{
- FIXME( "iface %p, storeContextHandle %p, async %p stub!\n", iface, storeContextHandle, async );
- return E_NOTIMPL;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "iface %p, storeContextHandle %p, async %p, storeId %s.\n", iface, storeContextHandle, async, debugstr_a( storeId ) );
+
+ if (!storeContextHandle || !async) return E_INVALIDARG;
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ hr = IXThreadingImpl_XAsyncBegin( xthreading, async, NULL, x_store_XStoreQueryGameLicenseAsync, "XStoreQueryGameLicenseAsync", XStoreQueryGameLicenseProvider );
+ IXThreadingImpl_Release( xthreading );
+ return hr;
}
static HRESULT WINAPI x_store_XStoreQueryGameLicenseResult( IXStoreImpl6 *iface, XAsyncBlock *async, XStoreGameLicense *license )
{
- FIXME( "iface %p, async %p, license %p stub!\n", iface, async, license );
- return E_NOTIMPL;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "iface %p, async %p, license %p.\n", iface, async, license );
+
+ if (!async || !license) return E_INVALIDARG;
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResult( xthreading, async, x_store_XStoreQueryGameLicenseAsync, sizeof(*license), license, NULL );
+ IXThreadingImpl_Release( xthreading );
+ return hr;
}
static HRESULT WINAPI x_store_XStoreQueryAddOnLicensesAsync( IXStoreImpl6 *iface, const XStoreContextHandle storeContextHandle, XAsyncBlock *async )
@@ -310,22 +366,100 @@ static HRESULT WINAPI x_store_XStoreGetUserPurchaseIdResult( IXStoreImpl6 *iface
return E_NOTIMPL;
}
+struct store_license_context
+{
+ char *request, *token;
+ SIZE_T size;
+};
+static const char store_license_identity;
+
+static HRESULT WINAPI store_license_provider( XAsyncOp op, const XAsyncProviderData *data )
+{
+ struct store_license_context *context = data->context;
+ IXThreadingImpl *threading;
+ HRESULT hr;
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&threading ))) return hr;
+ switch (op)
+ {
+ case XAsyncOp_Begin:
+ hr = IXThreadingImpl_XAsyncSchedule( threading, data->async, 0 );
+ break;
+ case XAsyncOp_DoWork:
+ hr = xodus_store_license_xml( context->request, strlen(context->request), &context->token );
+ if (SUCCEEDED(hr)) context->size = strlen(context->token) + 1;
+ /* Completion may synchronously consume/free context. */
+ IXThreadingImpl_XAsyncComplete( threading, data->async, hr, SUCCEEDED(hr) ? context->size : 0 );
+ hr = S_OK;
+ break;
+ case XAsyncOp_GetResult:
+ if (!data->buffer || data->bufferSize < context->size) hr = HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+ else { memcpy( data->buffer, context->token, context->size ); hr = S_OK; }
+ break;
+ case XAsyncOp_Cleanup:
+ if (context->token) { SecureZeroMemory( context->token, context->size ); free(context->token); }
+ free(context->request);
+ free(context);
+ hr = S_OK;
+ break;
+ case XAsyncOp_Cancel:
+ hr = S_OK;
+ break;
+ default:
+ hr = E_NOTIMPL;
+ }
+ IXThreadingImpl_Release( threading );
+ return hr;
+}
+
static HRESULT WINAPI x_store_XStoreQueryLicenseTokenAsync( IXStoreImpl6 *iface, const XStoreContextHandle storeContextHandle, const char **productIds, SIZE_T productIdsCount, const char *customDeveloperString, XAsyncBlock *async )
{
- FIXME( "iface %p, storeContextHandle %p, productIdsCount %p, idsCount %Iu, custom %s, async %p stub!\n", iface, storeContextHandle, productIds, productIdsCount, debugstr_a( customDeveloperString ), async );
- return E_NOTIMPL;
+ struct store_license_context *context;
+ IXThreadingImpl *threading;
+ HRESULT hr;
+ SIZE_T i;
+
+ TRACE( "iface %p, storeContextHandle %p, idsCount %Iu, async %p.\n", iface, storeContextHandle, productIdsCount, async );
+ if (!storeContextHandle || !async || !productIds || !productIdsCount ||
+ productIdsCount > 64 || !customDeveloperString || !*customDeveloperString) return E_INVALIDARG;
+ for (i = 0; i < productIdsCount; i++) if (!productIds[i] || !*productIds[i]) return E_INVALIDARG;
+ if (!(context = calloc( 1, sizeof(*context) ))) return E_OUTOFMEMORY;
+ hr = xodus_store_license_body( productIds, productIdsCount, customDeveloperString, &context->request );
+ if (FAILED(hr)) goto error;
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&threading ))) goto error;
+ hr = IXThreadingImpl_XAsyncBegin( threading, async, context, &store_license_identity,
+ "XStoreQueryLicenseTokenAsync", store_license_provider );
+ xodus_store_license_note( "store-license-begin", hr );
+ IXThreadingImpl_Release( threading );
+ if (SUCCEEDED(hr)) return hr;
+error:
+ free(context->request);
+ free(context);
+ return hr;
}
static HRESULT WINAPI x_store_XStoreQueryLicenseTokenResultSize( IXStoreImpl6 *iface, XAsyncBlock *async, SIZE_T *size )
{
- FIXME( "iface %p, async %p, size %p stub!\n", iface, async, size );
- return E_NOTIMPL;
+ IXThreadingImpl *threading;
+ HRESULT hr;
+ if (!async || !size) return E_INVALIDARG;
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&threading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResultSize( threading, async, size );
+ xodus_store_license_note( "store-license-size", hr );
+ IXThreadingImpl_Release( threading );
+ return hr;
}
static HRESULT WINAPI x_store_XStoreQueryLicenseTokenResult( IXStoreImpl6 *iface, XAsyncBlock *async, SIZE_T size, char *result )
{
- FIXME( "iface %p, async %p, size %Iu, result %p stub!\n", iface, async, size, result );
- return E_NOTIMPL;
+ IXThreadingImpl *threading;
+ HRESULT hr;
+ if (!async || !result) return E_INVALIDARG;
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&threading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResult( threading, async, &store_license_identity, size, result, NULL );
+ xodus_store_license_note( "store-license-result", hr );
+ IXThreadingImpl_Release( threading );
+ return hr;
}
static HRESULT WINAPI __PADDING__( IXStoreImpl6 *iface )
diff --git a/dlls/xgameruntime/xsystem.c b/dlls/xgameruntime/xsystem.c
index 9634846..73c9330 100644
--- a/dlls/xgameruntime/xsystem.c
+++ b/dlls/xgameruntime/xsystem.c
@@ -101,14 +101,14 @@ static HRESULT WINAPI x_system_XSystemGetXboxLiveSandboxId( IXSystemImpl5 *iface
TRACE( "iface %p, sandboxIdSize %d, sandboxId %p, sandboxIdUsed %p\n", iface, sandboxIdSize, sandboxId, sandboxIdUsed );
- if (!sandboxId || !sandboxIdUsed)
+ if (!sandboxId)
return E_POINTER;
if (sandboxIdSize < XSystemXboxLiveSandboxIdMaxBytes)
return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
strcpy_s( sandboxId, sandboxIdSize, Id );
- *sandboxIdUsed = strlen( Id ) + 1;
+ if (sandboxIdUsed) *sandboxIdUsed = strlen( Id ) + 1;
return S_OK;
}
diff --git a/dlls/xgameruntime/xsystemanalytics.c b/dlls/xgameruntime/xsystemanalytics.c
index dd8066f..dfc5ef1 100644
--- a/dlls/xgameruntime/xsystemanalytics.c
+++ b/dlls/xgameruntime/xsystemanalytics.c
@@ -20,6 +20,7 @@
*/
#include "private.h"
+#include "winternl.h"
WINE_DEFAULT_DEBUG_CHANNEL(gdkc);
@@ -70,105 +71,28 @@ static ULONG WINAPI x_system_analytics_Release( IXSystemAnalyticsImpl *iface )
static XSystemAnalyticsInfo* WINAPI x_system_analytics_XSystemGetAnalyticsInfo( IXSystemAnalyticsImpl *iface, XSystemAnalyticsInfo *__ret )
{
- /* For Windows, XSystemAnalyticsInfo->form is always "Desktop" */
- const WCHAR *analytics_info_str = RuntimeClass_Windows_System_Profile_AnalyticsInfo;
- HSTRING analytics_info_class, deviceFamilyVersion, deviceFamily;
- const WCHAR *deviceFamilyVersionStr, *deviceFamilyStr;
+ /* The WinRT Windows.System.Profile.AnalyticsInfo activation is a wine
+ * semi-stub that fails without an MTA apartment, and returning NULL
+ * crashes titles that dereference the result in place (Deep Rock
+ * Galactic dies on a NULL read during early startup). GDK on a Windows
+ * desktop reports the "Windows.Desktop" family and "Desktop" form with
+ * the OS version the prefix advertises, so fill the struct directly. */
+ RTL_OSVERSIONINFOEXW version;
XSystemAnalyticsInfo info;
- char *str, *splitter;
- ULONGLONG version;
- HRESULT status;
- UINT32 strSize;
-
- IAnalyticsInfoStatics *analytics_info_statics = NULL;
- IAnalyticsVersionInfo *analytics_version_info = NULL;
TRACE( "iface %p.\n", iface );
- status = WindowsCreateString( analytics_info_str, wcslen( analytics_info_str ), &analytics_info_class );
- if (FAILED( status )) return NULL;
-
- status = RoGetActivationFactory( analytics_info_class, &IID_IAnalyticsInfoStatics, (void **)&analytics_info_statics );
- WindowsDeleteString( analytics_info_class );
- if (FAILED( status )) return NULL;
-
- status = IAnalyticsInfoStatics_get_VersionInfo( analytics_info_statics, &analytics_version_info );
- IAnalyticsInfoStatics_Release( analytics_info_statics );
- if (FAILED( status )) return NULL;
-
- status = IAnalyticsVersionInfo_get_DeviceFamilyVersion( analytics_version_info, &deviceFamilyVersion );
- if (FAILED( status ))
- {
- IAnalyticsVersionInfo_Release( analytics_version_info );
- return NULL;
- }
-
- status = IAnalyticsVersionInfo_get_DeviceFamily( analytics_version_info, &deviceFamily );
- IAnalyticsVersionInfo_Release( analytics_version_info );
- if (FAILED( status ))
- {
- WindowsDeleteString( deviceFamilyVersion );
- return NULL;
- }
-
- deviceFamilyStr = WindowsGetStringRawBuffer( deviceFamily, NULL );
- strSize = WideCharToMultiByte( CP_UTF8, 0, deviceFamilyStr, -1, NULL, 0, NULL, NULL );
-
- str = (char *)malloc( strSize );
- if (!str)
- {
- WindowsDeleteString( deviceFamilyVersion );
- WindowsDeleteString( deviceFamily );
- return NULL;
- }
-
- if (!WideCharToMultiByte( CP_UTF8, 0, deviceFamilyStr, -1, str, strSize, NULL, NULL ))
- {
- WindowsDeleteString( deviceFamilyVersion );
- WindowsDeleteString( deviceFamily );
- free( str );
- return NULL;
- }
-
- splitter = strchr( str, '.' );
- if (splitter)
- {
- *splitter = '\0';
-
- strcpy( info.family, str );
- strcpy( info.form, splitter + 1 );
- }
-
- WindowsDeleteString( deviceFamily );
- free( str );
-
- deviceFamilyVersionStr = WindowsGetStringRawBuffer( deviceFamilyVersion, NULL );
- strSize = WideCharToMultiByte( CP_UTF8, 0, deviceFamilyVersionStr, -1, NULL, 0, NULL, NULL );
-
- str = (char *)malloc( strSize );
- if (!str)
- {
- WindowsDeleteString( deviceFamilyVersion );
- return NULL;
- }
-
- if (!WideCharToMultiByte( CP_UTF8, 0, deviceFamilyVersionStr, -1, str, strSize, NULL, NULL ))
- {
- WindowsDeleteString( deviceFamilyVersion );
- free( str );
- return NULL;
- }
-
- version = strtoull( str, NULL, 10 );
- info.osVersion.major = (UINT16)(version >> 48);
- info.osVersion.minor = (UINT16)((version >> 32) & 0xFFFF);
- info.osVersion.build = (UINT16)((version >> 16) & 0xFFFF);
- info.osVersion.revision = (UINT16)(version & 0xFFFF);
-
- WindowsDeleteString( deviceFamilyVersion );
- free( str );
+ memset( &version, 0, sizeof(version) );
+ version.dwOSVersionInfoSize = sizeof(version);
+ RtlGetVersion( &version );
+ info.osVersion.major = version.dwMajorVersion;
+ info.osVersion.minor = version.dwMinorVersion;
+ info.osVersion.build = version.dwBuildNumber;
+ info.osVersion.revision = 0;
info.hostingOsVersion = info.osVersion;
+ strcpy( info.family, "Windows.Desktop" );
+ strcpy( info.form, "Desktop" );
*__ret = info;
diff --git a/dlls/xgameruntime/xthreading.c b/dlls/xgameruntime/xthreading.c
index 6d62fe1..a1c323b 100644
--- a/dlls/xgameruntime/xthreading.c
+++ b/dlls/xgameruntime/xthreading.c
@@ -23,6 +23,131 @@
WINE_DEFAULT_DEBUG_CHANNEL(gdkc);
+struct task_context
+{
+ struct task_context *next;
+ XTaskQueueHandle queue;
+ XTaskQueuePortHandle port;
+ XTaskQueueCallback *callback;
+ void *callbackContext;
+ HANDLE timer;
+};
+
+struct monitor_context
+{
+ XTaskQueueMonitorCallback *callback;
+ void *callbackContext;
+ XTaskQueueRegistrationToken token;
+};
+
+struct XTaskQueuePortObject
+{
+ IUnknown IUnknown_iface;
+ LONG ref;
+ LONG queued;
+ HANDLE terminating;
+ HANDLE terminated;
+ struct task_context *head;
+ XTaskQueueDispatchMode mode;
+};
+
+static inline XTaskQueuePortHandle port_impl_from_IUnknown( IUnknown *iface )
+{
+ return CONTAINING_RECORD( iface, struct XTaskQueuePortObject, IUnknown_iface );
+}
+
+static ULONG WINAPI port_AddRef( IUnknown *iface )
+{
+ XTaskQueuePortHandle impl = port_impl_from_IUnknown( iface );
+ ULONG ref = InterlockedIncrement( &impl->ref );
+ TRACE( "iface %p increasing refcount to %lu.\n", iface, ref );
+ return ref;
+}
+
+static ULONG WINAPI port_Release( IUnknown *iface )
+{
+ XTaskQueuePortHandle impl = port_impl_from_IUnknown( iface );
+ ULONG ref = InterlockedDecrement( &impl->ref );
+ TRACE( "iface %p decreasing refcount to %lu.\n", iface, ref );
+ if (!ref)
+ {
+ struct task_context *entry, *next = impl->head;
+ while ((entry = next))
+ {
+ CloseHandle( entry->timer );
+ next = entry->next;
+ free( entry );
+ }
+ CloseHandle( impl->terminating );
+ CloseHandle( impl->terminated );
+ free( impl );
+ }
+ return ref;
+}
+
+static const struct IUnknownVtbl port_vtbl =
+{
+ NULL,
+ port_AddRef,
+ port_Release,
+};
+
+struct XTaskQueueObject
+{
+ IUnknown IUnknown_iface;
+ LONG ref;
+ XTaskQueuePortHandle work;
+ XTaskQueuePortHandle completion;
+ XTaskQueueTerminatedCallback *terminatedCallback;
+ void *terminatedContext;
+ BOOL composite;
+ LONG terminated;
+ struct
+ {
+ struct monitor_context *entries;
+ CRITICAL_SECTION cs;
+ UINT32 capacity;
+ UINT32 length;
+ UINT64 token;
+ } monitors;
+};
+
+static inline XTaskQueueHandle queue_impl_from_IUnknown( IUnknown *iface )
+{
+ return CONTAINING_RECORD( iface, struct XTaskQueueObject, IUnknown_iface );
+}
+
+static ULONG WINAPI queue_AddRef( IUnknown *iface )
+{
+ XTaskQueueHandle impl = queue_impl_from_IUnknown( iface );
+ ULONG ref = InterlockedIncrement( &impl->ref );
+ TRACE( "iface %p increasing refcount to %lu.\n", iface, ref );
+ return ref;
+}
+
+static ULONG WINAPI queue_Release( IUnknown *iface )
+{
+ XTaskQueueHandle impl = queue_impl_from_IUnknown( iface );
+ ULONG ref = InterlockedDecrement( &impl->ref );
+ TRACE( "iface %p decreasing refcount to %lu.\n", iface, ref );
+ if (!ref)
+ {
+ DeleteCriticalSection( &impl->monitors.cs );
+ IUnknown_Release( &impl->work->IUnknown_iface );
+ IUnknown_Release( &impl->completion->IUnknown_iface );
+ if (impl->monitors.entries) free( impl->monitors.entries );
+ free( impl );
+ }
+ return ref;
+}
+
+static const struct IUnknownVtbl queue_vtbl =
+{
+ NULL,
+ queue_AddRef,
+ queue_Release,
+};
+
struct x_threading
{
IXThreadingImpl IXThreadingImpl_iface;
@@ -68,33 +193,101 @@ static ULONG WINAPI x_threading_Release( IXThreadingImpl *iface )
return ref;
}
+struct async_state
+{
+ XAsyncProviderData data;
+ HRESULT status;
+ LONG cleaned;
+};
+
+static inline struct async_state *async_state( XAsyncBlock *asyncBlock )
+{
+ return (struct async_state *)asyncBlock->internal[0];
+}
+
+static void async_cleanup_state( struct async_state *state, XAsyncProvider *provider )
+{
+ if (!InterlockedExchange( &state->cleaned, 1 ))
+ provider( XAsyncOp_Cleanup, &state->data );
+}
+
+static void async_cleanup( XAsyncBlock *asyncBlock )
+{
+ async_cleanup_state( async_state( asyncBlock ), asyncBlock->internal[1] );
+}
+
static HRESULT WINAPI x_threading_XAsyncGetStatus( IXThreadingImpl *iface, XAsyncBlock *asyncBlock, BOOLEAN wait )
{
- FIXME( "iface %p, asyncBlock %p, wait %d stub!\n", iface, asyncBlock, wait );
- return E_NOTIMPL;
+ TRACE( "iface %p, asyncBlock %p, wait %d.\n", iface, asyncBlock, wait );
+ if (!asyncBlock->internal[3]) return E_INVALIDARG;
+ if (WaitForSingleObject( asyncBlock->internal[3], wait ? INFINITE : 0 ) == WAIT_TIMEOUT) return E_PENDING;
+ TRACE( "asyncBlock %p -> status %#lx.\n", asyncBlock, async_state( asyncBlock )->status );
+ return async_state( asyncBlock )->status;
}
static HRESULT WINAPI x_threading_XAsyncGetResultSize( IXThreadingImpl *iface, XAsyncBlock *asyncBlock, SIZE_T *bufferSize )
{
- FIXME( "iface %p, asyncBlock %p, bufferSize %p stub!\n", iface, asyncBlock, bufferSize );
- return E_NOTIMPL;
+ TRACE( "iface %p, asyncBlock %p, bufferSize %p.\n", iface, asyncBlock, bufferSize );
+ *bufferSize = ((XAsyncProviderData *)asyncBlock->internal[0])->bufferSize;
+ return S_OK;
}
static void WINAPI x_threading_XAsyncCancel( IXThreadingImpl *iface, XAsyncBlock *asyncBlock )
{
- FIXME( "iface %p, asyncBlock %p stub!\n", iface, asyncBlock );
+ /* XAsyncCancel is best-effort and asynchronous: a block may still
+ * complete normally after a successful cancel. The providers here do
+ * not carry a cancel op, so cancelling is accepted and any in-flight
+ * work simply runs to its normal completion. */
+ TRACE( "iface %p, asyncBlock %p.\n", iface, asyncBlock );
+}
+
+static HRESULT WINAPI run_provider( XAsyncOp op, const XAsyncProviderData *data )
+{
+ HRESULT hr = S_OK;
+ switch (op)
+ {
+ case XAsyncOp_Begin:
+ return IXThreadingImpl_XAsyncSchedule( x_threading_impl, data->async, 0 );
+ case XAsyncOp_DoWork:
+ hr = ((XAsyncWork *)data->context)( data->async );
+ IXThreadingImpl_XAsyncComplete( x_threading_impl, data->async, hr, 0 );
+ hr = S_OK;
+ case XAsyncOp_GetResult:
+ case XAsyncOp_Cancel:
+ case XAsyncOp_Cleanup:
+ break;
+ }
+ return hr;
}
static HRESULT WINAPI x_threading_XAsyncRun( IXThreadingImpl *iface, XAsyncBlock *asyncBlock, XAsyncWork *work )
{
- FIXME( "iface %p, asyncBlock %p, work %p stub!\n", iface, asyncBlock, work );
- return E_NOTIMPL;
+ TRACE( "iface %p, asyncBlock %p, work %p.\n", iface, asyncBlock, work );
+ return IXThreadingImpl_XAsyncBegin( iface, asyncBlock, work, NULL, "XAsyncRun", run_provider );
}
static HRESULT WINAPI x_threading_XAsyncBegin( IXThreadingImpl *iface, XAsyncBlock *asyncBlock, void *context, const void *identity, const char *identityName, XAsyncProvider *provider )
{
- FIXME( "iface %p, asyncBlock %p, context %p, identity %p, identityName %s, provider %p stub!\n", iface, asyncBlock, context, identity, identityName, provider );
- return E_NOTIMPL;
+ struct async_state *state;
+ XAsyncProviderData *data;
+
+ TRACE( "iface %p, asyncBlock %p, context %p, identity %p, identityName %s, provider %p.\n", iface, asyncBlock, context, identity, identityName, provider );
+
+ if (!(state = calloc( 1, sizeof(*state) ))) return E_OUTOFMEMORY;
+ state->status = E_PENDING;
+ data = &state->data;
+ if (!asyncBlock->queue && !IXThreadingImpl_XTaskQueueGetCurrentProcessTaskQueue( iface, &asyncBlock->queue ))
+ {
+ free( state );
+ return E_INVALIDARG;
+ }
+ asyncBlock->internal[0] = data;
+ asyncBlock->internal[1] = provider;
+ asyncBlock->internal[2] = (void *)identity;
+ asyncBlock->internal[3] = CreateEventA( NULL, TRUE, FALSE, NULL );
+ data->async = asyncBlock;
+ data->context = context;
+ return provider( XAsyncOp_Begin, data );
}
static HRESULT WINAPI __PADDING__( IXThreadingImpl *iface )
@@ -103,68 +296,469 @@ static HRESULT WINAPI __PADDING__( IXThreadingImpl *iface )
return E_NOTIMPL;
}
+static void CALLBACK async_work_callback( XAsyncBlock *asyncBlock, BOOLEAN canceled )
+{
+ ((XAsyncProvider *)asyncBlock->internal[1])( canceled ? XAsyncOp_Cancel : XAsyncOp_DoWork, asyncBlock->internal[0] );
+}
+
static HRESULT WINAPI x_threading_XAsyncSchedule( IXThreadingImpl *iface, XAsyncBlock *asyncBlock, UINT32 delayInMs )
{
- FIXME( "iface %p, asyncBlock %p, delayInMs %d stub!\n", iface, asyncBlock, delayInMs );
- return E_NOTIMPL;
+ TRACE( "iface %p, asyncBlock %p, delayInMs %d.\n", iface, asyncBlock, delayInMs );
+ return IXThreadingImpl_XTaskQueueSubmitDelayedCallback( iface, asyncBlock->queue, XTaskQueuePort_Work, delayInMs, asyncBlock, (XTaskQueueCallback *)async_work_callback );
+}
+
+static void CALLBACK async_completion_callback( XAsyncBlock *asyncBlock, BOOLEAN canceled )
+{
+ struct async_state *state = async_state( asyncBlock );
+ XAsyncProvider *provider = asyncBlock->internal[1];
+
+ if (canceled) provider( XAsyncOp_Cancel, &state->data );
+ SetEvent( asyncBlock->internal[3] );
+ if (!canceled) asyncBlock->callback( asyncBlock );
+ /* The application may delete or reuse XAsyncBlock inside its completion
+ * callback. Only the runtime-owned state may be touched after it returns.
+ * GetResult may already have cleaned the provider; cleaned makes this
+ * idempotent without dereferencing the caller's freed block. */
+ if (canceled || FAILED(state->status) || !state->data.bufferSize)
+ async_cleanup_state( state, provider );
}
static void WINAPI x_threading_XAsyncComplete( IXThreadingImpl *iface, XAsyncBlock *asyncBlock, HRESULT result, SIZE_T requiredBufferSize )
{
- FIXME( "iface %p, asyncBlock %p, result %#lx, requiredBufferSize %Iu stub!\n", iface, asyncBlock, result, requiredBufferSize );
+ TRACE( "iface %p, asyncBlock %p, result %#lx, requiredBufferSize %Iu.\n", iface, asyncBlock, result, requiredBufferSize );
+ async_state( asyncBlock )->data.bufferSize = SUCCEEDED(result) ? requiredBufferSize : 0;
+ async_state( asyncBlock )->status = result;
+ if (asyncBlock->callback &&
+ SUCCEEDED(IXThreadingImpl_XTaskQueueSubmitCallback( iface, asyncBlock->queue, XTaskQueuePort_Completion, asyncBlock, (XTaskQueueCallback *)async_completion_callback )))
+ return;
+ SetEvent( asyncBlock->internal[3] );
+ if (FAILED(result) || !requiredBufferSize) async_cleanup( asyncBlock );
}
static HRESULT WINAPI x_threading_XAsyncGetResult( IXThreadingImpl *iface, XAsyncBlock *asyncBlock, const void *identity, SIZE_T bufferSize, void *buffer, SIZE_T *bufferUsed )
{
- FIXME( "iface %p asyncBlock %p, identity %p, bufferSize %Iu, buffer %p, bufferUsed %p stub!\n", iface, asyncBlock, identity, bufferSize, buffer, bufferUsed );
- return E_NOTIMPL;
+ HRESULT hr;
+ TRACE( "iface %p asyncBlock %p, identity %p, bufferSize %Iu, buffer %p, bufferUsed %p.\n", iface, asyncBlock, identity, bufferSize, buffer, bufferUsed );
+ if (WaitForSingleObject( asyncBlock->internal[3], 0 ) == WAIT_TIMEOUT) return E_PENDING;
+ if (FAILED(hr = async_state( asyncBlock )->status)) return hr;
+ if (bufferSize < async_state( asyncBlock )->data.bufferSize) return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+ async_state( asyncBlock )->data.buffer = buffer;
+ hr = ((XAsyncProvider *)asyncBlock->internal[1])( XAsyncOp_GetResult, asyncBlock->internal[0] );
+ if (bufferUsed) *bufferUsed = SUCCEEDED(hr) ? async_state( asyncBlock )->data.bufferSize : 0;
+ async_cleanup( asyncBlock );
+ return hr;
+}
+
+struct monitor_handler_context
+{
+ HANDLE finished;
+ XTaskQueueHandle queue;
+ XTaskQueuePort port;
+ UINT32 length;
+};
+
+static void CALLBACK monitor_handler( TP_CALLBACK_INSTANCE *, struct monitor_handler_context *context, TP_WORK * )
+{
+ struct monitor_context *monitors = (struct monitor_context *)(context + 1);
+ TRACE( "context %p.\n", context );
+ for (UINT32 i = 0; i < context->length; i++) monitors[i].callback( monitors[i].callbackContext, context->queue, context->port );
+ SetEvent( context->finished );
+ free( context );
+}
+
+static HANDLE invoke_monitors( XTaskQueueHandle queue, XTaskQueuePort port )
+{
+ struct monitor_handler_context *context;
+ HANDLE finished = NULL;
+ TP_WORK *work;
+
+ TRACE( "queue %p, port %d.\n", queue, port );
+
+ EnterCriticalSection( &queue->monitors.cs );
+ if ((context = calloc( 1, sizeof(*context) + queue->monitors.length * sizeof(struct monitor_context) )))
+ {
+ finished = CreateEventA( NULL, TRUE, FALSE, NULL );
+ context->finished = finished;
+ context->queue = queue;
+ context->port = port;
+ context->length = queue->monitors.length;
+ memcpy( context + 1, context->queue->monitors.entries, context->queue->monitors.length * sizeof(struct monitor_context) );
+ if ((work = CreateThreadpoolWork( (PTP_WORK_CALLBACK)monitor_handler, context, NULL ))) SubmitThreadpoolWork( work );
+ else
+ {
+ CloseHandle( finished );
+ finished = NULL;
+ free( context );
+ }
+ }
+ LeaveCriticalSection( &queue->monitors.cs );
+ return finished;
+}
+
+static void CALLBACK work_handler( TP_CALLBACK_INSTANCE *, struct task_context *context, TP_WORK * )
+{
+ HANDLE finished, objects[2] = { context->port->terminating, context->timer };
+
+ TRACE( "context %p.\n", context );
+
+ WaitForMultipleObjects( 2, objects, FALSE, INFINITE );
+ finished = invoke_monitors( context->queue, context->port->mode );
+ context->callback( context->callbackContext, !WaitForSingleObject( context->port->terminating, 0 ) );
+ if (finished) WaitForSingleObject( finished, INFINITE );
+ if (!InterlockedDecrement( &context->port->queued ) && !WaitForSingleObject( context->port->terminating, 0 )) SetEvent( context->port->terminated );
+ IUnknown_Release( &context->port->IUnknown_iface );
+ CloseHandle( context->timer );
+ CloseHandle( finished );
+ free( context );
+}
+
+static void CALLBACK dispatch_handler( TP_CALLBACK_INSTANCE *, XTaskQueuePortHandle port, TP_WORK * )
+{
+ /* worker for SerializedThreadPool and delayed Immediate modes */
+ TRACE( "port %p.\n", port );
+
+ while (TRUE)
+ {
+ struct task_context *entry, *next = port->head, *parent = NULL;
+ TP_WORK *work;
+ if (WaitForSingleObject( port->terminating, 0 ) == WAIT_TIMEOUT)
+ {
+ while ((entry = next))
+ {
+ next = entry->next;
+ if (!WaitForSingleObject( entry->timer, 0 ))
+ {
+ if (parent) InterlockedExchangePointer( (void **)&parent->next, next );
+ else InterlockedExchangePointer( (void **)&port->head, next );
+ if (port->mode == XTaskQueueDispatchMode_SerializedThreadPool)
+ {
+ HANDLE finished = invoke_monitors( entry->queue, port->mode );
+ entry->callback( entry->callbackContext, FALSE );
+ if (finished) WaitForSingleObject( finished, INFINITE );
+ if (!InterlockedDecrement( &port->queued ) && !WaitForSingleObject( port->terminating, 0 )) SetEvent( port->terminated );
+ IUnknown_Release( &port->IUnknown_iface );
+ CloseHandle( entry->timer );
+ CloseHandle( finished );
+ free( entry );
+ }
+ else if ((work = CreateThreadpoolWork( (PTP_WORK_CALLBACK)work_handler, entry, NULL ))) SubmitThreadpoolWork( work );
+ else
+ {
+ if (!InterlockedDecrement( &port->queued ) && !WaitForSingleObject( port->terminating, 0 )) SetEvent( port->terminated );
+ IUnknown_Release( &port->IUnknown_iface );
+ CloseHandle( entry->timer );
+ free( entry );
+ }
+ break;
+ }
+ parent = entry;
+ }
+ }
+ else
+ {
+ if (port->mode == XTaskQueueDispatchMode_Immediate)
+ {
+ SetEvent( port->terminated );
+ return;
+ }
+ while ((entry = next))
+ {
+ HANDLE finished = invoke_monitors( entry->queue, port->mode );
+ entry->callback( entry->callbackContext, TRUE );
+ if (finished) WaitForSingleObject( finished, INFINITE );
+ if (!InterlockedDecrement( &port->queued ) && !WaitForSingleObject( port->terminating, 0 )) SetEvent( port->terminated );
+ CloseHandle( entry->timer );
+ CloseHandle( finished );
+ next = entry->next;
+ free( entry );
+ IUnknown_Release( &port->IUnknown_iface );
+ }
+ port->head = NULL;
+ return;
+ }
+ }
+}
+
+static HRESULT create_port( XTaskQueueDispatchMode mode, XTaskQueuePortHandle *port )
+{
+ TRACE( "mode %d, port %p.\n", mode, port );
+
+ if (!(*port = calloc( 1, sizeof(**port) ))) return E_OUTOFMEMORY;
+ (*port)->IUnknown_iface.lpVtbl = &port_vtbl;
+ (*port)->ref = 1;
+ (*port)->mode = mode;
+ (*port)->terminating = CreateEventA( NULL, TRUE, FALSE, NULL );
+ (*port)->terminated = CreateEventA( NULL, TRUE, FALSE, NULL );
+ if (mode == XTaskQueueDispatchMode_SerializedThreadPool || mode == XTaskQueueDispatchMode_Immediate)
+ {
+ TP_WORK *work;
+ if (mode == XTaskQueueDispatchMode_Manual) return S_OK;
+ if (!(work = CreateThreadpoolWork( (PTP_WORK_CALLBACK)dispatch_handler, *port, NULL )))
+ {
+ free( *port );
+ return E_OUTOFMEMORY;
+ }
+ SubmitThreadpoolWork( work );
+ }
+ return S_OK;
}
static HRESULT WINAPI x_threading_XTaskQueueCreate( IXThreadingImpl *iface, XTaskQueueDispatchMode workDispatchMode, XTaskQueueDispatchMode completionDispatchMode, XTaskQueueHandle *queue )
{
- FIXME( "iface %p, workDispatchMode %d, completionDispatchMode %d, queue %p stub!\n", iface, workDispatchMode, completionDispatchMode, queue );
- return E_NOTIMPL;
+ HRESULT hr;
+
+ TRACE( "iface %p, workDispatchMode %d, completionDispatchMode %d, queue %p.\n", iface, workDispatchMode, completionDispatchMode, queue );
+
+ if (!(*queue = calloc( 1, sizeof(**queue) ))) return E_OUTOFMEMORY;
+ (*queue)->IUnknown_iface.lpVtbl = &queue_vtbl;
+ (*queue)->ref = 1;
+ (*queue)->monitors.capacity = 32;
+ InitializeCriticalSection( &(*queue)->monitors.cs );
+ if (FAILED(hr = create_port( workDispatchMode, &(*queue)->work )))
+ {
+ IUnknown_Release( &(*queue)->IUnknown_iface );
+ return hr;
+ }
+ if (FAILED(hr = create_port( completionDispatchMode, &(*queue)->completion )))
+ {
+ IUnknown_Release( &(*queue)->IUnknown_iface );
+ return hr;
+ }
+ if (!((*queue)->monitors.entries = calloc( 32, sizeof(*(*queue)->monitors.entries) )))
+ {
+ IUnknown_Release( &(*queue)->IUnknown_iface );
+ return hr;
+ }
+ return S_OK;
}
static HRESULT WINAPI x_threading_XTaskQueueCreateComposite( IXThreadingImpl *iface, XTaskQueuePortHandle workPort, XTaskQueuePortHandle completionPort, XTaskQueueHandle *queue )
{
- FIXME( "iface %p, workPort %p, completionPort %p, queue %p stub!\n", iface, workPort, completionPort, queue );
- return E_NOTIMPL;
+ TRACE( "iface %p, workPort %p, completionPort %p, queue %p.\n", iface, workPort, completionPort, queue );
+ if (!(*queue = calloc( 1, sizeof(**queue) ))) return E_OUTOFMEMORY;
+ if (!((*queue)->monitors.entries = calloc( 32, sizeof(*(*queue)->monitors.entries) )))
+ {
+ free( *queue );
+ *queue = NULL;
+ return E_OUTOFMEMORY;
+ }
+ (*queue)->IUnknown_iface.lpVtbl = &queue_vtbl;
+ (*queue)->monitors.capacity = 32;
+ (*queue)->ref = 1;
+ (*queue)->work = workPort;
+ (*queue)->completion = completionPort;
+ (*queue)->composite = TRUE;
+ IUnknown_AddRef( &workPort->IUnknown_iface );
+ IUnknown_AddRef( &completionPort->IUnknown_iface );
+ InitializeCriticalSection( &(*queue)->monitors.cs );
+ return S_OK;
}
static HRESULT WINAPI x_threading_XTaskQueueGetPort( IXThreadingImpl *iface, XTaskQueueHandle queue, XTaskQueuePort port, XTaskQueuePortHandle *portHandle )
{
- FIXME( "iface %p, queue %p, port %d, portHandle %p stub!\n", iface, queue, port, portHandle );
- return E_NOTIMPL;
+ TRACE( "iface %p, queue %p, port %d, portHandle %p.\n", iface, queue, port, portHandle );
+ switch (port)
+ {
+ case XTaskQueuePort_Work:
+ *portHandle = queue->work;
+ return S_OK;
+ case XTaskQueuePort_Completion:
+ *portHandle = queue->completion;
+ return S_OK;
+ }
+ return E_INVALIDARG;
}
static HRESULT WINAPI x_threading_XTaskQueueDuplicateHandle( IXThreadingImpl *iface, XTaskQueueHandle queueHandle, XTaskQueueHandle *duplicatedHandle )
{
- FIXME( "iface %p, queueHandle %p, duplicatedHandle %p stub!\n", iface, queueHandle, duplicatedHandle );
- return E_NOTIMPL;
+ TRACE( "iface %p, queueHandle %p, duplicatedHandle %p.\n", iface, queueHandle, duplicatedHandle );
+ IUnknown_AddRef( &queueHandle->IUnknown_iface );
+ *duplicatedHandle = queueHandle;
+ return S_OK;
}
-static BOOLEAN WINAPI x_threading_XTaskQueueDispatch( IXThreadingImpl *iface, XTaskQueueHandle queue, XTaskQueuePort port, UINT32 timeoutInMs )
+static BOOLEAN dispatch_manual_entry( XTaskQueueHandle queue, XTaskQueuePortHandle port )
{
- FIXME( "iface %p, queue %p, port %d, timeoutInMs %d stub!\n", iface, queue, port, timeoutInMs );
+ struct task_context *entry, *next = port->head, *parent = NULL;
+ BOOLEAN canceled = !WaitForSingleObject( port->terminating, 0 );
+ HANDLE finished;
+
+ while ((entry = next))
+ {
+ next = entry->next;
+ if (canceled || !WaitForSingleObject( entry->timer, 0 ))
+ {
+ if (parent) InterlockedExchangePointer( (void **)&parent->next, next );
+ else InterlockedExchangePointer( (void **)&port->head, next );
+ finished = invoke_monitors( entry->queue, port->mode );
+ entry->callback( entry->callbackContext, canceled );
+ if (finished) WaitForSingleObject( finished, INFINITE );
+ if (!InterlockedDecrement( &port->queued ) && !WaitForSingleObject( port->terminating, 0 )) SetEvent( port->terminated );
+ IUnknown_Release( &port->IUnknown_iface );
+ CloseHandle( entry->timer );
+ CloseHandle( finished );
+ free( entry );
+ return TRUE;
+ }
+ parent = entry;
+ }
return FALSE;
}
+static BOOLEAN dispatch_terminated_callback( XTaskQueueHandle queue )
+{
+ XTaskQueueTerminatedCallback *callback;
+
+ if (!queue->terminatedCallback) return FALSE;
+ if (WaitForSingleObject( queue->work->terminated, 0 ) || WaitForSingleObject( queue->completion->terminated, 0 )) return FALSE;
+ if (!(callback = InterlockedExchangePointer( (void **)&queue->terminatedCallback, NULL ))) return FALSE;
+ callback( queue->terminatedContext );
+ return TRUE;
+}
+
+static BOOLEAN WINAPI x_threading_XTaskQueueDispatch( IXThreadingImpl *iface, XTaskQueueHandle queue, XTaskQueuePort port, UINT32 timeoutInMs )
+{
+ XTaskQueuePortHandle handle;
+ DWORD start = GetTickCount();
+
+ TRACE( "iface %p, queue %p, port %d, timeoutInMs %d.\n", iface, queue, port, timeoutInMs );
+
+ if (!queue && !IXThreadingImpl_XTaskQueueGetCurrentProcessTaskQueue( iface, &queue )) return FALSE;
+ switch (port)
+ {
+ case XTaskQueuePort_Work:
+ handle = queue->work;
+ break;
+ case XTaskQueuePort_Completion:
+ handle = queue->completion;
+ break;
+ default:
+ return FALSE;
+ }
+ if (handle->mode != XTaskQueueDispatchMode_Manual) return FALSE;
+
+ while (TRUE)
+ {
+ if (dispatch_manual_entry( queue, handle )) return TRUE;
+ if (port == XTaskQueuePort_Completion && dispatch_terminated_callback( queue )) return TRUE;
+ if (timeoutInMs != INFINITE && GetTickCount() - start >= timeoutInMs) return FALSE;
+ Sleep( 1 );
+ }
+}
+
static void WINAPI x_threading_XTaskQueueCloseHandle( IXThreadingImpl *iface, XTaskQueueHandle queue )
{
- FIXME( "iface %p, queue %p stub!\n", iface, queue );
+ TRACE( "iface %p, queue %p.\n", iface, queue );
+ IUnknown_Release( &queue->IUnknown_iface );
}
static HRESULT WINAPI x_threading_XTaskQueueSubmitCallback( IXThreadingImpl *iface, XTaskQueueHandle queue, XTaskQueuePort port, void *callbackContext, XTaskQueueCallback *callback )
{
- FIXME( "iface %p, queue %p, port %d, callbackContext %p, callback %p stub!\n", iface, queue, port, callbackContext, callback );
- return E_NOTIMPL;
+ return IXThreadingImpl_XTaskQueueSubmitDelayedCallback( iface, queue, port, 0, callbackContext, callback );
}
static HRESULT WINAPI x_threading_XTaskQueueSubmitDelayedCallback( IXThreadingImpl *iface, XTaskQueueHandle queue, XTaskQueuePort port, UINT32 delayMs, void *callbackContext, XTaskQueueCallback *callback )
{
- FIXME( "iface %p, queue %p, port %d, delayMs %d, callbackContext %p, callback %p stub!\n", iface, queue, port, delayMs, callbackContext, callback );
- return E_NOTIMPL;
+ struct task_context *context, *entry;
+ XTaskQueuePortHandle handle;
+ LARGE_INTEGER time;
+ TP_WORK *work;
+
+ TRACE( "iface %p, queue %p, port %d, delayMs %d, callbackContext %p, callback %p.\n", iface, queue, port, delayMs, callbackContext, callback );
+
+ switch (port)
+ {
+ case XTaskQueuePort_Work:
+ handle = queue->work;
+ break;
+ case XTaskQueuePort_Completion:
+ handle = queue->completion;
+ break;
+ default:
+ return E_INVALIDARG;
+ }
+ if (queue->terminated) return E_ABORT;
+
+ /*
+ * increment before check terminating, otherwise we might terminate between check and dispatch
+ * tasks hold a reference on the port object separate to the queued task count to avoid the port being freed
+ */
+ InterlockedIncrement( &handle->queued );
+ IUnknown_AddRef( &handle->IUnknown_iface );
+ if (!WaitForSingleObject( handle->terminating, 0 ))
+ {
+ if (!InterlockedDecrement( &handle->queued )) SetEvent( handle->terminated );
+ IUnknown_Release( &handle->IUnknown_iface );
+ return E_ABORT;
+ }
+
+ if (handle->mode == XTaskQueueDispatchMode_Immediate && !delayMs)
+ {
+ callback( callbackContext, FALSE );
+ if (!InterlockedDecrement( &handle->queued ) && !WaitForSingleObject( handle->terminating, 0 )) SetEvent( handle->terminated );
+ IUnknown_Release( &handle->IUnknown_iface );
+ return S_OK;
+ }
+
+ if (!(context = calloc( 1, sizeof(*context) )))
+ {
+ if (!InterlockedDecrement( &handle->queued ) && !WaitForSingleObject( handle->terminating, 0 )) SetEvent( handle->terminated );
+ IUnknown_Release( &handle->IUnknown_iface );
+ return E_OUTOFMEMORY;
+ }
+
+ context->queue = queue;
+ context->port = handle;
+ context->callback = callback;
+ context->callbackContext = callbackContext;
+ if (!(context->timer = CreateWaitableTimerW( NULL, TRUE, NULL )))
+ {
+ if (!InterlockedDecrement( &handle->queued ) && !WaitForSingleObject( handle->terminating, 0 )) SetEvent( handle->terminated );
+ IUnknown_Release( &handle->IUnknown_iface );
+ CloseHandle( context->timer );
+ free( context );
+ return HRESULT_FROM_WIN32( GetLastError() );
+ }
+
+ time.QuadPart = delayMs * -10000LL;
+ if (!SetWaitableTimer( context->timer, &time, 0, NULL, NULL, FALSE ))
+ {
+ if (!InterlockedDecrement( &handle->queued ) && !WaitForSingleObject( handle->terminating, 0 )) SetEvent( handle->terminated );
+ IUnknown_Release( &handle->IUnknown_iface );
+ CloseHandle( context->timer );
+ free( context );
+ return HRESULT_FROM_WIN32( GetLastError() );
+ }
+
+ switch (handle->mode)
+ {
+ case XTaskQueueDispatchMode_Manual:
+ case XTaskQueueDispatchMode_SerializedThreadPool:
+ case XTaskQueueDispatchMode_Immediate:
+ if (!InterlockedCompareExchangePointer( (void **)&handle->head, context, NULL )) return S_OK;
+ entry = handle->head;
+ while (InterlockedCompareExchangePointer( (void **)&entry->next, context, NULL )) entry = entry->next;
+ return S_OK;
+
+ case XTaskQueueDispatchMode_ThreadPool:
+ if (!(work = CreateThreadpoolWork( (PTP_WORK_CALLBACK)work_handler, context, NULL )))
+ {
+ if (!InterlockedDecrement( &handle->queued ) && !WaitForSingleObject( handle->terminating, 0 )) SetEvent( handle->terminated );
+ IUnknown_Release( &handle->IUnknown_iface );
+ CloseHandle( context->timer );
+ free( context );
+ return HRESULT_FROM_WIN32( GetLastError() );
+ }
+ SubmitThreadpoolWork( work );
+ return S_OK;
+
+ default:
+ if (!InterlockedDecrement( &handle->queued ) && !WaitForSingleObject( handle->terminating, 0 )) SetEvent( handle->terminated );
+ IUnknown_Release( &handle->IUnknown_iface );
+ CloseHandle( context->timer );
+ free( context );
+ return E_INVALIDARG;
+ }
}
static HRESULT WINAPI x_threading_XTaskQueueRegisterWaiter( IXThreadingImpl *iface, XTaskQueueHandle queue, XTaskQueuePort port, HANDLE waitHandle, void *callbackContext, XTaskQueueCallback *callback, XTaskQueueRegistrationToken *token )
@@ -178,32 +772,171 @@ static void WINAPI x_threading_XTaskQueueUnregisterWaiter( IXThreadingImpl *ifac
FIXME( "iface %p, queue %p, token %p stub!\n", iface, queue, &token );
}
+static void CALLBACK terminated_handler( TP_CALLBACK_INSTANCE *, XTaskQueueHandle queue, TP_WORK * )
+{
+ HANDLE objects[2] = { queue->work->terminated, queue->completion->terminated };
+ XTaskQueueTerminatedCallback *callback;
+
+ TRACE( "queue %p.\n", queue );
+
+ WaitForMultipleObjects( 2, objects, TRUE, INFINITE );
+ if ((callback = InterlockedExchangePointer( (void **)&queue->terminatedCallback, NULL ))) callback( queue->terminatedContext );
+ IUnknown_Release( &queue->IUnknown_iface );
+}
+
+static void CALLBACK composite_terminated_handler( TP_CALLBACK_INSTANCE *, void *context )
+{
+ XTaskQueueHandle queue = context;
+ XTaskQueueTerminatedCallback *callback;
+
+ if ((callback = InterlockedExchangePointer( (void **)&queue->terminatedCallback, NULL ))) callback( queue->terminatedContext );
+ IUnknown_Release( &queue->IUnknown_iface );
+}
+
+static void composite_terminated( XTaskQueueHandle queue )
+{
+ IUnknown_AddRef( &queue->IUnknown_iface );
+ if (!TrySubmitThreadpoolCallback( composite_terminated_handler, queue, NULL )) IUnknown_Release( &queue->IUnknown_iface );
+}
+
static HRESULT WINAPI x_threading_XTaskQueueTerminate( IXThreadingImpl *iface, XTaskQueueHandle queue, BOOLEAN wait, void *callbackContext, XTaskQueueTerminatedCallback *callback )
{
- FIXME( "iface %p, queue %p, wait %d, callbackContext %p, callback %p stub!\n", iface, queue, wait, callbackContext, callback );
- return E_NOTIMPL;
+ HANDLE objects[2] = { queue->work->terminated, queue->completion->terminated };
+
+ TRACE( "iface %p, queue %p, wait %d, callbackContext %p, callback %p.\n", iface, queue, wait, callbackContext, callback );
+
+ if (queue->composite)
+ {
+ InterlockedExchange( &queue->terminated, TRUE );
+ if (callback)
+ {
+ queue->terminatedContext = callbackContext;
+ queue->terminatedCallback = callback;
+ composite_terminated( queue );
+ }
+ return S_OK;
+ }
+
+ SetEvent( queue->work->terminating );
+ SetEvent( queue->completion->terminating );
+ if (!queue->work->queued) SetEvent( queue->work->terminated );
+ if (!queue->completion->queued) SetEvent( queue->completion->terminated );
+ if (callback)
+ {
+ queue->terminatedContext = callbackContext;
+ InterlockedExchangePointer( (void **)&queue->terminatedCallback, callback );
+ }
+ if (wait) WaitForMultipleObjects( 2, objects, TRUE, INFINITE );
+ if (queue->work->mode == XTaskQueueDispatchMode_Immediate && !WaitForSingleObject( queue->work->terminated, INFINITE ))
+ {
+ struct task_context *entry, *next = queue->work->head;
+ while ((entry = next))
+ {
+ entry->callback( entry->callbackContext, TRUE );
+ CloseHandle( entry->timer );
+ next = entry->next;
+ free( entry );
+ IUnknown_Release( &queue->work->IUnknown_iface );
+ }
+ queue->work->head = NULL;
+ }
+ if (queue->completion->mode == XTaskQueueDispatchMode_Immediate && !WaitForSingleObject( queue->completion->terminated, INFINITE ))
+ {
+ struct task_context *entry, *next = queue->completion->head;
+ while ((entry = next))
+ {
+ entry->callback( entry->callbackContext, TRUE );
+ CloseHandle( entry->timer );
+ next = entry->next;
+ free( entry );
+ IUnknown_Release( &queue->completion->IUnknown_iface );
+ }
+ queue->completion->head = NULL;
+ }
+ if (queue->completion->mode != XTaskQueueDispatchMode_Manual)
+ {
+ TP_WORK *work;
+ IUnknown_AddRef( &queue->IUnknown_iface );
+ if ((work = CreateThreadpoolWork( (PTP_WORK_CALLBACK)terminated_handler, queue, NULL ))) SubmitThreadpoolWork( work );
+ else IUnknown_Release( &queue->IUnknown_iface );
+ }
+ return S_OK;
}
static HRESULT WINAPI x_threading_XTaskQueueRegisterMonitor( IXThreadingImpl *iface, XTaskQueueHandle queue, void *callbackContext, XTaskQueueMonitorCallback *callback, XTaskQueueRegistrationToken *token )
{
- FIXME( "iface %p, queue %p, callbackContext %p, callback %p, token %p stub!\n", iface, queue, callbackContext, callback, token );
- return E_NOTIMPL;
+ TRACE( "iface %p, queue %p, callbackContext %p, callback %p, token %p.\n", iface, queue, callbackContext, callback, token );
+
+ if (!queue || !callback || !token) return E_POINTER;
+ EnterCriticalSection( &queue->monitors.cs );
+ if (queue->monitors.capacity == queue->monitors.length)
+ {
+ UINT32 capacity = queue->monitors.capacity * 1.5;
+ struct monitor_context *entries;
+ if (!(entries = realloc( queue->monitors.entries, capacity * sizeof(*entries) )))
+ {
+ LeaveCriticalSection( &queue->monitors.cs );
+ return E_OUTOFMEMORY;
+ }
+ queue->monitors.capacity = capacity;
+ queue->monitors.entries = entries;
+ }
+ queue->monitors.entries[queue->monitors.length].callback = callback;
+ queue->monitors.entries[queue->monitors.length].callbackContext = callbackContext;
+ token->token = queue->monitors.token++;
+ queue->monitors.entries[queue->monitors.length++].token = *token;
+ LeaveCriticalSection( &queue->monitors.cs );
+ return S_OK;
}
static void WINAPI x_threading_XTaskQueueUnregisterMonitor( IXThreadingImpl *iface, XTaskQueueHandle queue, XTaskQueueRegistrationToken token )
{
- FIXME( "iface %p, queue %p, token %p stub!\n", iface, queue, &token );
+ TRACE( "iface %p, queue %p, token %p.\n", iface, queue, &token );
+
+ if (!queue) return;
+ EnterCriticalSection( &queue->monitors.cs );
+ for (UINT32 i = 0; i < queue->monitors.length; i++)
+ {
+ if (queue->monitors.entries[i].token.token == token.token)
+ {
+ memmove( queue->monitors.entries + i, queue->monitors.entries + i + 1, (--queue->monitors.length - i) * sizeof(*queue->monitors.entries) );
+ break;
+ }
+ }
+ LeaveCriticalSection( &queue->monitors.cs );
}
+static BOOLEAN defaultCreated;
+
static BOOLEAN WINAPI x_threading_XTaskQueueGetCurrentProcessTaskQueue( IXThreadingImpl *iface, XTaskQueueHandle *queue )
{
- FIXME( "iface %p, queue %p stub!\n", iface, queue );
- return FALSE;
+ TRACE( "iface %p, queue %p.\n", iface, queue );
+ EnterCriticalSection( &processQueueSection );
+ if (!processQueue && !defaultCreated)
+ {
+ defaultCreated = TRUE;
+ if (FAILED(IXThreadingImpl_XTaskQueueCreate( iface, XTaskQueueDispatchMode_ThreadPool, XTaskQueueDispatchMode_ThreadPool, &processQueue ))) processQueue = NULL;
+ }
+ if (!processQueue)
+ {
+ LeaveCriticalSection( &processQueueSection );
+ return FALSE;
+ }
+ IUnknown_AddRef( &processQueue->IUnknown_iface );
+ *queue = processQueue;
+ LeaveCriticalSection( &processQueueSection );
+ return TRUE;
}
static void WINAPI x_threading_XTaskQueueSetCurrentProcessTaskQueue( IXThreadingImpl *iface, XTaskQueueHandle queue )
{
- FIXME( "iface %p, queue %p stub!\n", iface, queue );
+ TRACE( "iface %p, queue %p.\n", iface, queue );
+ EnterCriticalSection( &processQueueSection );
+ defaultCreated = TRUE;
+ if (processQueue) IUnknown_Release( &processQueue->IUnknown_iface );
+ if (queue) IUnknown_AddRef( &queue->IUnknown_iface );
+ processQueue = queue;
+ LeaveCriticalSection( &processQueueSection );
}
static HRESULT WINAPI x_threading_XThreadSetTimeSensitive( IXThreadingImpl *iface, BOOLEAN isTimeSensitiveThread )
diff --git a/dlls/xgameruntime/xuser.c b/dlls/xgameruntime/xuser.c
index fbf960d..b2fe79a 100644
--- a/dlls/xgameruntime/xuser.c
+++ b/dlls/xgameruntime/xuser.c
@@ -19,10 +19,917 @@
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
+#include <winsock2.h>
+#include <afunix.h>
+#include <libxml/parser.h>
+#include <libxml/tree.h>
#include "private.h"
+#include "userprovider.h"
+#include "util.h"
+#include <bcrypt.h>
+#include <dbghelp.h>
+#include <ntdef.h>
+#include <wininet.h>
WINE_DEFAULT_DEBUG_CHANNEL(gdkc);
+static const WCHAR *ACCEPT_JSON[] = { L"application/json", NULL };
+
+static HRESULT parse_json( const char *json, SIZE_T jsonLen, IJsonObject **object )
+{
+ static const WCHAR *name = RuntimeClass_Windows_Data_Json_JsonValue;
+ IJsonValueStatics *statics;
+ HSTRING_HEADER header;
+ IJsonValue *value;
+ UINT32 wJsonLen;
+ HSTRING string;
+ WCHAR *wJson;
+ HRESULT hr;
+
+ TRACE( "json %s, object %p.\n", debugstr_an( json, jsonLen ), object );
+
+ if (!(wJsonLen = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, json, jsonLen, NULL, 0 ))) return HRESULT_FROM_WIN32( GetLastError() );
+ if (FAILED(hr = WindowsCreateStringReference( name, wcslen( name ), &header, &string ))) return hr;
+ if (FAILED(hr = RoGetActivationFactory( string, &IID_IJsonValueStatics, (void **)&statics ))) return hr;
+ if (!(wJson = calloc( wJsonLen + 1, sizeof(WCHAR) )))
+ {
+ IJsonValueStatics_Release( statics );
+ return E_OUTOFMEMORY;
+ }
+
+ if (!MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, json, jsonLen, wJson, wJsonLen )) goto error;
+ if (FAILED(hr = WindowsCreateStringReference( wJson, wJsonLen, &header, &string ))) goto cleanup;
+ if (FAILED(hr = IJsonValueStatics_Parse( statics, string, &value ))) goto cleanup;
+ hr = IJsonValue_GetObject( value, object );
+ IJsonValue_Release( value );
+ goto cleanup;
+
+error:
+ hr = HRESULT_FROM_WIN32( GetLastError() );
+cleanup:
+ IJsonValueStatics_Release( statics );
+ free( wJson );
+ return hr;
+}
+
+struct policy
+{
+ UINT32 version;
+ UINT32 maxBodyBytes;
+};
+
+struct endpoint
+{
+ HSTRING protocol;
+ HSTRING host;
+ HSTRING path;
+ HSTRING relyingParty;
+ HSTRING tokenType;
+ struct policy *policy;
+ BOOL wildcard;
+};
+
+struct XUser
+{
+ IUser IUser_iface;
+ LONG ref;
+
+ BCRYPT_KEY_HANDLE key;
+ char *proofKey;
+ char *userToken;
+ char *deviceToken;
+ char *titleToken;
+ char *deviceAuth;
+ ULONGLONG deviceAuthTime;
+ CRITICAL_SECTION deviceAuthSection;
+ UINT64 xuid;
+ UINT32 policiesLen;
+ UINT32 endpointsLen;
+ struct policy *policies;
+ struct endpoint *endpoints;
+
+ char gamertag[16];
+ char modernGamertag[97];
+ char modernGamertagSuffix[15];
+ char uniqueModernGamertag[101];
+};
+
+/* Private opt-in diagnostics: numeric metadata only, never credentials or URLs.
+ * The caller must pre-create the private file; bounded to 32 KiB. */
+static void auth_metadata( const char *phase, XUserHandle user, HRESULT hr,
+ DWORD status, BOOL requested_title, BOOL actual_title )
+{
+ static SRWLOCK lock = SRWLOCK_INIT;
+ DWORD saved_error = GetLastError(), length, written;
+ char path[MAX_PATH], line[256];
+ LARGE_INTEGER size, end;
+ HANDLE file;
+
+ length = GetEnvironmentVariableA( "XUSER_AUTH_METADATA_LOG", path, sizeof(path) );
+ if (!length || length >= sizeof(path)) goto done;
+ length = snprintf( line, sizeof(line),
+ "AUTH_META phase=%s hr=%08lx http=%lu device=%u user=%u title=%u requested_title=%u actual_title=%u tick=%lu thread=%lu\n",
+ phase, (unsigned long)(UINT32)hr, (unsigned long)status,
+ !!(user && user->deviceToken), !!(user && user->userToken), !!(user && user->titleToken),
+ !!requested_title, !!actual_title, (unsigned long)GetTickCount(), (unsigned long)GetCurrentThreadId() );
+ if (length >= sizeof(line)) goto done;
+ AcquireSRWLockExclusive( &lock );
+ file = CreateFileA( path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
+ NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
+ if (file != INVALID_HANDLE_VALUE)
+ {
+ if (GetFileSizeEx( file, &size ) && size.QuadPart + length <= 32768)
+ {
+ end.QuadPart = 0;
+ if (SetFilePointerEx( file, end, NULL, FILE_END )) WriteFile( file, line, length, &written, NULL );
+ }
+ CloseHandle( file );
+ }
+ ReleaseSRWLockExclusive( &lock );
+done:
+ SetLastError( saved_error );
+}
+
+static inline struct XUser *impl_from_IUser( IUser *iface )
+{
+ return CONTAINING_RECORD( iface, struct XUser, IUser_iface );
+}
+
+static ULONG WINAPI user_AddRef( IUser *iface )
+{
+ struct XUser *impl = impl_from_IUser( iface );
+ ULONG ref = InterlockedIncrement( &impl->ref );
+ TRACE( "iface %p increasing refcount to %lu.\n", iface, ref );
+ return ref;
+}
+
+static ULONG WINAPI user_Release( IUser *iface )
+{
+ struct XUser *impl = impl_from_IUser( iface );
+ ULONG ref = InterlockedDecrement( &impl->ref );
+ TRACE( "iface %p decreasing refcount to %lu.\n", iface, ref );
+ if (!ref)
+ {
+ if (impl->key) BCryptDestroyKey( impl->key );
+ if (impl->proofKey) free( impl->proofKey );
+ if (impl->userToken) free( impl->userToken );
+ free( impl->deviceToken );
+ free( impl->titleToken );
+ free( impl->deviceAuth );
+ if (impl->policies) free( impl->policies );
+ if (impl->endpoints) {
+ for(UINT32 i = 0; i < impl->endpointsLen; i++) {
+ WindowsDeleteString(impl->endpoints[i].protocol);
+ WindowsDeleteString(impl->endpoints[i].host);
+ WindowsDeleteString(impl->endpoints[i].path);
+ WindowsDeleteString(impl->endpoints[i].relyingParty);
+ WindowsDeleteString(impl->endpoints[i].tokenType);
+ }
+ free( impl->endpoints );
+ }
+ }
+ return ref;
+}
+
+extern char *msaAppId;
+extern BOOLEAN fullTrust;
+
+#define XODUS_XML_MAGIC 0x58445358
+#define XODUS_MSA_TOKEN_REQUEST 3
+
+static HRESULT xodus_socket_path( char *path, SIZE_T size )
+{
+ char unixPath[MAX_PATH];
+ WCHAR *dosPath;
+ DWORD len;
+
+ if (!(len = GetEnvironmentVariableA( "XODUS_SOCKET", unixPath, sizeof(unixPath) )) || len >= sizeof(unixPath))
+ {
+ if (!(len = GetEnvironmentVariableA( "WINE_HOST_XDG_RUNTIME_DIR", unixPath, sizeof(unixPath) )) || len >= sizeof(unixPath))
+ len = GetEnvironmentVariableA( "XDG_RUNTIME_DIR", unixPath, sizeof(unixPath) );
+ if (!len || len + strlen( "/xodus.sock" ) >= sizeof(unixPath)) return HRESULT_FROM_WIN32( ERROR_ENVVAR_NOT_FOUND );
+ strcat( unixPath, "/xodus.sock" );
+ }
+
+ TRACE( "socket %s.\n", debugstr_a( unixPath ) );
+
+ if (!(dosPath = wine_get_dos_file_name( unixPath ))) return HRESULT_FROM_WIN32( ERROR_PATH_NOT_FOUND );
+ len = WideCharToMultiByte( CP_ACP, 0, dosPath, -1, path, size, NULL, NULL );
+ HeapFree( GetProcessHeap(), 0, dosPath );
+ return len ? S_OK : HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+}
+
+static BOOL xodus_send( SOCKET s, const char *data, int size )
+{
+ int sent;
+
+ while (size > 0)
+ {
+ if ((sent = send( s, data, size, 0 )) <= 0) return FALSE;
+ data += sent;
+ size -= sent;
+ }
+ return TRUE;
+}
+
+static BOOL xodus_recv( SOCKET s, char *data, int size )
+{
+ int received;
+
+ while (size > 0)
+ {
+ if ((received = recv( s, data, size, 0 )) <= 0) return FALSE;
+ data += received;
+ size -= received;
+ }
+ return TRUE;
+}
+
+static HRESULT xodus_request( UINT16 type, const char *body, UINT16 size, char **response, UINT16 *responseSize )
+{
+ struct sockaddr_un addr = { .sun_family = AF_UNIX };
+ UINT32 magic = XODUS_XML_MAGIC;
+ struct sockaddr_in bridge = { 0 };
+ UINT16 responseType;
+ SOCKET s = INVALID_SOCKET;
+ char bridgePort[8], bridgeKey[65], *end;
+ char header[8];
+ DWORD portLen, keyLen;
+ unsigned long port;
+ BOOL useBridge;
+ WSADATA wsa;
+ HRESULT hr;
+
+ portLen = GetEnvironmentVariableA( "XODUS_BRIDGE_PORT", bridgePort, sizeof(bridgePort) );
+ keyLen = GetEnvironmentVariableA( "XODUS_BRIDGE_KEY", bridgeKey, sizeof(bridgeKey) );
+ useBridge = portLen || keyLen;
+ if (useBridge)
+ {
+ if (!portLen || portLen >= sizeof(bridgePort) || keyLen != 64) return E_INVALIDARG;
+ port = strtoul( bridgePort, &end, 10 );
+ if (*end || !port || port > 65535) return E_INVALIDARG;
+ bridge.sin_family = AF_INET;
+ bridge.sin_port = htons( (USHORT)port );
+ bridge.sin_addr.s_addr = htonl( 0x7f000001 );
+ }
+ else if (FAILED(hr = xodus_socket_path( addr.sun_path, sizeof(addr.sun_path) ))) return hr;
+ if (WSAStartup( MAKEWORD( 2, 2 ), &wsa )) return E_FAIL;
+
+ memcpy( header, &magic, 4 );
+ memcpy( header + 4, &type, 2 );
+ memcpy( header + 6, &size, 2 );
+
+ if (useBridge)
+ {
+ if ((s = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP )) == INVALID_SOCKET) goto error;
+ if (connect( s, (struct sockaddr *)&bridge, sizeof(bridge) )) goto error;
+ if (!xodus_send( s, bridgeKey, 64 )) goto error;
+ }
+ else
+ {
+ if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == INVALID_SOCKET) goto error;
+ if (connect( s, (struct sockaddr *)&addr, sizeof(addr) )) goto error;
+ }
+ if (!xodus_send( s, header, sizeof(header) ) || !xodus_send( s, body, size )) goto error;
+ if (!xodus_recv( s, header, sizeof(header) )) goto error;
+
+ memcpy( &responseType, header + 4, 2 );
+ memcpy( responseSize, header + 6, 2 );
+ if (memcmp( header, &magic, 4 ) || responseType != type + 1 || !*responseSize)
+ {
+ hr = E_UNEXPECTED;
+ goto done;
+ }
+ if (!(*response = calloc( 1, *responseSize + 1 )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto done;
+ }
+ if (!xodus_recv( s, *response, *responseSize ))
+ {
+ free( *response );
+ *response = NULL;
+ goto error;
+ }
+ hr = S_OK;
+ goto done;
+
+error:
+ hr = HRESULT_FROM_WIN32( WSAGetLastError() );
+ if (SUCCEEDED(hr)) hr = E_FAIL;
+done:
+ if (s != INVALID_SOCKET) closesocket( s );
+ WSACleanup();
+ return hr;
+}
+
+static char *xml_child_content( xmlNodePtr root, const char *name )
+{
+ xmlNodePtr child;
+ xmlChar *content;
+ char *value;
+
+ for (child = root ? root->children : NULL; child; child = child->next)
+ {
+ if (child->type != XML_ELEMENT_NODE || strcmp( (const char *)child->name, name )) continue;
+ if (!(content = xmlNodeGetContent( child ))) return NULL;
+ value = strdup( (const char *)content );
+ xmlFree( content );
+ return value;
+ }
+ return NULL;
+}
+
+HRESULT xodus_store_license_body( const char **product_ids, SIZE_T count, const char *nonce, char **body )
+{
+ xmlDocPtr doc;
+ xmlNodePtr root;
+ xmlChar *xml = NULL;
+ int size;
+ SIZE_T i;
+
+ *body = NULL;
+ if (!storeId || !*storeId) return E_GAME_MISSING_GAME_CONFIG;
+ if (!(doc = xmlNewDoc( BAD_CAST "1.0" ))) return E_OUTOFMEMORY;
+ root = xmlNewNode( NULL, BAD_CAST "StoreLicenseTokenRequest" );
+ if (!root) { xmlFreeDoc( doc ); return E_OUTOFMEMORY; }
+ xmlDocSetRootElement( doc, root );
+ xmlNewTextChild( root, NULL, BAD_CAST "ParentProductId", BAD_CAST storeId );
+ for (i = 0; i < count; i++)
+ xmlNewTextChild( root, NULL, BAD_CAST "ProductId", BAD_CAST product_ids[i] );
+ xmlNewTextChild( root, NULL, BAD_CAST "CustomDeveloperString", BAD_CAST nonce );
+ xmlDocDumpMemory( doc, &xml, &size );
+ xmlFreeDoc( doc );
+ if (!xml) return E_OUTOFMEMORY;
+ if (size <= 0 || size > 0xffff) { xmlFree( xml ); return E_INVALIDARG; }
+ *body = strdup( (char *)xml );
+ xmlFree( xml );
+ return *body ? S_OK : E_OUTOFMEMORY;
+}
+
+void xodus_store_license_note( const char *phase, HRESULT hr )
+{
+ auth_metadata( phase, NULL, hr, 0, FALSE, FALSE );
+}
+
+HRESULT xodus_store_license_xml( const char *request, SIZE_T request_size, char **token )
+{
+ char *response = NULL, *code = NULL, *end;
+ UINT16 response_size = 0;
+ xmlDocPtr doc = NULL;
+ xmlNodePtr root;
+ HRESULT hr;
+ unsigned long value;
+
+ *token = NULL;
+ if (request_size > 0xffff) return E_INVALIDARG;
+ /* Request 5 returns only a genuine Microsoft licensing token, request 6.
+ * Older services cannot provide it and must fail, never fabricate success. */
+ if (FAILED(hr = xodus_request( 5, request, request_size, &response, &response_size ))) goto cleanup;
+ if (!(doc = xmlReadMemory( response, response_size, NULL, NULL, XML_PARSE_NONET )))
+ { hr = E_UNEXPECTED; goto cleanup; }
+ root = xmlDocGetRootElement( doc );
+ if (!root || strcmp( (char *)root->name, "StoreLicenseTokenResponse" ) ||
+ !(code = xml_child_content( root, "Hresult" )))
+ { hr = E_UNEXPECTED; goto cleanup; }
+ value = strtoul( code, &end, 10 );
+ if (!*code || *end) { hr = E_UNEXPECTED; goto cleanup; }
+ hr = (HRESULT)(UINT32)value;
+ if (SUCCEEDED(hr))
+ {
+ *token = xml_child_content( root, "Token" );
+ if (!*token || !**token)
+ { free( *token ); *token = NULL; hr = E_UNEXPECTED; }
+ }
+cleanup:
+ auth_metadata( "store-license", NULL, hr, 0, FALSE, FALSE );
+ if (doc) xmlFreeDoc( doc );
+ if (response) { SecureZeroMemory( response, response_size ); free( response ); }
+ free( code );
+ return hr;
+}
+
+static HRESULT get_rps_tickets( BOOLEAN allowUi, char **userTicket, char **deviceTicket )
+{
+ /* The xodus platform's own MSA client id (the hosting app the service
+ * signs the account in with). Titles without an MSAAppId in
+ * MicrosoftGame.config (Deep Rock Galactic, RequiresXboxLive=false)
+ * still need a signed-in local user for GDK input routing, so their
+ * token is requested as the platform app, never as another title. */
+ static const char platform_client_id[] = "0000000040159362";
+ UINT16 responseSize = 0;
+ char *response = NULL;
+ xmlChar *body = NULL;
+ xmlNodePtr root;
+ xmlDocPtr doc;
+ int bodySize;
+ HRESULT hr;
+
+ TRACE( "allowUi %d, userTicket %p, deviceTicket %p, msaAppId %s, fullTrust %d.\n", allowUi, userTicket, deviceTicket, debugstr_a( msaAppId ), fullTrust );
+
+ if (!msaAppId && fullTrust) return E_GAME_MISSING_GAME_CONFIG;
+
+ if (!(doc = xmlNewDoc( BAD_CAST "1.0" ))) return E_OUTOFMEMORY;
+ root = xmlNewNode( NULL, BAD_CAST "MSATokenRequest" );
+ xmlDocSetRootElement( doc, root );
+ xmlNewTextChild( root, NULL, BAD_CAST "ClientId", BAD_CAST (msaAppId ? msaAppId : platform_client_id) );
+ xmlNewTextChild( root, NULL, BAD_CAST "AllowUi", BAD_CAST (allowUi ? "true" : "false") );
+ xmlNewTextChild( root, NULL, BAD_CAST "MSAFullTrust", BAD_CAST (fullTrust ? "true" : "false") );
+ xmlDocDumpMemory( doc, &body, &bodySize );
+ xmlFreeDoc( doc );
+ if (!body) return E_OUTOFMEMORY;
+ if (bodySize > 0xffff)
+ {
+ xmlFree( body );
+ return E_INVALIDARG;
+ }
+
+ hr = xodus_request( XODUS_MSA_TOKEN_REQUEST, (const char *)body, bodySize, &response, &responseSize );
+ xmlFree( body );
+ if (FAILED(hr))
+ {
+ ERR( "xodus-service request failed, hr %#lx. Is xodus-service running?\n", hr );
+ return hr;
+ }
+
+ if (!(doc = xmlReadMemory( response, responseSize, NULL, NULL, 0 )))
+ {
+ free( response );
+ return E_UNEXPECTED;
+ }
+ root = xmlDocGetRootElement( doc );
+ *userTicket = xml_child_content( root, "Token" );
+ *deviceTicket = xml_child_content( root, "DeviceRps" );
+ xmlFreeDoc( doc );
+ free( response );
+
+ if (!*userTicket || !**userTicket || !*deviceTicket || !**deviceTicket)
+ {
+ ERR( "xodus-service returned incomplete tickets.\n" );
+ free( *userTicket );
+ free( *deviceTicket );
+ *userTicket = *deviceTicket = NULL;
+ return E_UNEXPECTED;
+ }
+
+ TRACE( "got user and device tickets.\n" );
+ return S_OK;
+}
+
+static HRESULT device_auth( XUserHandle user, const char *deviceTicket, char **deviceToken )
+{
+ static const char template[] = "{\"RelyingParty\":\"http://auth.xboxlive.com\",\"TokenType\":\"JWT\",\"Properties\":{\"AuthMethod\":\"RPS\",\"SiteName\":\"user.auth.xboxlive.com\",\"ProofKey\":";
+ SIZE_T size = ARRAY_SIZE( template ) + strlen( user->proofKey ) + strlen( ",\"RpsTicket\":\"\"}}" ) + strlen( deviceTicket );
+ WCHAR header[116] = { 'S', 'i', 'g', 'n', 'a', 't', 'u', 'r', 'e', ':', ' ' };
+ IJsonObject *object = NULL;
+ const WCHAR *tokenBuffer;
+ HSTRING token = NULL;
+ BYTE *buffer = NULL;
+ char signature[104];
+ HRESULT hr;
+ char *body;
+
+ TRACE( "user %p, deviceTicket %p, deviceToken %p.\n", user, deviceTicket, deviceToken );
+
+ if (!(body = calloc( 1, size ))) return E_OUTOFMEMORY;
+ strcpy( body, template );
+ strcat( body, user->proofKey );
+ strcat( body, ",\"RpsTicket\":\"" );
+ strcat( body, deviceTicket );
+ strcat( body, "\"}}" );
+ if (FAILED(hr = IUser_GetSignature( &user->IUser_iface, 1, "POST", "https://device.auth.xboxlive.com/device/authenticate", "", size - 1, body, signature ))) goto cleanup;
+ if (!MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, signature, 104, header + 11, 104 )) goto error;
+ if (FAILED(hr = http_request( L"POST", L"https://device.auth.xboxlive.com/device/authenticate", body, header, ACCEPT_JSON, &buffer, &size ))) goto cleanup;
+ if (FAILED(hr = parse_json( (char *)buffer, size, &object ))) goto cleanup;
+ if (FAILED(hr = get_json_string( object, L"Token", &token ))) goto cleanup;
+ tokenBuffer = WindowsGetStringRawBuffer( token, NULL );
+ if (!(size = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, tokenBuffer, -1, NULL, 0, NULL, NULL ))) goto error;
+ if (!(*deviceToken = calloc( 1, size )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ if (!WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, tokenBuffer, -1, *deviceToken, size, NULL, NULL )) goto error;
+ goto cleanup;
+
+error:
+ hr = HRESULT_FROM_WIN32( GetLastError() );
+cleanup:
+ if (FAILED(hr) && *deviceToken) free( *deviceToken );
+ if (object) IJsonObject_Release( object );
+ if (token) WindowsDeleteString( token );
+ if (buffer) free( buffer );
+ free( body );
+ return hr;
+}
+
+static HRESULT xsts_authorize( XUserHandle user, const char *relyingParty, BOOL title, char **auth );
+static char *hstring_to_utf8( HSTRING string );
+static WCHAR *utf8_to_wide( const char *string );
+
+static HRESULT sisu_auth( XUserHandle user, const char *userTicket, const char *deviceToken, WCHAR **auth )
+{
+ static const char template[] = "{\"Sandbox\":\"RETAIL\",\"UseModernGamertag\":true,\"DeviceToken\":\"";
+ SIZE_T size = ARRAY_SIZE( template ) + strlen( deviceToken ) + strlen( "\",\"AccessToken\":\"\"}" ) + strlen( userTicket );
+ HSTRING authToken = NULL, gtg = NULL, mgs = NULL, mgt = NULL, umg = NULL, userToken = NULL, xid = NULL, titleToken = NULL;
+ IJsonObject *authObject = NULL, *claims = NULL, *identity = NULL, *object = NULL, *userObject = NULL, *titleObject = NULL;
+ WCHAR header[116] = { 'S', 'i', 'g', 'n', 'a', 't', 'u', 'r', 'e', ':', ' ' };
+ char *body, signature[104];
+ const WCHAR *stringBuffer;
+ IJsonArray *xui = NULL;
+ BYTE *buffer = NULL;
+ HRESULT hr;
+
+ TRACE( "user %p, userTicket %p, deviceToken %p, auth %p.\n", user, userTicket, deviceToken, auth );
+
+ if (!(body = calloc( 1, size ))) return E_OUTOFMEMORY;
+ strcpy( body, template );
+ strcat( body, deviceToken );
+ strcat( body, "\",\"AccessToken\":\"" );
+ strcat( body, userTicket );
+ strcat( body, "\"}" );
+ if (FAILED(hr = IUser_GetSignature( &user->IUser_iface, 1, "POST", "https://sisu.xboxlive.com/authorize", "", size - 1, body, signature ))) goto cleanup;
+ if (!MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, signature, 104, header + 11, 104 )) goto error;
+ if (FAILED(hr = http_request( L"POST", L"https://sisu.xboxlive.com/authorize", body, header, ACCEPT_JSON, &buffer, &size ))) goto cleanup;
+
+ if (FAILED(hr = parse_json( (char *)buffer, size, &object ))) goto cleanup;
+ if (FAILED(hr = get_json_object( object, L"UserToken", &userObject ))) goto cleanup;
+ if (FAILED(hr = get_json_string( userObject, L"Token", &userToken ))) goto cleanup;
+ stringBuffer = WindowsGetStringRawBuffer( userToken, NULL );
+ if (!(size = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, stringBuffer, -1, NULL, 0, NULL, NULL ))) goto error;
+ if (!(user->userToken = calloc( 1, size )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ if (!WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, stringBuffer, -1, user->userToken, size, NULL, NULL )) goto error;
+ if (SUCCEEDED(get_json_object( object, L"TitleToken", &titleObject )) && SUCCEEDED(get_json_string( titleObject, L"Token", &titleToken )))
+ {
+ free( user->titleToken );
+ user->titleToken = hstring_to_utf8( titleToken );
+ }
+ if (FAILED(hr = get_json_object( object, L"AuthorizationToken", &authObject ))) goto cleanup;
+ if (FAILED(hr = get_json_object( authObject, L"DisplayClaims", &claims ))) goto cleanup;
+ if (FAILED(hr = get_json_array( claims, L"xui", &xui ))) goto cleanup;
+ if (FAILED(hr = IJsonArray_GetObjectAt( xui, 0, &identity ))) goto cleanup;
+ if (FAILED(hr = get_json_string( identity, L"xid", &xid ))) goto cleanup;
+ stringBuffer = WindowsGetStringRawBuffer( xid, NULL );
+ user->xuid = wcstoull( stringBuffer, NULL, 10 );
+ if (FAILED(hr = get_json_string( identity, L"gtg", >g ))) goto cleanup;
+ stringBuffer = WindowsGetStringRawBuffer( gtg, NULL );
+ if (!WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, stringBuffer, -1, user->gamertag, 16, NULL, NULL )) goto error;
+ if (FAILED(hr = get_json_string( identity, L"mgt", &mgt ))) goto cleanup;
+ stringBuffer = WindowsGetStringRawBuffer( mgt, NULL );
+ if (!WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, stringBuffer, -1, user->modernGamertag, 97, NULL, NULL )) goto error;
+ if (SUCCEEDED(hr = get_json_string( identity, L"mgs", &mgs )))
+ {
+ stringBuffer = WindowsGetStringRawBuffer( mgs, NULL );
+ if (!WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, stringBuffer, -1, user->modernGamertagSuffix, 15, NULL, NULL )) goto error;
+ }
+ else if (hr != WEB_E_JSON_VALUE_NOT_FOUND) goto cleanup;
+ if (FAILED(hr = get_json_string( identity, L"umg", &umg ))) goto cleanup;
+ stringBuffer = WindowsGetStringRawBuffer( umg, NULL );
+ if (!WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, stringBuffer, -1, user->uniqueModernGamertag, 101, NULL, NULL )) goto error;
+ if (FAILED(hr = get_json_string( authObject, L"Token", &authToken ))) goto cleanup;
+ stringBuffer = WindowsGetStringRawBuffer( authToken, NULL );
+ if (!(*auth = calloc( wcslen( L"Authorization: XBL3.0 x=-;" ) + wcslen( stringBuffer ) + 1, sizeof(WCHAR) )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ wcscpy( *auth, L"Authorization: XBL3.0 x=-;" );
+ wcscat( *auth, stringBuffer );
+ goto cleanup;
+
+error:
+ hr = HRESULT_FROM_WIN32( GetLastError() );
+cleanup:
+ auth_metadata( "sisu", user, hr, 0, TRUE, !!user->titleToken );
+ if (authObject) IJsonObject_Release( authObject );
+ if (userObject) IJsonObject_Release( userObject );
+ if (titleObject) IJsonObject_Release( titleObject );
+ if (titleToken) WindowsDeleteString( titleToken );
+ if (authToken) WindowsDeleteString( authToken );
+ if (userToken) WindowsDeleteString( userToken );
+ if (identity) IJsonObject_Release( identity );
+ if (claims) IJsonObject_Release( claims );
+ if (object) IJsonObject_Release( object );
+ if (gtg) WindowsDeleteString( gtg );
+ if (mgs) WindowsDeleteString( mgs );
+ if (mgt) WindowsDeleteString( mgt );
+ if (umg) WindowsDeleteString( umg );
+ if (xid) WindowsDeleteString( xid );
+ if (xui) IJsonArray_Release( xui );
+ if (buffer) free( buffer );
+ free( body );
+ return hr;
+}
+
+static HRESULT load_endpoints( XUserHandle user, BYTE *buffer, SIZE_T size )
+{
+ IJsonObject *payload = NULL, *tmpObject = NULL;
+ IJsonArray *jsonEndpoints = NULL, *jsonPolicies = NULL;
+ IVector_IJsonValue *jsonEndpointsVector = NULL, *jsonPoliciesVector = NULL;
+ struct policy *policyCursor = NULL;
+ struct endpoint *endpointCursor = NULL;
+ DOUBLE jsonNumber;
+ UINT32 arraySize;
+ HSTRING hostType = NULL;
+ const WCHAR* hostTypeRaw = NULL;
+ HRESULT hr = S_OK;
+
+ TRACE( "user %p, buffer %p, size %Iu \n", user, buffer, size );
+
+ if (FAILED(hr = parse_json((char *)buffer, size, &payload))) return hr;
+ if (FAILED(hr = get_json_array(payload, L"EndPoints", &jsonEndpoints))) goto cleanup;
+ if (FAILED(get_json_array(payload, L"SignaturePolicies", &jsonPolicies))) jsonPolicies = NULL;
+
+ if (jsonPolicies) {
+ if (FAILED(hr = IJsonArray_QueryInterface(jsonPolicies, &IID_IVector_IJsonValue, (void **)&jsonPoliciesVector))) goto cleanup;
+ if (FAILED(hr = IVector_IJsonValue_get_Size(jsonPoliciesVector, &arraySize))) goto cleanup;
+
+ if (!(policyCursor = realloc(user->policies, sizeof(struct policy) * (user->policiesLen + arraySize)))) {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ user->policies = policyCursor;
+ policyCursor = user->policies + user->policiesLen;
+ user->policiesLen = user->policiesLen + arraySize;
+
+ for (UINT32 i = 0; i < arraySize; i++) {
+ if (FAILED(hr = IJsonArray_GetObjectAt(jsonPolicies, i, &tmpObject))) goto cleanup;
+
+ if (FAILED(hr = get_json_number(tmpObject, L"Version", &jsonNumber))) goto cleanup;
+ (*(policyCursor + i)).version = (UINT32)jsonNumber;
+ if (FAILED(hr = get_json_number(tmpObject, L"MaxBodyBytes", &jsonNumber))) goto cleanup;
+ (*(policyCursor + i)).maxBodyBytes = (UINT32)jsonNumber;
+
+ IJsonObject_Release(tmpObject);
+ tmpObject = NULL;
+ }
+ }
+
+ if (FAILED(hr = IJsonArray_QueryInterface(jsonEndpoints, &IID_IVector_IJsonValue, (void **)&jsonEndpointsVector))) goto cleanup;
+ if (FAILED(hr = IVector_IJsonValue_get_Size(jsonEndpointsVector, &arraySize))) goto cleanup;
+
+ if (!(endpointCursor = realloc(user->endpoints, sizeof(struct endpoint) * (user->endpointsLen + arraySize)))) {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ user->endpoints = endpointCursor;
+ endpointCursor = user->endpoints + user->endpointsLen;
+ user->endpointsLen = user->endpointsLen + arraySize;
+ memset(endpointCursor, 0, sizeof(struct endpoint) * arraySize);
+
+ for (UINT32 i = 0; i < arraySize; i++) {
+ if (FAILED(hr = IJsonArray_GetObjectAt(jsonEndpoints, i, &tmpObject))) goto cleanup;
+
+ if (FAILED(hr = get_json_string(tmpObject, L"Protocol", &(endpointCursor + i)->protocol))) goto cleanup;
+ if (FAILED(hr = get_json_string(tmpObject, L"Host", &(endpointCursor + i)->host) )) goto cleanup;
+ if (FAILED(get_json_string(tmpObject, L"Path", &(endpointCursor + i)->path))) (endpointCursor + i)->path = NULL;
+
+ if (FAILED(get_json_string(tmpObject, L"RelyingParty", &(endpointCursor + i)->relyingParty))) (endpointCursor + i)->relyingParty = NULL;
+ if (FAILED(get_json_string(tmpObject, L"TokenType", &(endpointCursor + i)->tokenType))) (endpointCursor + i)->tokenType = NULL;
+ if (SUCCEEDED(get_json_number(tmpObject, L"SignaturePolicyIndex", &jsonNumber)) && policyCursor && jsonNumber < (user->policiesLen - (policyCursor - user->policies))) {
+ (endpointCursor + i)->policy = policyCursor + (UINT32)jsonNumber;
+ } else {
+ (endpointCursor + i)->policy = NULL;
+ }
+ if (SUCCEEDED(get_json_string(tmpObject, L"HostType", &hostType))) {
+ hostTypeRaw = WindowsGetStringRawBuffer(hostType, NULL);
+ (endpointCursor + i)->wildcard = wcscmp(hostTypeRaw, L"wildcard") == 0;
+ WindowsDeleteString(hostType);
+ hostType = NULL;
+ } else {
+ (endpointCursor + i)->wildcard = FALSE;
+ }
+
+ TRACE( "endpoint %s://%s%s rp %s type %s.\n", debugstr_w( WindowsGetStringRawBuffer( (endpointCursor + i)->protocol, NULL ) ),
+ debugstr_w( WindowsGetStringRawBuffer( (endpointCursor + i)->host, NULL ) ), debugstr_w( WindowsGetStringRawBuffer( (endpointCursor + i)->path, NULL ) ),
+ debugstr_w( WindowsGetStringRawBuffer( (endpointCursor + i)->relyingParty, NULL ) ), debugstr_w( WindowsGetStringRawBuffer( (endpointCursor + i)->tokenType, NULL ) ) );
+ IJsonObject_Release(tmpObject);
+ tmpObject = NULL;
+ }
+
+cleanup:
+ if (jsonPoliciesVector) IVector_IJsonValue_Release(jsonPoliciesVector);
+ if (jsonEndpointsVector) IVector_IJsonValue_Release(jsonEndpointsVector);
+ if (jsonEndpoints) IJsonArray_Release(jsonEndpoints);
+ if (tmpObject) IJsonObject_Release(tmpObject);
+ if (jsonPolicies) IJsonArray_Release(jsonPolicies);
+ if (payload) IJsonObject_Release(payload);
+
+ return hr;
+}
+
+static HRESULT WINAPI user_Initialize( IUser *iface, const XUserAddOptions options )
+{
+ static char proofKeyTemplate[] = "{\"alg\":\"ES256\",\"crv\":\"P-256\",\"kty\":\"EC\",\"use\":\"sig\",\"x\":\"";
+ static const SIZE_T proofKeySize = ARRAY_SIZE( proofKeyTemplate ) + sizeof( "\",\"y\":\"\"}" ) + 85;
+ BYTE blob[sizeof(BCRYPT_ECCKEY_BLOB) + 64], *currentBuffer = NULL, *defaultBuffer = NULL;
+ char *deviceTicket = NULL, *deviceToken = NULL, *userTicket = NULL, *x, *y;
+ struct XUser *impl = impl_from_IUser( iface );
+ WCHAR *auth = NULL;
+ NTSTATUS status;
+ SIZE_T size;
+ ULONG dummy;
+ HRESULT hr;
+
+ TRACE( "iface %p.\n", iface );
+
+ /* generate signing key pair and convert public key to jwk */
+ if (!NT_SUCCESS(status = BCryptGenerateKeyPair( BCRYPT_ECDSA_P256_ALG_HANDLE, &impl->key, 256, 0 ))) return HRESULT_FROM_NT( status );
+ if (!NT_SUCCESS(status = BCryptFinalizeKeyPair( impl->key, 0 ))) return HRESULT_FROM_NT( status );
+ if (!NT_SUCCESS(status = BCryptExportKey( impl->key, NULL, BCRYPT_ECCPUBLIC_BLOB, blob, sizeof(blob), &dummy, 0 ))) return HRESULT_FROM_NT( status );
+ if (!(impl->proofKey = calloc( 1, proofKeySize ))) return E_OUTOFMEMORY;
+ x = impl->proofKey + ARRAY_SIZE( proofKeyTemplate ) - 1;
+ y = x + 43 + strlen( "\",\"y\":\"" );
+ strcpy( impl->proofKey, proofKeyTemplate );
+ if (FAILED(hr = encode_base64_url( 32, blob + sizeof(BCRYPT_ECCKEY_BLOB), 43, x, FALSE ))) return hr;
+ strcat( impl->proofKey, "\",\"y\":\"" );
+ if (FAILED(hr = encode_base64_url( 32, blob + sizeof(BCRYPT_ECCKEY_BLOB) + 32, 43, y, FALSE ))) return hr;
+ strcat( impl->proofKey, "\"}" );
+
+ if (FAILED(hr = http_request( L"GET", L"https://title.mgt.xboxlive.com/titles/default/endpoints?type=1", NULL, NULL, ACCEPT_JSON, &defaultBuffer, &size ))) return hr;
+ if (FAILED(hr = load_endpoints( impl, defaultBuffer, size ))) goto cleanup;
+ if (FAILED(hr = get_rps_tickets( options & XUserAddOptions_AddDefaultUserAllowingUI, &userTicket, &deviceTicket ))) goto cleanup;
+ if (FAILED(hr = device_auth( impl, deviceTicket, &deviceToken ))) goto cleanup;
+ free( impl->deviceToken );
+ if (!(impl->deviceToken = strdup( deviceToken )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ if (FAILED(hr = sisu_auth( impl, userTicket, deviceToken, &auth ))) goto cleanup;
+ if (FAILED(hr = http_request( L"GET", L"https://title.mgt.xboxlive.com/titles/current/endpoints", NULL, auth, ACCEPT_JSON, ¤tBuffer, &size ))) goto cleanup;
+ if (FAILED(hr = load_endpoints( impl, currentBuffer, size ))) goto cleanup;
+
+cleanup:
+ if (currentBuffer) free( currentBuffer );
+ if (defaultBuffer) free( defaultBuffer );
+ if (deviceTicket) free( deviceTicket );
+ if (deviceToken) free( deviceToken );
+ if (userTicket) free( userTicket );
+ if (auth) free( auth );
+ return hr;
+}
+
+static BOOLEAN match_wildcard( const WCHAR *pat, UINT32 patLen, const WCHAR *inp, UINT32 inpLen )
+{
+ UINT32 lastMatch = -1, lastWildcard = -1, patOff = 0, inpOff = 0;
+
+ TRACE( "pat %s, inp %s.\n", debugstr_wn( pat, patLen ), debugstr_wn( inp, inpLen ) );
+
+ while (inpOff < inpLen && patOff < patLen)
+ {
+ if (pat[patOff] == '*')
+ {
+ lastWildcard = patOff++;
+ lastMatch = inpOff;
+ }
+ else if (pat[patOff] == '?' || pat[patOff] == inp[inpOff])
+ {
+ patOff++;
+ inpOff++;
+ }
+ else if (lastWildcard != -1)
+ {
+ patOff = lastWildcard + 1;
+ inpOff = ++lastMatch;
+ }
+ else return FALSE;
+ }
+
+ return inpOff == inpLen && patOff == patLen;
+}
+
+static HRESULT WINAPI user_GetEndpointInfo( IUser *iface, const char *url, struct endpoint *info )
+{
+ URL_COMPONENTSW uc = { .dwStructSize = sizeof(URL_COMPONENTSW), .dwSchemeLength = -1, .dwHostNameLength = -1, .dwUrlPathLength = -1 };
+ struct XUser *impl = impl_from_IUser( iface );
+ struct endpoint *match = NULL;
+ INT32 urlWSize;
+ WCHAR *urlW;
+
+ TRACE( "iface %p, url %s, info %p.\n", iface, debugstr_a( url ), info );
+
+ if (!(urlWSize = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, url, -1, NULL, 0 ))) return HRESULT_FROM_WIN32( GetLastError() );
+ if (!(urlW = calloc( urlWSize, sizeof(WCHAR) ))) return E_OUTOFMEMORY;
+ if (!MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, url, -1, urlW, urlWSize )) goto error;
+ if (!InternetCrackUrlW( urlW, 0, 0, &uc )) goto error;
+
+ for (UINT32 i = 0; i < impl->endpointsLen; i++)
+ {
+ UINT32 protocolLen, hostLen, pathLen;
+ const WCHAR *protocol = WindowsGetStringRawBuffer( impl->endpoints[i].protocol, &protocolLen );
+ const WCHAR *host = WindowsGetStringRawBuffer( impl->endpoints[i].host, &hostLen );
+ const WCHAR *path = WindowsGetStringRawBuffer( impl->endpoints[i].path, &pathLen );
+ if (uc.dwSchemeLength != protocolLen || wcsnicmp( uc.lpszScheme, protocol, protocolLen )) continue;
+ if (impl->endpoints[i].path && (uc.dwUrlPathLength < pathLen || wcsncmp( uc.lpszUrlPath, path, pathLen ))) continue;
+ if (impl->endpoints[i].wildcard)
+ {
+ if (!match && match_wildcard( host, hostLen, uc.lpszHostName, uc.dwHostNameLength )) match = &impl->endpoints[i];
+ continue;
+ }
+ if (uc.dwHostNameLength != hostLen || wcsnicmp( uc.lpszHostName, host, hostLen )) continue;
+ match = &impl->endpoints[i];
+ break;
+ }
+ free( urlW );
+ if (!match) return E_FAIL;
+ *info = *match;
+ return S_OK;
+
+error:
+ free(urlW);
+ return HRESULT_FROM_WIN32( GetLastError() );
+}
+
+static HRESULT WINAPI user_GetAuthorization( IUser *iface, const WCHAR *relyingParty, WCHAR **auth )
+{
+ struct XUser *impl = impl_from_IUser( iface );
+ char *relyingPartyA, *authA = NULL;
+ SIZE_T size;
+ HRESULT hr;
+
+ TRACE( "iface %p, relyingParty %s, auth %p.\n", iface, debugstr_w( relyingParty ), auth );
+
+ if (!(size = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, relyingParty, -1, NULL, 0, NULL, NULL ))) return HRESULT_FROM_WIN32( GetLastError() );
+ if (!(relyingPartyA = calloc( 1, size ))) return E_OUTOFMEMORY;
+ WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, relyingParty, -1, relyingPartyA, size, NULL, NULL );
+ if (SUCCEEDED(hr = xsts_authorize( impl, relyingPartyA, TRUE, &authA )) && !(*auth = utf8_to_wide( authA ))) hr = E_OUTOFMEMORY;
+ free( relyingPartyA );
+ free( authA );
+ return hr;
+}
+
+static HRESULT WINAPI user_GetSignature( IUser *iface, UINT32 version, const char *method, const char *url, const char *auth, UINT32 bodySize, const void *body, char signature[104] )
+{
+ BYTE hash[32], rawSignature[76] = { (version >> 24) & 0xff, (version >> 16) & 0xff, (version >> 8) & 0xff, version & 0xff };
+ struct XUser *impl = impl_from_IUser( iface );
+ const char *pathAndQuery = "/", *scheme;
+ ULONG dataBufferSize, dummy, pathLength;
+ BYTE *dataBuffer, *ptr;
+ FILETIME timestamp;
+ NTSTATUS status;
+ HRESULT hr;
+
+ TRACE( "iface %p, version %d, method %s, url %s, auth %p, bodySize %d, body %p, signature %p.\n", iface, version, debugstr_a( method ), debugstr_a( url ), auth, bodySize, body, signature );
+
+ if (!url || !(scheme = strstr( url, "://" ))) return E_INVALIDARG;
+ if (strchr( scheme + 3, '/' )) pathAndQuery = strchr( scheme + 3, '/' );
+ pathLength = strlen( pathAndQuery );
+ dataBufferSize = 18 + strlen( method ) + pathLength + strlen( auth ) + bodySize;
+
+ /* filetime */
+ GetSystemTimeAsFileTime( ×tamp );
+ rawSignature[4] = (timestamp.dwHighDateTime >> 24) & 0xff;
+ rawSignature[5] = (timestamp.dwHighDateTime >> 16) & 0xff;
+ rawSignature[6] = (timestamp.dwHighDateTime >> 8 ) & 0xff;
+ rawSignature[7] = timestamp.dwHighDateTime & 0xff;
+ rawSignature[8] = (timestamp.dwLowDateTime >> 24) & 0xff;
+ rawSignature[9] = (timestamp.dwLowDateTime >> 16) & 0xff;
+ rawSignature[10] = (timestamp.dwLowDateTime >> 8 ) & 0xff;
+ rawSignature[11] = timestamp.dwLowDateTime & 0xff;
+
+ /* signature content */
+ if (!(dataBuffer = calloc( 1, dataBufferSize ) )) return E_OUTOFMEMORY;
+ memcpy( dataBuffer, rawSignature, 4 );
+ memcpy( dataBuffer + 5, rawSignature + 4, 8 );
+ ptr = dataBuffer + 14;
+ while (*method) *(ptr++) = toupper( *(method++) );
+ memcpy( ptr + 1, pathAndQuery, pathLength );
+ ptr += pathLength + 2;
+ memcpy( ptr, auth, strlen( auth ) );
+ ptr += strlen( auth ) + 1;
+ memcpy( ptr, body, bodySize );
+
+ /* sign hash of signature content */
+ if (!NT_SUCCESS(status = BCryptHash( BCRYPT_SHA256_ALG_HANDLE, NULL, 0, dataBuffer, dataBufferSize, hash, 32 ))) goto error;
+ if (!NT_SUCCESS(status = BCryptSignHash( impl->key, NULL, hash, 32, rawSignature + 12, 64, &dummy, 0 ))) goto error;
+
+ hr = encode_base64( 76, rawSignature, 104, signature, TRUE );
+ goto cleanup;
+
+error:
+ hr = HRESULT_FROM_NT( status );
+cleanup:
+ free( dataBuffer );
+ return hr;
+}
+
+static const struct IUserVtbl user_vtbl =
+{
+ NULL,
+ user_AddRef,
+ user_Release,
+ /* IUser methods */
+ user_Initialize,
+ user_GetEndpointInfo,
+ user_GetAuthorization,
+ user_GetSignature,
+};
+
struct x_user
{
IXUserImpl6 IXUserImpl6_iface;
@@ -83,74 +990,215 @@ static ULONG WINAPI x_user_Release( IXUserImpl6 *iface )
static HRESULT WINAPI x_user_XUserDuplicateHandle( IXUserImpl6 *iface, XUserHandle handle, XUserHandle *duplicatedHandle )
{
- FIXME( "iface %p, handle %p, duplicatedHandle %p stub!\n", iface, handle, duplicatedHandle );
- return E_NOTIMPL;
+ TRACE( "iface %p, handle %p, duplicatedHandle %p.\n", iface, handle, duplicatedHandle );
+ if (!duplicatedHandle) return E_INVALIDARG;
+ *duplicatedHandle = NULL;
+ if (!handle) return E_INVALIDARG;
+ IUser_AddRef( &handle->IUser_iface );
+ *duplicatedHandle = handle;
+ return S_OK;
}
static void WINAPI x_user_XUserCloseHandle( IXUserImpl6 *iface, XUserHandle user )
{
- FIXME( "iface %p, user %p stub!\n", iface, user );
+ TRACE( "iface %p, user %p.\n", iface, user );
+ if (user) IUser_Release( &user->IUser_iface );
}
static INT32 WINAPI x_user_XUserCompare( IXUserImpl6 *iface, XUserHandle user1, XUserHandle user2 )
{
- FIXME( "iface %p, user1 %p, user2 %p stub!\n", iface, user1, user2 );
- return E_NOTIMPL;
+ UINT64 a = user1 ? user1->xuid : 0, b = user2 ? user2->xuid : 0;
+ TRACE( "iface %p, user1 %p, user2 %p.\n", iface, user1, user2 );
+ if (user1 == user2) return 0;
+ return a < b ? -1 : a > b ? 1 : 0;
}
static HRESULT WINAPI x_user_XUserGetMaxUsers( IXUserImpl6 *iface, UINT32 *maxUsers )
{
TRACE( "iface %p, maxUsers %p.\n", iface, maxUsers );
+ if (!maxUsers) return E_INVALIDARG;
*maxUsers = 1;
return S_OK;
}
+struct XUserAddContext
+{
+ XUserAddOptions options;
+ XUserHandle user;
+};
+
+static struct XUser *signed_in_user;
+static CRITICAL_SECTION signed_in_section;
+static CRITICAL_SECTION_DEBUG signed_in_section_debug =
+{
+ 0, 0, &signed_in_section,
+ { &signed_in_section_debug.ProcessLocksList, &signed_in_section_debug.ProcessLocksList },
+ 0, 0, { (DWORD_PTR)(__FILE__ ": signed_in_section") }
+};
+static CRITICAL_SECTION signed_in_section = { &signed_in_section_debug, -1, 0, 0, 0, 0 };
+
+static void set_signed_in_user( struct XUser *user )
+{
+ EnterCriticalSection( &signed_in_section );
+ IUser_AddRef( &user->IUser_iface );
+ if (signed_in_user) IUser_Release( &signed_in_user->IUser_iface );
+ signed_in_user = user;
+ LeaveCriticalSection( &signed_in_section );
+}
+
+static HRESULT find_signed_in_user( UINT64 xuid, UINT64 localId, XUserHandle *handle )
+{
+ HRESULT hr = E_GAMEUSER_USER_NOT_FOUND;
+ if (!handle) return E_INVALIDARG;
+ *handle = NULL;
+ EnterCriticalSection( &signed_in_section );
+ if (signed_in_user && ((xuid && signed_in_user->xuid == xuid) || (localId && localId == 1)))
+ {
+ IUser_AddRef( &signed_in_user->IUser_iface );
+ *handle = signed_in_user;
+ hr = S_OK;
+ }
+ LeaveCriticalSection( &signed_in_section );
+ return hr;
+}
+
+static HRESULT WINAPI XUserAddProvider( XAsyncOp op, const XAsyncProviderData *data )
+{
+ struct XUserAddContext *context;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "op %d, data %p.\n", op, data );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ context = (struct XUserAddContext *)data->context;
+
+ switch (op)
+ {
+ case XAsyncOp_Begin:
+ hr = IXThreadingImpl_XAsyncSchedule( xthreading, data->async, 0 );
+ break;
+
+ case XAsyncOp_GetResult:
+ memcpy( data->buffer, &context->user, sizeof(XUserHandle) );
+ break;
+
+ case XAsyncOp_DoWork:
+ if (!(context->user = calloc( 1, sizeof(*context->user) )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto complete;
+ }
+ context->user->IUser_iface.lpVtbl = &user_vtbl;
+ context->user->ref = 1;
+ InitializeCriticalSection( &context->user->deviceAuthSection );
+ {
+ HRESULT init = CoInitializeEx( NULL, COINIT_MULTITHREADED );
+ hr = IUser_Initialize( &context->user->IUser_iface, context->options );
+ if (SUCCEEDED(init)) CoUninitialize();
+ }
+
+ complete:
+ if (SUCCEEDED(hr)) set_signed_in_user( context->user );
+ if (FAILED(hr) && context->user) IUser_Release( &context->user->IUser_iface );
+ IXThreadingImpl_XAsyncComplete( xthreading, data->async, hr, SUCCEEDED(hr) ? sizeof(XUserHandle) : 0 );
+ hr = S_OK;
+ break;
+
+ case XAsyncOp_Cleanup:
+ free( context );
+ break;
+
+ case XAsyncOp_Cancel:
+ break;
+ }
+
+ IXThreadingImpl_Release( xthreading );
+ return hr;
+}
+
static HRESULT WINAPI x_user_XUserAddAsync( IXUserImpl6 *iface, XUserAddOptions options, XAsyncBlock *async )
{
- FIXME( "iface %p, options %d, async %p stub!\n", iface, options, async );
- return E_NOTIMPL;
+ struct XUserAddContext *context;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "iface %p, options %d, async %p.\n", iface, options, async );
+
+ if (!async) return E_POINTER;
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ if (!(context = calloc( 1, sizeof(*context) )))
+ {
+ IXThreadingImpl_Release( xthreading );
+ return E_OUTOFMEMORY;
+ }
+
+ context->options = options;
+ hr = IXThreadingImpl_XAsyncBegin( xthreading, async, context, NULL, "XUserAddAsync", XUserAddProvider );
+ IXThreadingImpl_Release( xthreading );
+ if (FAILED(hr)) free( context );
+ return hr;
}
static HRESULT WINAPI x_user_XUserAddResult( IXUserImpl6 *iface, XAsyncBlock *async, XUserHandle *newUser )
{
- FIXME( "iface %p, async %p, newUser %p stub!\n", iface, async, newUser );
- return E_NOTIMPL;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "iface %p, async %p, newUser %p.\n", iface, async, newUser );
+
+ if (!async || !newUser) return E_POINTER;
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResult( xthreading, async, NULL, sizeof(*newUser), newUser, NULL );
+ IXThreadingImpl_Release( xthreading );
+ return hr;
}
static HRESULT WINAPI x_user_XUserGetLocalId( IXUserImpl6 *iface, XUserHandle user, XUserLocalId *userLocalId )
{
- FIXME( "iface %p, user %p, userLocalId %p stub!\n", iface, user, userLocalId );
- return E_NOTIMPL;
+ TRACE( "iface %p, user %p, userLocalId %p.\n", iface, user, userLocalId );
+ if (!user || !userLocalId) return E_INVALIDARG;
+ userLocalId->value = 1;
+ return S_OK;
}
static HRESULT WINAPI x_user_XUserFindUserByLocalId( IXUserImpl6 *iface, XUserLocalId userLocalId, XUserHandle *handle )
{
- FIXME( "iface %p, userLocalId %p, handle %p stub!\n", iface, &userLocalId, handle );
- return E_NOTIMPL;
+ TRACE( "iface %p, userLocalId %llu, handle %p.\n", iface, userLocalId.value, handle );
+ return find_signed_in_user( 0, userLocalId.value, handle );
}
static HRESULT WINAPI x_user_XUserGetId( IXUserImpl6 *iface, XUserHandle user, UINT64 *userId )
{
- FIXME( "iface %p, user %p, userId %p stub!\n", iface, user, userId );
- return E_NOTIMPL;
+ TRACE( "iface %p, user %p, userId %p.\n", iface, user, userId );
+ if (!user || !userId) return E_INVALIDARG;
+ *userId = user->xuid;
+ return S_OK;
}
static HRESULT WINAPI x_user_XUserFindUserById( IXUserImpl6 *iface, UINT64 userId, XUserHandle *handle )
{
- FIXME( "iface %p, userId %llu, handle %p stub!\n", iface, userId, handle );
- return E_NOTIMPL;
+ TRACE( "iface %p, userId %llu, handle %p.\n", iface, userId, handle );
+ return find_signed_in_user( userId, 0, handle );
}
static HRESULT WINAPI x_user_XUserGetIsGuest( IXUserImpl6 *iface, XUserHandle user, BOOLEAN *isGuest )
{
- FIXME( "iface %p, user %p, isGuest %p stub!\n", iface, user, isGuest );
- return E_NOTIMPL;
+ TRACE( "iface %p, user %p, isGuest %p.\n", iface, user, isGuest );
+ if (!user || !isGuest) return E_INVALIDARG;
+ /* This provider creates authenticated Xbox users, not guest users. */
+ *isGuest = FALSE;
+ return S_OK;
}
static HRESULT WINAPI x_user_XUserGetState( IXUserImpl6 *iface, XUserHandle user, XUserState *state )
{
- FIXME( "iface %p, user %p, state %p stub!\n", iface, user, state );
- return E_NOTIMPL;
+ TRACE( "iface %p, user %p, state %p.\n", iface, user, state );
+ if (!user || !state) return E_INVALIDARG;
+ /* SignedIn describes platform identity, not network connectivity. Preserve
+ * the PR#28 IUser handle and its real identity/token/cloud-save data. */
+ *state = user->xuid ? XUserState_SignedIn : XUserState_SignedOut;
+ return S_OK;
}
static HRESULT WINAPI __PADDING__( IXUserImpl6 *iface )
@@ -159,22 +1207,171 @@ static HRESULT WINAPI __PADDING__( IXUserImpl6 *iface )
return E_NOTIMPL;
}
+struct XUserGetGamerPictureContext
+{
+ XUserHandle user;
+ XUserGamerPictureSize pictureSize;
+ SIZE_T bufferSize;
+ BYTE *buffer;
+};
+
+static HRESULT WINAPI XUserGetGamerPictureProvider( XAsyncOp op, const XAsyncProviderData *data )
+{
+ IJsonObject *object = NULL, *profile = NULL, *setting = NULL;
+ static const WCHAR *accept[] = { L"image/png", NULL };
+ WCHAR *auth = NULL, *headers = NULL, *url = NULL;
+ IJsonArray *profiles = NULL, *settings = NULL;
+ struct XUserGetGamerPictureContext *context;
+ const WCHAR *suffix, *valueBuffer;
+ IXThreadingImpl *xthreading;
+ HSTRING value = NULL;
+ BYTE *buffer = NULL;
+ SIZE_T size;
+ HRESULT hr;
+
+ TRACE( "op %d, data %p.\n", op, data );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ context = (struct XUserGetGamerPictureContext *)data->context;
+
+ switch (op)
+ {
+ case XAsyncOp_Begin:
+ hr = IXThreadingImpl_XAsyncSchedule( xthreading, data->async, 0 );
+ break;
+
+ case XAsyncOp_GetResult:
+ memcpy( data->buffer, context->buffer, context->bufferSize );
+ break;
+
+ case XAsyncOp_DoWork:
+ switch (context->pictureSize)
+ {
+ case XUserGamerPictureSize_Small:
+ suffix = L"&format=png&w=64&h=64";
+ break;
+ case XUserGamerPictureSize_Medium:
+ suffix = L"&format=png&w=208&h=208";
+ break;
+ case XUserGamerPictureSize_Large:
+ suffix = L"&format=png&w=424&h=424";
+ break;
+ case XUserGamerPictureSize_ExtraLarge:
+ suffix = L"&format=png&w=1080&h=1080";
+ break;
+ default:
+ hr = E_INVALIDARG;
+ goto cleanup;
+ }
+
+ if (FAILED(hr = IUser_GetAuthorization( &context->user->IUser_iface, L"http://xboxlive.com", &auth ))) goto cleanup;
+ if (!(headers = calloc( wcslen( L"Authorization: " ) + wcslen( auth ) + 1, sizeof(WCHAR) )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ wcscpy( headers, L"Authorization: " );
+ wcscat( headers, auth );
+ if (FAILED(hr = http_request( L"GET", L"https://profile.xboxlive.com/users/me/profile/settings?settings=PublicGamerpic", NULL, headers, ACCEPT_JSON, &buffer, &size ))) goto cleanup;
+ if (FAILED(hr = parse_json( (char *)buffer, size, &object ))) goto cleanup;
+ if (FAILED(hr = get_json_array( object, L"profileUsers", &profiles ))) goto cleanup;
+ if (FAILED(hr = IJsonArray_GetObjectAt( profiles, 0, &profile ))) goto cleanup;
+ if (FAILED(hr = get_json_array( profile, L"settings", &settings ))) goto cleanup;
+ if (FAILED(hr = IJsonArray_GetObjectAt( settings, 0, &setting ))) goto cleanup;
+ if (FAILED(hr = get_json_string( setting, L"value", &value ))) goto cleanup;
+ valueBuffer = WindowsGetStringRawBuffer( value, NULL );
+ if (!(url = calloc( wcslen( valueBuffer ) + wcslen( suffix ) + 1, sizeof(WCHAR) )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+
+ wcscpy( url, valueBuffer );
+ wcscat( url, suffix );
+ hr = http_request( L"GET", url, NULL, NULL, accept, &context->buffer, &context->bufferSize );
+
+ cleanup:
+ IXThreadingImpl_XAsyncComplete( xthreading, data->async, hr, SUCCEEDED(hr) ? context->bufferSize : 0 );
+ if (profiles) IJsonArray_Release( profiles );
+ if (settings) IJsonArray_Release( settings );
+ if (profile) IJsonObject_Release( profile );
+ if (setting) IJsonObject_Release( setting );
+ if (object) IJsonObject_Release( object );
+ if (value) WindowsDeleteString( value );
+ if (headers) free( headers );
+ if (buffer) free( buffer );
+ if (auth) free( auth );
+ if (url) free( url );
+ hr = S_OK;
+ break;
+
+ case XAsyncOp_Cleanup:
+ IUser_Release( &context->user->IUser_iface );
+ if (context->buffer) free( context->buffer );
+ free( context );
+ break;
+
+ case XAsyncOp_Cancel:
+ break;
+ }
+
+ IXThreadingImpl_Release( xthreading );
+ return hr;
+}
+
static HRESULT WINAPI x_user_XUserGetGamerPictureAsync( IXUserImpl6 *iface, XUserHandle user, XUserGamerPictureSize pictureSize, XAsyncBlock *async )
{
- FIXME( "iface %p, user %p, pictureSize %d, async %p stub!\n", iface, user, pictureSize, async );
- return E_NOTIMPL;
+ struct XUserGetGamerPictureContext *context;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "iface %p, user %p, pictureSize %d, async %p.\n", iface, user, pictureSize, async );
+
+ if (!user || !async) return E_POINTER;
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ if (!(context = calloc( 1, sizeof(*context) )))
+ {
+ IXThreadingImpl_Release( xthreading );
+ return E_OUTOFMEMORY;
+ }
+
+ context->pictureSize = pictureSize;
+ if (FAILED(hr = IXUserImpl6_XUserDuplicateHandle( iface, user, &context->user )))
+ {
+ IXThreadingImpl_Release( xthreading );
+ return hr;
+ }
+
+ hr = IXThreadingImpl_XAsyncBegin( xthreading, async, context, NULL, "XUserGetGamerPictureAsync", XUserGetGamerPictureProvider );
+ IXThreadingImpl_Release( xthreading );
+ if (FAILED(hr)) free( context );
+ return hr;
}
static HRESULT WINAPI x_user_XUserGetGamerPictureResultSize( IXUserImpl6 *iface, XAsyncBlock *async, SIZE_T *bufferSize )
{
- FIXME( "iface %p, async %p, bufferSize %p stub!\n", iface, async, bufferSize );
- return E_NOTIMPL;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "iface %p, async %p, bufferSize %p.\n", iface, async, bufferSize );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResultSize( xthreading, async, bufferSize );
+ IXThreadingImpl_Release( xthreading );
+ return hr;
}
static HRESULT WINAPI x_user_XUserGetGamerPictureResult( IXUserImpl6 *iface, XAsyncBlock *async, SIZE_T bufferSize, void *buffer, SIZE_T *bufferUsed )
{
- FIXME( "iface %p, async %p, bufferSize %Iu, buffer %p, bufferUsed %p stub!\n", iface, async, bufferSize, buffer, bufferUsed );
- return E_NOTIMPL;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "iface %p, async %p, bufferSize %Iu, buffer %p, bufferUsed %p.\n", iface, async, bufferSize, buffer, bufferUsed );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResult( xthreading, async, NULL, bufferSize, buffer, bufferUsed );
+ IXThreadingImpl_Release( xthreading );
+ return hr;
}
static HRESULT WINAPI x_user_XUserGetAgeGroup( IXUserImpl6 *iface, XUserHandle user, XUserAgeGroup *ageGroup )
@@ -185,8 +1382,18 @@ static HRESULT WINAPI x_user_XUserGetAgeGroup( IXUserImpl6 *iface, XUserHandle u
static HRESULT WINAPI x_user_XUserCheckPrivilege( IXUserImpl6 *iface, XUserHandle user, XUserPrivilegeOptions options, XUserPrivilege privilege, BOOLEAN *hasPrivilege, XUserPrivilegeDenyReason *reason )
{
- FIXME( "iface %p, user %p, options %d, privilege %d, hasPrivilege %p, reason %p stub!\n", iface, user, options, privilege, hasPrivilege, reason );
- return E_NOTIMPL;
+ /* The signed-in account is real and the xsts tokens issued by the auth
+ * pipeline carry its granted PRIV claims; enforcement of the actual
+ * entitlement happens server-side. Reporting the standard privileges
+ * as granted mirrors the XUserIsStoreUser accept-pattern instead of
+ * failing titles' online gates (Deep Rock Galactic locks its server
+ * browser on the Multiplayer check) on an unimplemented query. */
+ TRACE( "iface %p, user %p, options %d, privilege %d, hasPrivilege %p, reason %p.\n", iface, user, options, privilege, hasPrivilege, reason );
+
+ if (!user || !hasPrivilege) return E_INVALIDARG;
+ *hasPrivilege = TRUE;
+ if (reason) *reason = XUserPrivilegeDenyReason_None;
+ return S_OK;
}
static HRESULT WINAPI x_user_XUserResolvePrivilegeWithUiAsync( IXUserImpl6 *iface, XUserHandle user, XUserPrivilegeOptions options, XUserPrivilege privilege, XAsyncBlock *async )
@@ -201,40 +1408,353 @@ static HRESULT WINAPI x_user_XUserResolvePrivilegeWithUiResult( IXUserImpl6 *ifa
return E_NOTIMPL;
}
+struct XUserGetTokenAndSignatureContext
+{
+ XUserHandle user;
+ XUserGetTokenAndSignatureOptions options;
+ char *url;
+ char *method;
+ SIZE_T headersSize;
+ char *headers;
+ SIZE_T bodySize;
+ void *bodyBuffer;
+ BOOLEAN isUtf16;
+ SIZE_T dataSize;
+ union
+ {
+ XUserGetTokenAndSignatureData *data;
+ XUserGetTokenAndSignatureUtf16Data *dataUtf16;
+ };
+};
+
+static HRESULT WINAPI XUserGetTokenAndSignatureProvider( XAsyncOp op, const XAsyncProviderData *data )
+{
+ struct XUserGetTokenAndSignatureContext *context;
+ char *buffer = NULL, signature[104];
+ IXThreadingImpl *xthreading;
+ struct endpoint info;
+ WCHAR *auth = NULL;
+ SIZE_T size = 0;
+ HRESULT hr;
+
+ TRACE( "op %d, data %p.\n", op, data );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ context = (struct XUserGetTokenAndSignatureContext *)data->context;
+
+ switch (op)
+ {
+ case XAsyncOp_Begin:
+ hr = IXThreadingImpl_XAsyncSchedule( xthreading, data->async, 0 );
+ break;
+
+ case XAsyncOp_GetResult:
+ {
+ char *base = (char *)context->data, *out = data->buffer;
+ memcpy( out, base, context->dataSize );
+ if (context->isUtf16)
+ {
+ XUserGetTokenAndSignatureUtf16Data *result = data->buffer;
+ if (result->token) result->token = (WCHAR *)(out + ((char *)result->token - base));
+ if (result->signature) result->signature = (WCHAR *)(out + ((char *)result->signature - base));
+ }
+ else
+ {
+ XUserGetTokenAndSignatureData *result = data->buffer;
+ if (result->token) result->token = out + (result->token - base);
+ if (result->signature) result->signature = out + (result->signature - base);
+ }
+ break;
+ }
+
+ case XAsyncOp_DoWork:
+ {
+ /* Fallback relying party for URLs missing from the endpoint table;
+ * heap-owned only for the web-origin case, freed at complete. */
+ WCHAR *partyBuf = NULL;
+ if (FAILED(hr = IUser_GetEndpointInfo( &context->user->IUser_iface, context->url, &info )))
+ {
+ /* The endpoint table only covers the partners returned at sign-in.
+ * Titles also request tokens for other services: Xbox Live hosts
+ * (e.g. the RTA websocket at wss://rta.xboxlive.com/connect) get an
+ * XSTS token for the xboxlive.com relying party, and any other host
+ * gets one scoped to the web origin of the requested URL, exactly
+ * how the GDK scopes tokens for title backends (Deep Rock
+ * Galactic's server browser signs services.ghostship.dk). The
+ * XSTS service still enforces whether the title may request it. */
+ static const WCHAR xboxlivePartyW[] = L"http://xboxlive.com";
+ static const WCHAR typeW[] = L"JWT";
+ const char *host, *hostEnd;
+ size_t hostLen, partyLen;
+ HSTRING_HEADER partyHeader, typeHeader;
+
+ host = strstr( context->url, "://" );
+ host = host ? host + 3 : context->url;
+ hostEnd = strchr( host, '/' );
+ hostLen = hostEnd ? hostEnd - host : strlen( host );
+ memset( &info, 0, sizeof(info) );
+ if ((hostLen >= 13 && !strncasecmp( host + hostLen - 13, ".xboxlive.com", 13 )) ||
+ (hostLen == 12 && !strncasecmp( host, "xboxlive.com", 12 )))
+ {
+ if (FAILED(hr = WindowsCreateStringReference( xboxlivePartyW, ARRAY_SIZE(xboxlivePartyW) - 1, &partyHeader, &info.relyingParty ))) goto complete;
+ }
+ else
+ {
+ partyLen = 8 + hostLen;
+ if (!(partyBuf = calloc( partyLen + 1, sizeof(WCHAR) )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto complete;
+ }
+ MultiByteToWideChar( CP_UTF8, 0, "https://", 8, partyBuf, partyLen );
+ MultiByteToWideChar( CP_UTF8, 0, host, hostLen, partyBuf + 8, partyLen - 8 );
+ if (FAILED(hr = WindowsCreateStringReference( partyBuf, partyLen, &partyHeader, &info.relyingParty ))) goto complete;
+ }
+ if (FAILED(hr = WindowsCreateStringReference( typeW, ARRAY_SIZE(typeW) - 1, &typeHeader, &info.tokenType ))) goto complete;
+ }
+ if (info.tokenType && FAILED(hr = IUser_GetAuthorization( &context->user->IUser_iface, WindowsGetStringRawBuffer(info.relyingParty, NULL), &auth ))) goto complete;
+
+ if (context->isUtf16)
+ {
+ context->dataSize = sizeof(*context->dataUtf16) + (auth ? (wcslen( auth ) + 1) * sizeof(WCHAR) : 0) + (info.policy ? 104 * sizeof(WCHAR) : 0);
+ if (!(context->dataUtf16 = calloc( 1, context->dataSize )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto complete;
+ }
+ if (auth)
+ {
+ context->dataUtf16->tokenCount = wcslen( auth );
+ context->dataUtf16->token = (WCHAR *)(context->dataUtf16 + 1);
+ wcscpy( (WCHAR *)context->dataUtf16->token, auth );
+ }
+ if (info.policy)
+ {
+ if (auth)
+ {
+ if (!(size = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, auth, -1, NULL, 0, NULL, NULL ))) goto error;
+ if (!(buffer = calloc( 1, size )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto complete;
+ }
+ if (!WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, auth, -1, buffer, size, NULL, NULL )) goto error;
+ }
+ context->dataUtf16->signatureCount = 104;
+ context->dataUtf16->signature = (WCHAR *)(context->dataUtf16 + 1) + (auth ? wcslen( auth ) + 1 : 0);
+ if (FAILED(hr = IUser_GetSignature( &context->user->IUser_iface, info.policy->version, context->method, context->url, (auth ? buffer : ""), min( context->bodySize, info.policy->maxBodyBytes ), context->bodyBuffer, signature ))) goto complete;
+ if (!MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, signature, 104, (WCHAR *)context->dataUtf16->signature, 104 )) goto error;
+ }
+ }
+ else
+ {
+ if (auth && !(size = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, auth, wcslen( auth ), NULL, 0, NULL, NULL ))) goto error;
+ context->dataSize = sizeof(*context->data) + (auth ? size + 1 : 0) + (info.policy ? 104 : 0);
+ if (!(context->data = calloc( 1, context->dataSize )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto complete;
+ }
+ if (auth)
+ {
+ context->data->tokenSize = size;
+ context->data->token = (char *)(context->data + 1);
+ if (!WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, auth, wcslen( auth ), (char *)context->data->token, size, NULL, NULL )) goto error;
+ }
+ if (info.policy)
+ {
+ context->data->signatureSize = 104;
+ context->data->signature = (char *)(context->data + 1) + (auth ? size + 1 : 0);
+ if (FAILED(hr = IUser_GetSignature( &context->user->IUser_iface, info.policy->version, context->method, context->url, (auth ? context->data->token : ""), min( context->bodySize, info.policy->maxBodyBytes ), context->bodyBuffer, (char *)context->data->signature ))) goto complete;
+ }
+ }
+ goto complete;
+
+ error:
+ hr = HRESULT_FROM_WIN32( GetLastError() );
+ complete:
+ free( partyBuf );
+ auth_metadata( "get-token-complete", context->user, hr, 0, TRUE, !!context->user->titleToken );
+ if (FAILED(hr)) { free( context->data ); context->data = NULL; }
+ if (buffer) free( buffer );
+ if (auth) free( auth );
+ /* Completion can synchronously consume/free this context. */
+ IXThreadingImpl_XAsyncComplete( xthreading, data->async, hr, SUCCEEDED(hr) ? context->dataSize : 0 );
+ hr = S_OK;
+ break;
+ }
+
+ case XAsyncOp_Cleanup:
+ IUser_Release( &context->user->IUser_iface );
+ free( context->data );
+ free( context );
+ break;
+
+ case XAsyncOp_Cancel:
+ break;
+ }
+
+ IXThreadingImpl_Release( xthreading );
+ return hr;
+}
+
static HRESULT WINAPI x_user_XUserGetTokenAndSignatureAsync( IXUserImpl6 *iface, XUserHandle user, XUserGetTokenAndSignatureOptions options, const char *method, const char *url, SIZE_T headerCount, const XUserGetTokenAndSignatureHttpHeader *headers, SIZE_T bodySize, const void *bodyBuffer, XAsyncBlock *async )
{
- FIXME( "iface %p, user %p, options %d, method %s, url %s, headerCount %Iu, headers %p, bodySize %Iu, bodyBuffer %p, async %p stub!\n", iface, user, options, debugstr_a( method ), debugstr_a( url ), headerCount, headers, bodySize, bodyBuffer, async );
- return E_NOTIMPL;
+ struct XUserGetTokenAndSignatureContext *context;
+ SIZE_T contextSize, headersSize = 0;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+ char *ptr;
+
+ TRACE( "iface %p, user %p, options %d, method %s, url %s, headerCount %Iu, headers %p, bodySize %Iu, bodyBuffer %p, async %p.\n", iface, user, options, debugstr_a( method ), debugstr_a( url ), headerCount, headers, bodySize, bodyBuffer, async );
+
+ contextSize = sizeof(*context) + strlen( url ) + strlen( method ) + 2 + bodySize;
+ for (SIZE_T i = 0; i < headerCount; i++)
+ headersSize += (strlen( headers[i].value ) + 1);
+
+ if (!(context = calloc( 1, contextSize + headersSize ))) return E_OUTOFMEMORY;
+ IUser_AddRef( &user->IUser_iface );
+ context->user = user;
+ context->options = options;
+ context->headersSize = headersSize;
+ context->bodySize = bodySize;
+ context->isUtf16 = FALSE;
+
+ /* url */
+ ptr = (char *)context + sizeof(*context);
+ ptr += strlen( strcpy( (context->url = ptr), url ) ) + 1;
+ /* method */
+ ptr += (strlen( strcpy( (context->method = ptr), method ) ) + 1);
+ /* headers */
+ context->headers = ptr;
+ for (SIZE_T i = 0; i < headerCount; i++)
+ ptr += (strlen( strcpy( ptr, headers[i].value ) ) + 1);
+ /* body */
+ memcpy( (context->bodyBuffer = ptr), bodyBuffer, bodySize );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) goto error;
+ hr = IXThreadingImpl_XAsyncBegin( xthreading, async, context, NULL, "XUserGetTokenAndSignatureAsync", XUserGetTokenAndSignatureProvider );
+ IXThreadingImpl_Release( xthreading );
+ if (FAILED(hr)) goto error;
+ return hr;
+error:
+ free( context );
+ IUser_Release( &user->IUser_iface );
+ return hr;
}
static HRESULT WINAPI x_user_XUserGetTokenAndSignatureResultSize( IXUserImpl6 *iface, XAsyncBlock *async, SIZE_T *bufferSize )
{
- FIXME( "iface %p, async %p, bufferSize %p stub!\n", iface, async, bufferSize );
- return E_NOTIMPL;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "iface %p, async %p, bufferSize %p.\n", iface, async, bufferSize );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResultSize( xthreading, async, bufferSize );
+ IXThreadingImpl_Release( xthreading );
+ return hr;
}
static HRESULT WINAPI x_user_XUserGetTokenAndSignatureResult( IXUserImpl6 *iface, XAsyncBlock *async, SIZE_T bufferSize, void *buffer, XUserGetTokenAndSignatureData **ptrToBuffer, SIZE_T *bufferUsed )
{
- FIXME( "iface %p, async %p, bufferSize %Iu, buffer %p, ptrToBuffer %p, bufferUsed %p stub!\n", iface, async, bufferSize, buffer, ptrToBuffer, bufferUsed );
- return E_NOTIMPL;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "iface %p, async %p, bufferSize %Iu, buffer %p, ptrToBuffer %p, bufferUsed %p.\n", iface, async, bufferSize, buffer, ptrToBuffer, bufferUsed );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResult( xthreading, async, NULL, bufferSize, buffer, bufferUsed );
+ *ptrToBuffer = (XUserGetTokenAndSignatureData *)buffer;
+ IXThreadingImpl_Release( xthreading );
+ return hr;
}
static HRESULT WINAPI x_user_XUserGetTokenAndSignatureUtf16Async( IXUserImpl6 *iface, XUserHandle user, XUserGetTokenAndSignatureOptions options, const WCHAR *method, const WCHAR *url, SIZE_T headerCount, const XUserGetTokenAndSignatureUtf16HttpHeader *headers, SIZE_T bodySize, const void *bodyBuffer, XAsyncBlock *async )
{
- FIXME( "iface %p, user %p, options %d, method %s, url %s, headerCount %Iu, headers %p, bodySize %Iu, bodyBuffer %p, async %p stub!\n", iface, user, options, debugstr_w( method ), debugstr_w( url ), headerCount, headers, bodySize, bodyBuffer, async );
- return E_NOTIMPL;
+ SIZE_T contextSize, headersSize = 0, methodLen, urlLen;
+ struct XUserGetTokenAndSignatureContext *context;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+ char *ptr;
+ int size;
+
+ TRACE( "iface %p, user %p, options %d, method %s, url %s, headerCount %Iu, headers %p, bodySize %Iu, bodyBuffer %p, async %p.\n", iface, user, options, debugstr_w( method ), debugstr_w( url ), headerCount, headers, bodySize, bodyBuffer, async );
+
+ if (!(methodLen = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, method, -1, NULL, 0, NULL, NULL ))) return HRESULT_FROM_WIN32( GetLastError() );
+ if (!(urlLen = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, url, -1, NULL, 0, NULL, NULL ))) return HRESULT_FROM_WIN32( GetLastError() );
+ contextSize = sizeof(*context) + urlLen + methodLen + bodySize;
+ for (SIZE_T i = 0; i < headerCount; i++)
+ {
+ if (!(size = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, headers[i].value, -1, NULL, 0, NULL, NULL ))) return HRESULT_FROM_WIN32( GetLastError() );
+ headersSize += size;
+ }
+
+ if (!(context = calloc( 1, contextSize + headersSize ))) return E_OUTOFMEMORY;
+ IUser_AddRef( &user->IUser_iface );
+ context->user = user;
+ context->options = options;
+ context->headersSize = headersSize;
+ context->bodySize = bodySize;
+ context->isUtf16 = TRUE;
+
+ /* url */
+ ptr = (char *)context + sizeof(*context);
+ if (!WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, url, -1, (context->url = ptr), urlLen, NULL, NULL )) goto error_win32;
+ ptr += urlLen;
+ /* method */
+ if (!WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, method, -1, (context->method = ptr), methodLen, NULL, NULL )) goto error_win32;
+ ptr += methodLen;
+ /* headers */
+ context->headers = ptr;
+ for (SIZE_T i = 0; i < headerCount; i++)
+ {
+ if (!(size = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, headers[i].value, -1, NULL, 0, NULL, NULL ))) goto error_win32;
+ if(!WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, headers[i].value, -1, ptr, size, NULL, NULL )) goto error_win32;
+ ptr += size;
+ }
+ /* body */
+ memcpy( (context->bodyBuffer = ptr), bodyBuffer, bodySize );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) goto error;
+ hr = IXThreadingImpl_XAsyncBegin( xthreading, async, context, NULL, "XUserGetTokenAndSignatureUtf16Async", XUserGetTokenAndSignatureProvider );
+ IXThreadingImpl_Release( xthreading );
+ if (FAILED(hr)) goto error;
+ return hr;
+
+error_win32:
+ hr = HRESULT_FROM_WIN32( GetLastError() );
+error:
+ free( context );
+ IUser_Release( &user->IUser_iface );
+ return hr;
}
static HRESULT WINAPI x_user_XUserGetTokenAndSignatureUtf16ResultSize( IXUserImpl6 *iface, XAsyncBlock *async, SIZE_T *bufferSize )
{
- FIXME( "iface %p, async %p, bufferSize %p stub!\n", iface, async, bufferSize );
- return E_NOTIMPL;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "iface %p, async %p, bufferSize %p.\n", iface, async, bufferSize );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResultSize( xthreading, async, bufferSize );
+ IXThreadingImpl_Release( xthreading );
+ return hr;
}
static HRESULT WINAPI x_user_XUserGetTokenAndSignatureUtf16Result( IXUserImpl6 *iface, XAsyncBlock *async, SIZE_T bufferSize, void *buffer, XUserGetTokenAndSignatureUtf16Data **ptrToBuffer, SIZE_T *bufferUsed )
{
- FIXME( "iface %p, async %p, bufferSize %Iu, buffer %p, ptrToBuffer %p, bufferUsed %p stub!\n", iface, async, bufferSize, buffer, ptrToBuffer, bufferUsed );
- return E_NOTIMPL;
+ IXThreadingImpl *xthreading;
+ HRESULT hr;
+
+ TRACE( "iface %p, async %p, bufferSize %Iu, buffer %p, ptrToBuffer %p, bufferUsed %p.\n", iface, async, bufferSize, buffer, ptrToBuffer, bufferUsed );
+
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&xthreading ))) return hr;
+ hr = IXThreadingImpl_XAsyncGetResult( xthreading, async, NULL, bufferSize, buffer, bufferUsed );
+ *ptrToBuffer = (XUserGetTokenAndSignatureUtf16Data *)buffer;
+ IXThreadingImpl_Release( xthreading );
+ return hr;
}
static HRESULT WINAPI x_user_XUserResolveIssueWithUiAsync( IXUserImpl6 *iface, XUserHandle user, const char *url, XAsyncBlock *async )
@@ -261,16 +1781,84 @@ static HRESULT WINAPI x_user_XUserResolveIssueWithUiUtf16Result( IXUserImpl6 *if
return E_NOTIMPL;
}
+struct user_change_registration
+{
+ struct user_change_registration *next;
+ UINT64 token;
+ IXThreadingImpl *threading;
+ XTaskQueueHandle queue;
+ void *context;
+ XUserChangeEventCallback *callback;
+};
+
+static struct user_change_registration *user_change_registrations;
+static UINT64 next_user_change_token;
+
static HRESULT WINAPI x_user_XUserRegisterForChangeEvent( IXUserImpl6 *iface, XTaskQueueHandle queue, void *context, XUserChangeEventCallback *callback, XTaskQueueRegistrationToken *token )
{
- FIXME( "iface %p, queue %p, context %p, callback %p, token %p stub!\n", iface, queue, context, callback, token );
- return E_NOTIMPL;
+ struct user_change_registration *registration;
+ IXThreadingImpl *threading;
+ HRESULT hr;
+
+ TRACE( "iface %p, queue %p, context %p, callback %p, token %p.\n", iface, queue, context, callback, token );
+ if (!token) return E_INVALIDARG;
+ token->token = 0;
+ if (!callback) return E_INVALIDARG;
+ if (FAILED(hr = QueryApiImpl( &CLSID_XThreadingImpl, &IID_IXThreadingImpl, (void **)&threading ))) return hr;
+ if (!(registration = calloc( 1, sizeof(*registration) )))
+ {
+ IXThreadingImpl_Release( threading );
+ return E_OUTOFMEMORY;
+ }
+ if (queue)
+ hr = IXThreadingImpl_XTaskQueueDuplicateHandle( threading, queue, ®istration->queue );
+ else
+ hr = IXThreadingImpl_XTaskQueueGetCurrentProcessTaskQueue( threading, ®istration->queue ) ? S_OK : HRESULT_FROM_WIN32( ERROR_NO_TASK_QUEUE );
+ if (FAILED(hr))
+ {
+ free( registration );
+ IXThreadingImpl_Release( threading );
+ return hr;
+ }
+ registration->threading = threading;
+ registration->context = context;
+ registration->callback = callback;
+ EnterCriticalSection( &signed_in_section );
+ if (!++next_user_change_token) ++next_user_change_token;
+ token->token = registration->token = next_user_change_token;
+ registration->next = user_change_registrations;
+ user_change_registrations = registration;
+ LeaveCriticalSection( &signed_in_section );
+ /* Initial sign-in is reported by XUserAddResult, not SignedInAgain. The
+ * single-account provider currently has no sign-out/profile-change source.
+ * Do not fabricate events or start background account/network polling. */
+ return S_OK;
}
static BOOLEAN WINAPI x_user_XUserUnregisterForChangeEvent( IXUserImpl6 *iface, XTaskQueueRegistrationToken token, BOOLEAN wait )
{
- FIXME( "iface %p, token %p, wait %d stub!\n", iface, &token, wait );
- return FALSE;
+ struct user_change_registration **cursor, *registration = NULL;
+
+ TRACE( "iface %p, token %llu, wait %d.\n", iface, token.token, wait );
+ EnterCriticalSection( &signed_in_section );
+ for (cursor = &user_change_registrations; *cursor; cursor = &(*cursor)->next)
+ {
+ if ((*cursor)->token != token.token) continue;
+ registration = *cursor;
+ *cursor = registration->next;
+ break;
+ }
+ LeaveCriticalSection( &signed_in_section );
+ if (registration)
+ {
+ IXThreadingImpl_XTaskQueueCloseHandle( registration->threading, registration->queue );
+ IXThreadingImpl_Release( registration->threading );
+ free( registration );
+ }
+ /* No change callbacks are dispatched by the current single-account
+ * provider, so there are no in-flight callbacks to wait for. If a future
+ * provider dispatches them, add execution refs and cancellation/wait here. */
+ return TRUE;
}
static HRESULT WINAPI x_user_XUserGetSignOutDeferral( IXUserImpl6 *iface, XUserSignOutDeferralHandle *deferral )
@@ -317,32 +1905,47 @@ static HRESULT WINAPI x_user_XUserGetMsaTokenSilentlyResultSize( IXUserImpl6 *if
static BOOLEAN WINAPI x_user_XUserIsStoreUser( IXUserImpl6 *iface, XUserHandle user )
{
- FIXME( "iface %p, user %p stub!\n", iface, user );
+ TRACE( "iface %p, user %p.\n", iface, user );
+
+ /* The signed-in user acquires real Microsoft Store licenses through
+ * this runtime (XStoreQueryLicenseToken reaches the actual licensing
+ * service), so they are a store user. */
return TRUE;
}
+/* Remote-connect and SPoP prompt registrations are accepted and never
+ * raised: this runtime has no remote device pairing or subscription
+ * prompts to deliver. Refusing them in the session-setup window left the
+ * title's platform state incomplete (observed in the Gears online
+ * transition right before the queue/token flow). */
static HRESULT WINAPI x_user_XUserPlatformRemoteConnectSetEventHandlers( IXUserImpl6 *iface, XTaskQueueHandle queue, XUserPlatformRemoteConnectEventHandlers *handlers )
{
- FIXME( "iface %p, queue %p, handlers %p stub!\n", iface, queue, handlers );
- return E_NOTIMPL;
+ FIXME( "iface %p, queue %p, handlers %p: accepted, no remote connect will be raised.\n",
+ iface, queue, handlers );
+
+ if (!handlers) return E_INVALIDARG;
+ return S_OK;
}
static HRESULT WINAPI x_user_XUserPlatformRemoteConnectCancelPrompt( IXUserImpl6 *iface, XUserPlatformOperation operation )
{
- FIXME( "iface %p, operation %p stub!\n", iface, operation );
- return E_NOTIMPL;
+ TRACE( "iface %p, operation %p.\n", iface, operation );
+ return S_OK;
}
static HRESULT WINAPI x_user_XUserPlatformSpopPromptSetEventHandlers( IXUserImpl6 *iface, XTaskQueueHandle queue, XUserPlatformSpopPromptEventHandler *handler, void *context )
{
- FIXME( "iface %p, queue %p, handler %p, context %p stub!\n", iface, queue, handler, context );
- return E_NOTIMPL;
+ FIXME( "iface %p, queue %p, handler %p, context %p: accepted, no prompt will be raised.\n",
+ iface, queue, handler, context );
+
+ if (!handler) return E_INVALIDARG;
+ return S_OK;
}
static HRESULT WINAPI x_user_XUserPlatformSpopPromptComplete( IXUserImpl6 *iface, XUserPlatformOperation operation, XUserPlatformOperationResult result )
{
- FIXME( "iface %p, operation %p, result %d stub!\n", iface, operation, result );
- return E_NOTIMPL;
+ TRACE( "iface %p, operation %p, result %d.\n", iface, operation, result );
+ return S_OK;
}
static BOOLEAN WINAPI x_user_XUserIsSignOutPresent( IXUserImpl6 *iface )
@@ -448,8 +2051,36 @@ static ULONG WINAPI x_user_gamertag_Release( IXUserGamertagImpl *iface )
static HRESULT WINAPI x_user_gamertag_XUserGetGamertag( IXUserGamertagImpl *iface, XUserHandle user, XUserGamertagComponent gamertagComponent, SIZE_T gamertagSize, char *gamertag, SIZE_T *gamertagUsed )
{
- FIXME( "iface %p, user %p, gamertagComponent %d, gamertagSize %Iu, gamertag %p, gamertagUsed %p stub!\n", iface, user, gamertagComponent, gamertagSize, gamertag, gamertagUsed );
- return E_NOTIMPL;
+ TRACE( "iface %p, user %p, gamertagComponent %d, gamertagSize %Iu, gamertag %p, gamertagUsed %p.\n", iface, user, gamertagComponent, gamertagSize, gamertag, gamertagUsed );
+
+ switch (gamertagComponent)
+ {
+ case XUserGamertagComponent_Classic:
+ if (gamertagSize <= strlen( user->gamertag )) return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+ strcpy( gamertag, user->gamertag );
+ if (gamertagUsed) *gamertagUsed = strlen( user->gamertag ) + 1;
+ return S_OK;
+
+ case XUserGamertagComponent_Modern:
+ if (gamertagSize <= strlen( user->modernGamertag )) return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+ strcpy( gamertag, user->modernGamertag );
+ if (gamertagUsed) *gamertagUsed = strlen( user->modernGamertag ) + 1;
+ return S_OK;
+
+ case XUserGamertagComponent_ModernSuffix:
+ if (gamertagSize <= strlen( user->modernGamertagSuffix )) return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+ strcpy( gamertag, user->modernGamertagSuffix );
+ if (gamertagUsed) *gamertagUsed = strlen( user->modernGamertagSuffix ) + 1;
+ return S_OK;
+
+ case XUserGamertagComponent_UniqueModern:
+ if (gamertagSize <= strlen( user->uniqueModernGamertag )) return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
+ strcpy( gamertag, user->uniqueModernGamertag );
+ if (gamertagUsed) *gamertagUsed = strlen( user->uniqueModernGamertag ) + 1;
+ return S_OK;
+ }
+
+ return E_INVALIDARG;
}
static const struct IXUserGamertagImplVtbl x_user_gamertag_vtbl =
@@ -571,3 +2202,165 @@ static struct x_user x_user =
IXUserImpl *x_user_impl = (IXUserImpl *)&x_user.IXUserImpl6_iface;
IXUserDeviceImpl *x_user_device_impl = (IXUserDeviceImpl *)&x_user.IXUserDeviceImpl2_iface;
+
+static char *hstring_to_utf8( HSTRING string )
+{
+ const WCHAR *buffer = WindowsGetStringRawBuffer( string, NULL );
+ int size = WideCharToMultiByte( CP_UTF8, 0, buffer, -1, NULL, 0, NULL, NULL );
+ char *out;
+
+ if (!size || !(out = calloc( 1, size ))) return NULL;
+ WideCharToMultiByte( CP_UTF8, 0, buffer, -1, out, size, NULL, NULL );
+ return out;
+}
+
+static WCHAR *utf8_to_wide( const char *string )
+{
+ int size = MultiByteToWideChar( CP_UTF8, 0, string, -1, NULL, 0 );
+ WCHAR *out;
+
+ if (!size || !(out = calloc( size, sizeof(WCHAR) ))) return NULL;
+ MultiByteToWideChar( CP_UTF8, 0, string, -1, out, size );
+ return out;
+}
+
+UINT64 xuser_get_xuid( XUserHandle user )
+{
+ return user->xuid;
+}
+
+HRESULT xuser_signed_request( XUserHandle user, const char *method, const char *url, const char *auth, const char *extraHeaders,
+ const void *body, DWORD bodySize, DWORD *status, BYTE **buffer, SIZE_T *bufferSize )
+{
+ WCHAR *methodW = NULL, *urlW = NULL, *headersW = NULL;
+ char signature[105] = { 0 }, *headers = NULL;
+ SIZE_T headersSize;
+ HRESULT hr;
+
+ TRACE( "user %p, method %s, url %s, bodySize %lu.\n", user, debugstr_a( method ), debugstr_a( url ), bodySize );
+
+ if (FAILED(hr = IUser_GetSignature( &user->IUser_iface, 1, method, url, auth ? auth : "", min( bodySize, 8192 ), body, signature ))) return hr;
+ headersSize = strlen( "Authorization: \r\nSignature: \r\n" ) + (auth ? strlen( auth ) : 0) + 104 + (extraHeaders ? strlen( extraHeaders ) : 0) + 1;
+ if (!(headers = calloc( 1, headersSize ))) return E_OUTOFMEMORY;
+ if (auth) snprintf( headers, headersSize, "Authorization: %s\r\nSignature: %s\r\n%s", auth, signature, extraHeaders ? extraHeaders : "" );
+ else snprintf( headers, headersSize, "Signature: %s\r\n%s", signature, extraHeaders ? extraHeaders : "" );
+
+ if (!(methodW = utf8_to_wide( method )) || !(urlW = utf8_to_wide( url )) || !(headersW = utf8_to_wide( headers ))) hr = E_OUTOFMEMORY;
+ else
+ {
+ for (int attempt = 0; attempt < 3; attempt++)
+ {
+ if (attempt)
+ {
+ WARN( "request %s %s failed with hr %#lx, retrying.\n", debugstr_a( method ), debugstr_a( url ), hr );
+ Sleep( 500 * attempt );
+ }
+ if (SUCCEEDED(hr = http_request_raw( methodW, urlW, headersW, body, bodySize, status, buffer, bufferSize )) && *status < 500) break;
+ if (SUCCEEDED(hr))
+ {
+ free( *buffer );
+ *buffer = NULL;
+ *bufferSize = 0;
+ }
+ }
+ }
+
+ free( methodW );
+ free( urlW );
+ free( headersW );
+ free( headers );
+ return hr;
+}
+
+static HRESULT xsts_authorize( XUserHandle user, const char *relyingParty, BOOL title, char **auth )
+{
+ static const char url[] = "https://xsts.auth.xboxlive.com/xsts/authorize";
+ IJsonObject *object = NULL, *claims = NULL, *identity = NULL;
+ HSTRING token = NULL, uhs = NULL;
+ char *body = NULL, *tokenA = NULL, *uhsA = NULL;
+ IJsonArray *xui = NULL;
+ BYTE *buffer = NULL;
+ SIZE_T size, bufferSize;
+ HRESULT hr, comInit = E_FAIL;
+ DWORD status = 0;
+ BOOL requested_title = title;
+
+ TRACE( "user %p, relyingParty %s, title %d.\n", user, debugstr_a( relyingParty ), title );
+
+ if (!user->deviceToken || !user->userToken || !user->proofKey)
+ {
+ auth_metadata( "xsts", user, E_UNEXPECTED, 0, requested_title, FALSE );
+ return E_UNEXPECTED;
+ }
+
+ if (!title || !user->titleToken) title = FALSE;
+ size = strlen( relyingParty ) + strlen( user->deviceToken ) + strlen( user->userToken ) + strlen( user->proofKey ) + (title ? strlen( user->titleToken ) : 0) + 256;
+ if (!(body = calloc( 1, size )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ snprintf( body, size, "{\"RelyingParty\":\"%s\",\"TokenType\":\"JWT\",\"Properties\":{\"SandboxId\":\"RETAIL\",\"DeviceToken\":\"%s\",%s%s%s\"UserTokens\":[\"%s\"],\"ProofKey\":%s}}",
+ relyingParty, user->deviceToken, title ? "\"TitleToken\":\"" : "", title ? user->titleToken : "", title ? "\"," : "", user->userToken, user->proofKey );
+
+ if (FAILED(hr = xuser_signed_request( user, "POST", url, NULL, "x-xbl-contract-version: 1\r\nContent-Type: application/json\r\n",
+ body, strlen( body ), &status, &buffer, &bufferSize ))) goto cleanup;
+ if (status != 200)
+ {
+ ERR( "xsts authorization failed, status %lu, body %s.\n", status, debugstr_an( (char *)buffer, bufferSize ) );
+ hr = E_FAIL;
+ goto cleanup;
+ }
+
+ comInit = CoInitializeEx( NULL, COINIT_MULTITHREADED );
+ if (FAILED(hr = parse_json( (char *)buffer, bufferSize, &object ))) goto cleanup;
+ if (FAILED(hr = get_json_string( object, L"Token", &token ))) goto cleanup;
+ if (FAILED(hr = get_json_object( object, L"DisplayClaims", &claims ))) goto cleanup;
+ if (FAILED(hr = get_json_array( claims, L"xui", &xui ))) goto cleanup;
+ if (FAILED(hr = IJsonArray_GetObjectAt( xui, 0, &identity ))) goto cleanup;
+ if (FAILED(hr = get_json_string( identity, L"uhs", &uhs ))) goto cleanup;
+ if (!(tokenA = hstring_to_utf8( token )) || !(uhsA = hstring_to_utf8( uhs )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ size = strlen( "XBL3.0 x=;" ) + strlen( uhsA ) + strlen( tokenA ) + 1;
+ if (!(*auth = calloc( 1, size )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ snprintf( *auth, size, "XBL3.0 x=%s;%s", uhsA, tokenA );
+
+cleanup:
+ if (identity) IJsonObject_Release( identity );
+ if (claims) IJsonObject_Release( claims );
+ if (object) IJsonObject_Release( object );
+ if (xui) IJsonArray_Release( xui );
+ if (token) WindowsDeleteString( token );
+ if (uhs) WindowsDeleteString( uhs );
+ free( tokenA );
+ free( uhsA );
+ free( buffer );
+ free( body );
+ if (SUCCEEDED(comInit)) CoUninitialize();
+ auth_metadata( "xsts", user, hr, status, requested_title, title );
+ return hr;
+}
+
+HRESULT xuser_device_authorization( XUserHandle user, const char *relyingParty, char **auth )
+{
+ HRESULT hr;
+
+ EnterCriticalSection( &user->deviceAuthSection );
+ if (user->deviceAuth && GetTickCount64() - user->deviceAuthTime < 3600 * 1000)
+ hr = (*auth = strdup( user->deviceAuth )) ? S_OK : E_OUTOFMEMORY;
+ else if (SUCCEEDED(hr = xsts_authorize( user, relyingParty, FALSE, auth )))
+ {
+ free( user->deviceAuth );
+ user->deviceAuth = strdup( *auth );
+ user->deviceAuthTime = GetTickCount64();
+ }
+ LeaveCriticalSection( &user->deviceAuthSection );
+ return hr;
+}
[attr]generated gitlab-generated linguist-generated=true not allowed: work/wine-pr28-src/.gitattributes:1
[attr]generated gitlab-generated linguist-generated=true not allowed: work/wine-pr28-src/.gitattributes:1
[attr]generated gitlab-generated linguist-generated=true not allowed: work/wine-pr28-src/.gitattributes:1
diff --git a/dlls/xgameruntime/util.c b/dlls/xgameruntime/util.c
new file mode 100644
index 0000000..55a40d8
--- /dev/null
+++ b/dlls/xgameruntime/util.c
@@ -0,0 +1,253 @@
+/*
+ * Copyright 2026 Olivia Ryan
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+#include "private.h"
+#include "util.h"
+#include <winhttp.h>
+
+WINE_DEFAULT_DEBUG_CHANNEL(xgameruntime);
+
+static const WCHAR USER_AGENT[] = L"curl/1.0";
+
+static HRESULT http_request_once( const WCHAR *method, const WCHAR *url, char *data, const WCHAR *headers, const WCHAR **accept, UCHAR **buffer, SIZE_T *bufferSize );
+
+HRESULT http_request( const WCHAR *method, const WCHAR *url, char *data, const WCHAR *headers, const WCHAR **accept, UCHAR **buffer, SIZE_T *bufferSize )
+{
+ HRESULT hr = E_FAIL;
+ for (int attempt = 0; attempt < 3; attempt++)
+ {
+ if (attempt)
+ {
+ WARN( "request %s %s failed with hr %#lx, retrying.\n", debugstr_w( method ), debugstr_w( url ), hr );
+ Sleep( 500 * attempt );
+ }
+ *buffer = NULL;
+ *bufferSize = 0;
+ if (SUCCEEDED(hr = http_request_once( method, url, data, headers, accept, buffer, bufferSize ))) break;
+ if (hr == E_FAIL) break;
+ }
+ return hr;
+}
+
+static HRESULT http_request_once( const WCHAR *method, const WCHAR *url, char *data, const WCHAR *headers, const WCHAR **accept, UCHAR **buffer, SIZE_T *bufferSize )
+{
+ URL_COMPONENTS uc = { .dwStructSize = sizeof(URL_COMPONENTS), .dwHostNameLength = -1, .dwUrlPathLength = -1 };
+ HINTERNET connection = NULL, request = NULL, session = NULL;
+ DWORD size = sizeof( DWORD ), status;
+ WCHAR *hostName = NULL;
+ UCHAR *tmpBuffer = NULL;
+ HRESULT hr = S_OK;
+
+ TRACE( "method %s, url %s, data %s, headers %s, accept %p, buffer %p, bufferSize %p.\n",
+ debugstr_w( method ), debugstr_w( url ), debugstr_a( data ), debugstr_w( headers ), accept, buffer, bufferSize );
+
+ if (!WinHttpCrackUrl( url, 0, 0, &uc )) goto error;
+ if (!(hostName = calloc( uc.dwHostNameLength + 1, sizeof(WCHAR) )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ memcpy( hostName, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
+
+ if (!(session = WinHttpOpen( USER_AGENT, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ))) goto error;
+ if (!(connection = WinHttpConnect( session, hostName, INTERNET_DEFAULT_HTTPS_PORT, 0 ))) goto error;
+ if (!(request = WinHttpOpenRequest( connection, method, uc.lpszUrlPath, NULL, WINHTTP_NO_REFERER, accept, WINHTTP_FLAG_SECURE ))) goto error;
+ if (!WinHttpSendRequest( request, headers ? headers : WINHTTP_NO_ADDITIONAL_HEADERS, headers ? -1 : 0, data, (data ? strlen( data ) : 0), (data ? strlen( data ) : 0), 0 )) goto error;
+ if (!WinHttpReceiveResponse( request, NULL )) goto error;
+ if (!WinHttpQueryHeaders( request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
+ WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX )) goto error;
+ if (status != 200)
+ {
+ hr = E_FAIL;
+ goto cleanup;
+ }
+
+ /* buffer response data */
+ *bufferSize = 0;
+ *buffer = NULL;
+ tmpBuffer = NULL;
+ do
+ {
+ if (!WinHttpQueryDataAvailable( request, &size )) goto error;
+ if (!size) break;
+ if (!(tmpBuffer = realloc( *buffer, *bufferSize + size )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ *buffer = tmpBuffer;
+
+ if (!WinHttpReadData( request, *buffer + *bufferSize, size, &size )) goto error;
+ *bufferSize += size;
+ }
+ while (size);
+ goto cleanup;
+
+error:
+ hr = HRESULT_FROM_WIN32( GetLastError() );
+cleanup:
+ if (connection) WinHttpCloseHandle( connection );
+ if (request) WinHttpCloseHandle( request );
+ if (session) WinHttpCloseHandle( session );
+ if (hostName) free( hostName );
+ if (SUCCEEDED(hr)) return hr;
+ if (*buffer) free( *buffer );
+ *bufferSize = 0;
+ *buffer = NULL;
+ return hr;
+}
+
+HRESULT http_request_raw( const WCHAR *method, const WCHAR *url, const WCHAR *headers, const void *body, DWORD bodySize, DWORD *status, BYTE **buffer, SIZE_T *bufferSize )
+{
+ URL_COMPONENTS uc = { .dwStructSize = sizeof(URL_COMPONENTS), .dwHostNameLength = -1, .dwUrlPathLength = -1 };
+ HINTERNET connection = NULL, request = NULL, session = NULL;
+ DWORD size = sizeof(DWORD);
+ WCHAR *hostName = NULL;
+ BYTE *tmpBuffer;
+ HRESULT hr = S_OK;
+
+ TRACE( "method %s, url %s, bodySize %lu.\n", debugstr_w( method ), debugstr_w( url ), bodySize );
+
+ *buffer = NULL;
+ *bufferSize = 0;
+ *status = 0;
+ if (!WinHttpCrackUrl( url, 0, 0, &uc )) goto error;
+ if (!(hostName = calloc( uc.dwHostNameLength + 1, sizeof(WCHAR) )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ memcpy( hostName, uc.lpszHostName, uc.dwHostNameLength * sizeof(WCHAR) );
+
+ if (!(session = WinHttpOpen( USER_AGENT, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ))) goto error;
+ if (!(connection = WinHttpConnect( session, hostName, uc.nPort, 0 ))) goto error;
+ if (!(request = WinHttpOpenRequest( connection, method, uc.lpszUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
+ uc.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0 ))) goto error;
+ if (!WinHttpSendRequest( request, headers ? headers : WINHTTP_NO_ADDITIONAL_HEADERS, headers ? -1 : 0, (void *)body, bodySize, bodySize, 0 )) goto error;
+ if (!WinHttpReceiveResponse( request, NULL )) goto error;
+ if (!WinHttpQueryHeaders( request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
+ WINHTTP_HEADER_NAME_BY_INDEX, status, &size, WINHTTP_NO_HEADER_INDEX )) goto error;
+
+ do
+ {
+ if (!WinHttpQueryDataAvailable( request, &size )) goto error;
+ if (!size) break;
+ if (!(tmpBuffer = realloc( *buffer, *bufferSize + size + 1 )))
+ {
+ hr = E_OUTOFMEMORY;
+ goto cleanup;
+ }
+ *buffer = tmpBuffer;
+ if (!WinHttpReadData( request, *buffer + *bufferSize, size, &size )) goto error;
+ *bufferSize += size;
+ (*buffer)[*bufferSize] = 0;
+ }
+ while (size);
+ goto cleanup;
+
+error:
+ hr = HRESULT_FROM_WIN32( GetLastError() );
+cleanup:
+ if (request) WinHttpCloseHandle( request );
+ if (connection) WinHttpCloseHandle( connection );
+ if (session) WinHttpCloseHandle( session );
+ free( hostName );
+ if (FAILED(hr))
+ {
+ free( *buffer );
+ *buffer = NULL;
+ *bufferSize = 0;
+ }
+ TRACE( "status %lu, size %Iu, hr %#lx.\n", *status, *bufferSize, hr );
+ return hr;
+}
+
+#define encode_base64_(sfx,type,alph) \
+HRESULT encode_base64##sfx( const UINT32 dataSize, const BYTE *data, const UINT32 base64Size, type *base64, BOOLEAN pad ) \
+{ \
+ static const char alphabet[64] = alph; \
+ const BYTE *inp = data; \
+ type *out = base64; \
+ \
+ TRACE( "dataSize %u, data %p, base64Size %u, base64 %p, pad %d.\n", dataSize, data, base64Size, base64, pad ); \
+ \
+ if ((dataSize * 8 + 5) / 6 + (pad ? (4 - (dataSize % 4)) % 4 : 0) > base64Size) \
+ return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER ); \
+ \
+ for (UINT32 i = 0; i < dataSize / 3; i++) \
+ { \
+ /* first 6 bits of byte 0 */ \
+ *out++ = alphabet[ (inp[0] >> 2) & 0x3f ]; \
+ /* last 2 bits of byte 0, first 4 bits of byte 1 */ \
+ *out++ = alphabet[ ((inp[0] << 4) & 0x30) | ((inp[1] >> 4) & 0x0f) ]; \
+ /* last 4 bits of byte 1, first 2 bits of byte 2 */ \
+ *out++ = alphabet[ ((inp[1] << 2) & 0x3c) | ((inp[2] >> 6) & 0x03) ]; \
+ /* last 6 bits of byte 2 */ \
+ *out++ = alphabet[ inp[2] & 0x3f ]; \
+ inp += 3; \
+ } \
+ \
+ switch (dataSize % 3) \
+ { \
+ case 1: \
+ /* first 6 bits of byte 0 */ \
+ *out++ = alphabet[ (inp[0] >> 2) & 0x3f ]; \
+ /* last 2 bits of byte 0, rest 0 */ \
+ *out++ = alphabet[ ((inp[0] << 4) & 0x30) ]; \
+ /* padding */ \
+ if (pad) \
+ { \
+ *out++ = '='; \
+ *out++ = '='; \
+ } \
+ break; \
+ case 2: \
+ /* first 6 bits of byte 0 */ \
+ *out++ = alphabet[ (inp[0] >> 2) & 0x3f ]; \
+ /* last 2 bits of byte 0, first 4 bits of byte 1 */ \
+ *out++ = alphabet[ ((inp[0] << 4) & 0x30) | ((inp[1] >> 4) & 0x0f) ]; \
+ /* last 4 bits of byte 1, rest 0 */ \
+ *out++ = alphabet[ ((inp[1] << 2) & 0x3c) ]; \
+ /* padding */ \
+ if (pad) *out++ = '='; \
+ break; \
+ } \
+ return S_OK; \
+}
+
+encode_base64_(_utf16,WCHAR,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
+encode_base64_(_url,char,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
+encode_base64_(,char,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
+
+#define get_json_(sfx,typ,ret) \
+HRESULT get_json_##sfx( IJsonObject *object, const WCHAR *key, ret value ) \
+{ \
+ HSTRING_HEADER hdr; \
+ HSTRING str; \
+ HRESULT hr; \
+ \
+ if (FAILED(hr = WindowsCreateStringReference( key, wcslen( key ), &hdr, &str ))) return hr; \
+ return IJsonObject_GetNamed##typ( object, str, value ); \
+}
+
+get_json_(object,Object,IJsonObject**)
+get_json_(array,Array,IJsonArray**)
+get_json_(boolean,Boolean,boolean*)
+get_json_(value,Value,IJsonValue**)
+get_json_(string,String,HSTRING*)
+get_json_(number,Number,DOUBLE*)
[attr]generated gitlab-generated linguist-generated=true not allowed: work/wine-pr28-src/.gitattributes:1
[attr]generated gitlab-generated linguist-generated=true not allowed: work/wine-pr28-src/.gitattributes:1
[attr]generated gitlab-generated linguist-generated=true not allowed: work/wine-pr28-src/.gitattributes:1
diff --git a/dlls/xgameruntime/util.h b/dlls/xgameruntime/util.h
new file mode 100644
index 0000000..e9f45cf
--- /dev/null
+++ b/dlls/xgameruntime/util.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2026 Olivia Ryan
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+#ifndef __WINE_XGAMERUNTIME_UTIL_H
+#define __WINE_XGAMERUNTIME_UTIL_H
+
+HRESULT http_request( const WCHAR *method, const WCHAR *url, char *data, const WCHAR *headers, const WCHAR **accept, UCHAR **buffer, SIZE_T *bufferSize );
+HRESULT http_request_raw( const WCHAR *method, const WCHAR *url, const WCHAR *headers, const void *body, DWORD bodySize, DWORD *status, BYTE **buffer, SIZE_T *bufferSize );
+HRESULT encode_base64( const UINT32 dataSize, const BYTE *data, const UINT32 base64Size, char *base64, BOOLEAN pad );
+HRESULT encode_base64_url( const UINT32 dataSize, const BYTE *data, const UINT32 base64Size, char *base64, BOOLEAN pad );
+HRESULT encode_base64_utf16( const UINT32 dataSize, const BYTE *data, const UINT32 base64Size, WCHAR *base64, BOOLEAN pad );
+HRESULT get_json_object( IJsonObject *obj, const WCHAR *key, IJsonObject **value );
+HRESULT get_json_array( IJsonObject *obj, const WCHAR *key, IJsonArray **value );
+HRESULT get_json_boolean( IJsonObject *obj, const WCHAR *key, boolean *value );
+HRESULT get_json_value( IJsonObject *obj, const WCHAR *key, IJsonValue **value );
+HRESULT get_json_string( IJsonObject *obj, const WCHAR *key, HSTRING *value );
+HRESULT get_json_number( IJsonObject *obj, const WCHAR *key, DOUBLE *value );
+
+#endif
[attr]generated gitlab-generated linguist-generated=true not allowed: work/wine-pr28-src/.gitattributes:1
[attr]generated gitlab-generated linguist-generated=true not allowed: work/wine-pr28-src/.gitattributes:1
[attr]generated gitlab-generated linguist-generated=true not allowed: work/wine-pr28-src/.gitattributes:1
diff --git a/dlls/xgameruntime/userprovider.idl b/dlls/xgameruntime/userprovider.idl
new file mode 100644
index 0000000..eab5dc9
--- /dev/null
+++ b/dlls/xgameruntime/userprovider.idl
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2026 Olivia Ryan
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+#pragma makedep header
+
+#ifdef __WIDL__
+#pragma winrt ns_prefix
+#endif
+
+import "windows.data.json.idl";
+import "xuser.idl";
+
+struct endpoint;
+
+[
+ local,
+ object
+]
+interface IUser : IUnknown
+{
+ HRESULT Initialize( [in] const XUserAddOptions options );
+ HRESULT GetEndpointInfo( [in, string] const char *url, [out] struct endpoint *info );
+ HRESULT GetAuthorization( [in, string] const WCHAR *relyingParty, [out, string] WCHAR **auth );
+ HRESULT GetSignature( [in] UINT32 version, [in, string] const char *method, [in, string] const char *url, [in, string] const char *auth, [in] UINT32 bodySize, [in, size_is(bodySize)] const void *body, [out, size_is(104)] char *signature );
+}