diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 7dfc6569fb..fe41be72d4 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -39,10 +39,16 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + - name: Prepare pinned Apple cryptography for offline service fixtures + run: echo "DM_OPENSSL_ROOT=$(python3 dm/tools/apple_crypto.py macos)" >> "$GITHUB_ENV" - name: Host unit tests (dm/host/tests) run: | mkdir -p logs make -C dm/host/tests GAME="$GAME" -j3 run 2>&1 | tee logs/host-tests.log + - name: Calendar policy, archive, SDK and startup fixtures + run: make -C dm/host/tests GAME="$GAME" bcat 2>&1 | tee logs/bcat.log + - name: Native TLS with bounded numeric tracing + run: DM_SSL_TRACE=1 make -C dm/host/tests GAME="$GAME" ssl 2>&1 | tee logs/tls-trace.log - name: ThreadSanitizer (audio, HID and guest memory) run: | make -C dm/host/tests GAME="$GAME" -j3 tsan memory-tsan 2>&1 | tee logs/tsan.log @@ -92,6 +98,8 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + - name: Prepare pinned Apple cryptography for offline service fixtures + run: echo "DM_OPENSSL_ROOT=$(python3 dm/tools/apple_crypto.py macos)" >> "$GITHUB_ENV" - name: Registration sections (all producers, ASan and UBSan, no global ignorelist) run: | mkdir -p logs @@ -100,6 +108,11 @@ jobs: run: | mkdir -p logs make -C dm/host/tests GAME="$GAME" -j3 asan 2>&1 | tee logs/host-asan.log + - name: ASan and UBSan, calendar startup and native service fixtures + run: | + make -C dm/host/tests GAME="$GAME" B=build/bcat-asan SAN="-fsanitize=address,undefined -fno-omit-frame-pointer" bcat 2>&1 | tee logs/bcat-asan.log + make -C dm/host/tests GAME="$GAME" ssl-sanitize nextendo-routes-sanitize nextendo-x509-sanitize nsd-sanitize nextendo-account-sanitize nextendo-api-sanitize nextendo-social-sanitize online-policy-sanitize 2>&1 | tee logs/services-asan.log + DM_SSL_TRACE=1 make -C dm/host/tests GAME="$GAME" ssl-sanitize 2>&1 | tee logs/tls-trace-asan.log - name: ASan and UBSan, CPU texture layout and deswizzle test (dm/gfx/tex/tests) run: make -C dm/gfx/tex/tests asan 2>&1 | tee logs/texture-asan.log - name: ThreadSanitizer, the host tests that start threads (dm/host/tests) diff --git a/dm/.gitignore b/dm/.gitignore index 47168e2e9a..f55dcf361a 100644 --- a/dm/.gitignore +++ b/dm/.gitignore @@ -1,4 +1,5 @@ host/dmhost +host/nextendo_login host/dmhost_* host/*.dSYM/ *.bin diff --git a/dm/games/010015100B514000/README.md b/dm/games/010015100B514000/README.md index 98df198913..7c4aabfe7c 100644 --- a/dm/games/010015100B514000/README.md +++ b/dm/games/010015100B514000/README.md @@ -98,6 +98,14 @@ Game-specific findings; the general host changes they led to are listed under [F - Focus handling mode 2 (focus notifications are sent). Mario never throws C++ exceptions. - Ghidra: `main` (28 MB) took about 35 minutes to analyse, 138k functions. +### Online play (Nextendo), 1.2.1 + +- Online calls go through `nn::npln` over gRPC (a 1.3x build with xDS, linked into `main` with its own OpenSSL, `nnsdk_LoadBuiltinCerts.cpp`). gRPC does its own TLS over the C socket interface (`RecvMsg` / `SendMsg`); the `nn::ssl` connection calls `main` imports are libcurl's (`main+0xf79a98`..`0xf7a1e4`), so the host's `nn::ssl` peer policy never sees gRPC's connections. +- gRPC takes its roots from the firmware's certificate store: `ComputePemRootCerts` (`main+0xafa5b4`) reads `GRPC_DEFAULT_SSL_ROOTS_FILE_PATH`, then the store one ID at a time (`main+0xafaf50`: 1, 2, 0x3e8, 0x3f3, 0x3f4, 0x3f5, 0x409, stopping at the first failure), then `/usr/share/grpc/roots.pem`. With no root it builds no TLS factory (`main+0xaf6ca8`, `main+0xaf9010`), so no subchannel and no socket: the call fails as UNAVAILABLE, error 2321-4992. In Nextendo mode the player needs nothing for it: with no store on the device, the host answers each ID with Nextendo's own CA, the one the build's service profile carries and checks by SHA-256 (`hle_nextendo_routes.c` `provider_ca`, `hle_ssl_apple.m` `select_builtin`). A store from the player's own firmware (`ssl_TrustedCerts.bdf` in `/sysdata/0100000000000800/` or `/0100000000000800/files/`) is used instead when present. The host logs which it used and every built-in request. +- Nextendo's signed patch (`wonder-npln-ff773e90`, three instructions) makes gRPC install its accept-any verify callback (`main+0xb03528`) and skips two peer-name checks (`main+0xb02aa4`, `main+0xb02bbc`), so gRPC does not check Nextendo's server certificate; the roots are still required to build the factory. +- gRPC's logging is compiled out (`GRPC_TRACE` and `GRPC_VERBOSITY` print nothing). `patches.py` puts an observation gate on `grpc_error_create` (`main+0xb57b40`), and the host logs each internal error's source file, line and text once (`hle_grpc.c`). +- Proxy: gRPC's mapper (`main+0xb31760`) and libcurl's (`main+0xf7aa40`) both take a failed `nifm::GetCurrentProxySetting` as no proxy. + ## Mac routes - `DM_KEYS="12:A,14:A,20:A,26:A,32:A"` reaches the opening course. diff --git a/dm/games/010015100B514000/patches.py b/dm/games/010015100B514000/patches.py new file mode 100644 index 0000000000..5534bec321 --- /dev/null +++ b/dm/games/010015100B514000/patches.py @@ -0,0 +1,16 @@ +# Super Mario Bros. Wonder (010015100B514000): the rewriter's patches of this game's own builds. dm/tools/patch_nso.py loads every profile's patches.py and applies those of a module's +# NSO build ID; CUTS, OBS and FRAME_STEP as described there ("Registered patches"). Patches of Nintendo SDK module builds are in dm/tools/sdk_patches.py +# The gate number is dm/host/dm.h's OBS_GRPC_ERROR (27), written as a number as patch_nso.py writes its own (a table name is the only upper-case name a patches.py may have) +OBS = { + # 1.2.1 (v327680) main, also Nextendo's signed patch of it (an IPS of three instructions in gRPC's TLS code that keeps the build ID): gRPC's grpc_error_create + # (const char *file, int line, const grpc_slice &desc, ...), called from 509 sites. Nintendo's gRPC has its logging compiled out, so an online call that fails before + # its first socket (2321-4992, UNAVAILABLE) leaves no line; the host logs each error's source file, line and text once (dm/host/hle_grpc.c). The entry instruction is + # sub sp, sp, #0x60 + 'ff773e90972d544eb79406eaa65396d5': [(0xb57b40, 27, 'd10183ff', "gRPC's grpc_error_create entry: the source file, line and text of each internal error (hle_grpc.c)")], +} +BINDING = [ + {'what': "gRPC's internal errors logged (grpc_error_create observation gate)", 'now': 'build', 'goal': 'engine', 'purpose': 'runtime', + 'kept': 'a read-only diagnostic for bringing up online play on one build; a gRPC-wide locator (a fingerprint of grpc_error_create) is worth it only when another game needs it', + 'why': "gRPC is middleware: its grpc_error_create could be found by a fingerprint in any game that links the same gRPC; it is placed by offset in the one build " + "brought up online so far"}, +] diff --git a/dm/games/0100152000022000/README.md b/dm/games/0100152000022000/README.md index ed0438f59e..4f5143d545 100644 --- a/dm/games/0100152000022000/README.md +++ b/dm/games/0100152000022000/README.md @@ -86,3 +86,7 @@ General host changes first needed here; each applies to every game: ## Open - Mii heads draw nothing unless the player supplies their console's MiiModel archive (`0100000000000802`) under `DM_SYSTEM_DIR` ([A console's own Mii database and system data](../../../docs/reference/services.md#a-consoles-own-mii-database-and-system-data)); not run with one, as no console files are on hand. + +### Native local-network contribution + +I tested LAN and LDN play across native Mac/iOS ports and a physical Switch on 2026-10-31, using 3.0.5 in my originating fork. My modified console used a compatible LDN module; this does not establish stock radio LDN. The rebased backend and local identity/resource requirements are documented under [native LAN and LDN](../../../docs/reference/services.md#opt-in-native-lan-sockets-and-ldn-over-ip). Automated fixtures are separate from a fresh hardware game qualification of this upstream branch. diff --git a/dm/games/settings.py b/dm/games/settings.py index 08c7270ff2..e58c4fa995 100644 --- a/dm/games/settings.py +++ b/dm/games/settings.py @@ -81,6 +81,7 @@ def shown(cond, n): if cond.startswith('fixups:'): return cond[7:] in keys if cond.startswith('gfxapi:'): return os.environ.get('GFXAPI', '') == cond[7:] if cond.startswith('platform:'): return platform == cond[9:] + if cond.startswith('build:'): return os.environ.get(cond[6:], '') not in ('', '0', 'NO') # an IPA build's switch (build_ipa.sh DM_NEXTENDO) m = re.fullmatch(r'(DM_GAME_\w+)(!=|==)(.*)', cond) if m: return (macro(m[1], n) == m[3]) == (m[2] == '==') sys.exit(f'settings.tsv:{n}: unknown condition {cond}') diff --git a/dm/games/settings.tsv b/dm/games/settings.tsv index 569507883a..ac02fcc62d 100644 --- a/dm/games/settings.tsv +++ b/dm/games/settings.tsv @@ -9,7 +9,7 @@ # | selects the platform's default before resolving a profile macro or build variable # shown always; DM_GAME_!= or ==; fixups:: main's rewriter table has that key (a stub in the game's build, patch_nso.py); languages>1 (more than one to pick, so also when the control data lists none); gfxapi:: the packer's GFXAPI; # mac-mic: a Mac app whose modules import the supported polling InputStream API; -# platform:: the app's platform (SETTINGS_PLATFORM, ios when unset), for a switch only that platform's front end reads +# platform:: the app's platform (SETTINGS_PLATFORM, ios when unset), for a switch only that platform's front end reads; build:: the IPA build's switch is on (set, not 0 or NO) # section Game, Controls or Performance: a heading on the single settings screen. Rows appear in table order within each section # Reset to tested defaults clears all launcher choices; values fixed by an env file stay # label, note the setting's name and the line under it (may be empty; only for a setting with a cost: latency, memory, heat) @@ -26,6 +26,7 @@ DM_FULLSCREEN choice 0=Window,1=Fullscreen 0 platform:mac Game Display mode lev DM_PICTURE_FIT choice fit=Fit,fill=Fill fit platform:ios Game Picture Fill crops the game's 16:9 picture to cover the screen. Health bars, subtitles or maps near the edges can be cut off. A full-screen picture without cropping needs a patch for each game. DM_ROTATION choice auto=Automatic,landscape=Landscape,portrait=Portrait auto platform:ios Game Rotation DM_SHOW_FPS toggle - build:DM_SHOW_FPS platform:ios Game Frame-rate counter +DM_NETWORK choice offline=Offline,lan=LAN,ldn=Local wireless,nextendo=Nextendo (online)?build:DM_NEXTENDO build:DM_NETWORK always Game Network LAN and Local wireless play with devices on the same Wi-Fi network. Nextendo plays online through Nextendo, a community service, once you sign in under Online. DM_TOUCH_HAPTICS toggle - 1 platform:ios Controls Touch feedback DM_RUMBLE toggle - 1 always Controls Game rumble level=basic DM_RUMBLE_GAIN range 0:3:0.1 1.0 always Controls Rumble strength needs=DM_RUMBLE=1 diff --git a/dm/host/Makefile b/dm/host/Makefile index 38c5c6dc95..9b5292dc69 100644 --- a/dm/host/Makefile +++ b/dm/host/Makefile @@ -19,12 +19,17 @@ include ../mac/min_os.mk # -O2 as the other native code here (libvpx, dav1d, the launcher; the iOS host builds at Xcode Release's -Os). Not -O3 (no measured gain over -O2) and not -flto, which moves # hle_bigstack.c's inline-assembly entry apart from its return path (SIGBUS in dm_bigstack_enter on Breath of the Wild, PR #556) CFLAGS=-O2 -g -Wall -Wno-unused-function -mmacosx-version-min=$(MACOS_MIN) +# Static, source-hash-pinned libcrypto for explicit private-PKI verification. +# Metadata targets do not build it; Apple targets select their own SDK archive. +DM_OPENSSL_ROOT ?= $(shell python3 ../tools/apple_crypto.py $(if $(filter iphoneos,$(MSL_SDK)),ios,macos)) +PRIVATE_PKI_FLAGS = -DDM_OPENSSL_X509 "-I$(DM_OPENSSL_ROOT)/include" +PRIVATE_PKI_LIB = "$(DM_OPENSSL_ROOT)/lib/libcrypto.a" # One job per core unless the command line sets -j: the host and the libraries below build one object per source (GNU make 3.81, the system's, takes -j from MAKEFLAGS set here) ifeq ($(filter -j%,$(MAKEFLAGS)),) MAKEFLAGS += -j$(shell getconf _NPROCESSORS_ONLN 2>/dev/null || echo 4) endif -# Service-layer takeover hle_*.c files are included by wildcard: adding a file does not touch this line (avoids merge conflicts) -SRC=main.c loader.c hle.c crash.c probe.c thread.c save_sync.c memstat.m haptics_apple.m audio_input.c audio_input_mac.m audio_input_dualsense_mac.m dualsense_mic_mac.c pad_switch2_apple.m $(sort $(wildcard hle_*.c)) front_mac.m web_apple.m entry.S +# Service-layer takeover hle_*.c/hle_*.m files are included by wildcard: adding a file does not touch this line (avoids merge conflicts) +SRC=main.c loader.c hle.c crash.c probe.c thread.c save_sync.c memstat.m haptics_apple.m audio_input.c audio_input_mac.m audio_input_dualsense_mac.m dualsense_mic_mac.c pad_switch2_apple.m $(sort $(wildcard hle_*.c hle_*.m)) front_mac.m web_apple.m entry.S # NVN null device + nn::vi + the Vulkan layer (dm/gfx/) # Sources under dm/gfx, dm/gfx/nvn, dm/gfx/tex, dm/gfx/vk and dm/gfx/gl are included by wildcard (tests/ and metal/ do not go into the host): adding a file does not touch this line GFX=$(sort $(wildcard ../gfx/*.c ../gfx/nvn/*.c ../gfx/nvn/*.m ../gfx/nvn/*.S ../gfx/tex/*.c ../gfx/tex/*.m ../gfx/vk/*.m ../gfx/gl/*.m)) @@ -70,13 +75,17 @@ game_profile: $(GAME_H) $(GAME_H): $(GAME_DIR)/game.tsv ../games/game.py FORCE @"$(PYTHON)" ../games/game.py header $(GAME) $@ .PHONY: FORCE +# The Mac Nextendo sign-in tool: make -C dm/host nextendo_login, then dm/host/nextendo_login sign-in (status, sign-out). dmhost reads the sign-in it keeps +# (hle_nextendo_login_apple.m, nextendo_login_apple.inc) +nextendo_login: ../tools/nextendo_login.m nextendo_login_apple.inc + clang -O1 -g -fobjc-arc -Wall -Wextra -mmacosx-version-min=$(MACOS_MIN) -o $@ ../tools/nextendo_login.m -framework Foundation -framework Security -framework AppKit FORCE: # The host: one object per source in gen//obj (dm.h includes the profile header, so every game has its own), compiled on every core, then linked into gen//dmhost with # the same flags (as clang's one-step compile and link gives each of its jobs the whole line) and its dSYM made from the objects, as clang does after its own link. Each object # lists the headers its source read (-MMD; -MP: a removed header is no error), so an edit rebuilds the objects that include it and the link; the Makefile (CFLAGS, these lines) # rebuilds them all. The generated headers come first (order-only: the dependency files name them for the sources that read them). The NSP script builds gen//dmhost and takes it -HOST_CFLAGS = $(CFLAGS) -I../gfx/nvn/include -I$(dir $(MSL_H)) -I../third_party/vulkan-headers/include -I$(dir $(GAME_H)) -I$(VPX) -I$(DAV1D)/include -I../third_party/stb_vorbis -fobjc-arc -HOST_FRAMEWORKS = -framework Cocoa -framework WebKit -framework UserNotifications -framework QuartzCore -framework Metal -framework MetalFX -framework GameController -framework CoreBluetooth -framework IOBluetooth -framework CoreHaptics -framework IOKit -framework IOUSBHost -framework AudioToolbox -framework CoreAudio -framework AVFAudio -framework CoreFoundation -framework CoreGraphics -framework VideoToolbox -framework CoreMedia -framework CoreVideo -framework ImageIO -framework UniformTypeIdentifiers +HOST_CFLAGS = $(CFLAGS) $(PRIVATE_PKI_FLAGS) -I../gfx/nvn/include -I$(dir $(MSL_H)) -I../third_party/vulkan-headers/include -I$(dir $(GAME_H)) -I$(VPX) -I$(DAV1D)/include -I../third_party/stb_vorbis -fobjc-arc +HOST_FRAMEWORKS = -framework Security -framework Cocoa -framework WebKit -framework UserNotifications -framework QuartzCore -framework Metal -framework MetalFX -framework GameController -framework CoreBluetooth -framework IOBluetooth -framework CoreHaptics -framework IOKit -framework IOUSBHost -framework AudioToolbox -framework CoreAudio -framework AVFAudio -framework CoreFoundation -framework CoreGraphics -framework VideoToolbox -framework CoreMedia -framework CoreVideo -framework ImageIO -framework UniformTypeIdentifiers HOST_SRC = $(SRC) $(GFX) ifneq ($(filter ../%,$(filter-out ../gfx/%,$(HOST_SRC))),) $(error host sources outside dm/host and dm/gfx need an object rule: $(filter ../%,$(filter-out ../gfx/%,$(HOST_SRC)))) @@ -84,16 +93,17 @@ endif OBJ_DIR = gen/$(GAME)/obj HOST_OBJ = $(foreach s,$(HOST_SRC),$(if $(filter ../gfx/%,$(s)),$(OBJ_DIR)/gfx/$(s:../gfx/%=%).o,$(OBJ_DIR)/host/$(s).o)) # the line's order: the link lays code out in it HOST_BIN = gen/$(GAME)/dmhost -$(OBJ_DIR)/host/%.o: % Makefile ../mac/min_os.mk | $(GAME_H) $(MSL_H) +$(OBJ_DIR)/host/%.o: % Makefile ../mac/min_os.mk ../tools/apple_crypto.py | $(GAME_H) $(MSL_H) @mkdir -p $(dir $@) clang $(HOST_CFLAGS) -MMD -MP -c $< -o $@ -$(OBJ_DIR)/gfx/%.o: ../gfx/% Makefile ../mac/min_os.mk | $(GAME_H) $(MSL_H) +$(OBJ_DIR)/gfx/%.o: ../gfx/% Makefile ../mac/min_os.mk ../tools/apple_crypto.py | $(GAME_H) $(MSL_H) @mkdir -p $(dir $@) clang $(HOST_CFLAGS) -MMD -MP -c $< -o $@ -$(HOST_BIN): $(HOST_OBJ) $(VPX_LIB) $(DAV1D_LIB) Makefile ../mac/min_os.mk - clang $(HOST_CFLAGS) -o $@ $(HOST_OBJ) $(VPX_LIB) $(DAV1D_LIB) $(HOST_FRAMEWORKS) +$(HOST_BIN): $(HOST_OBJ) $(VPX_LIB) $(DAV1D_LIB) Makefile ../mac/min_os.mk ../tools/apple_crypto.py + clang $(HOST_CFLAGS) -o $@ $(HOST_OBJ) $(VPX_LIB) $(DAV1D_LIB) $(PRIVATE_PKI_LIB) -lz $(HOST_FRAMEWORKS) ./$@ --check-tables || { rm -f $@; exit 1; } dsymutil $@ + ./$@ --validate-hle ifneq ($(strip $(GAME)),) -include $(HOST_OBJ:.o=.d) endif diff --git a/dm/host/account_local.h b/dm/host/account_local.h new file mode 100644 index 0000000000..84cc8ae459 --- /dev/null +++ b/dm/host/account_local.h @@ -0,0 +1,4 @@ +#pragma once +int dm_account_uid_exists(const void *uid); +// Copy the actual local UID; this grants no provider identity. +int dm_account_copy_uid(void *output); diff --git a/dm/host/discovery_protocol.h b/dm/host/discovery_protocol.h new file mode 100644 index 0000000000..23611365e0 --- /dev/null +++ b/dm/host/discovery_protocol.h @@ -0,0 +1,23 @@ +// Original framing recognizer for verified discovery queries, never game data. +// PiaLan facts were checked in the SDK's serializer; LDN uses the public wire. +#pragma once +#include +#include +#include +enum { DM_DISCOVERY_PIA=1, DM_DISCOVERY_LDN=2 }; +static inline unsigned dm_discovery_query_protocol(unsigned port,const void *bytes,size_t size) { + if(!bytes)return 0; + const uint8_t *p=bytes; + if(port==30000) { + if(size<0x12f||size>1364||p[0])return 0; + uint32_t payload=(uint32_t)p[1]<<24|(uint32_t)p[2]<<16|(uint32_t)p[3]<<8|p[4]; + if(payload>1364-0x12f||size!=payload+0x12f||p[payload+5]!=1||p[payload+6]>1)return 0; + unsigned nonce=0;for(unsigned i=0;i<8;++i)nonce|=p[payload+7+i]; + return nonce?DM_DISCOVERY_PIA:0; + } + if(port==11452) { + static const uint8_t query[12]={0,0x14,0x45,0x11}; + return size==sizeof query&&!memcmp(p,query,sizeof query)?DM_DISCOVERY_LDN:0; + } + return 0; +} diff --git a/dm/host/dm.h b/dm/host/dm.h index 38eb09e19b..c95bfa7f41 100644 --- a/dm/host/dm.h +++ b/dm/host/dm.h @@ -170,7 +170,8 @@ enum { OBS_UE_MALLOC = 21, // Unreal's FMa OBS_REGION_ASK = 22, OBS_REGION_GOT = 23, OBS_REGION_FREE = 24, // the SDK's address regions, gates the rewriter places by symbol in every sdk (patch_nso.py "Address regions", hle_svc.c) OBS_STDALLOC_INIT = 25, // StandardAllocator::Initialize's entry, the same way: its callback writes the size (hle_svc.c) OBS_UE_REGION = 26, // the store of Unreal's engine region size before nninitStartup reserves it: the register its upper bits name (dm/tools/ue_region.py, hle_svc.c) - OBS_MAX = 27 }; + OBS_GRPC_ERROR = 27, // gRPC's grpc_error_create entry (a profile's patches.py, Super Mario Bros. Wonder): source file, line and text of each internal error (hle_grpc.c) + OBS_MAX = 28 }; // A gate number's bits from 8 up are a parameter for its callback (OBS_REGION_GOT: the register that holds the address). Callbacks read the registers; a write to x0–x29 takes // effect when the gate returns (entry.S restores them from the frame), which OBS_STDALLOC_INIT and OBS_UE_REGION do void gate_obs_set(int id, void (*fn)(uint64_t *regs, int param)); diff --git a/dm/host/entry.S b/dm/host/entry.S index 9350b29edf..85a6f8aac2 100644 --- a/dm/host/entry.S +++ b/dm/host/entry.S @@ -113,6 +113,7 @@ _dm_gate: ldr x0, [sp, #240] // Return point = gate identifier mov x1, sp // regs bl _gate_dispatch +Ldm_gate_restore: ldr x9, [sp, #784] msr fpcr, x9 ldr x9, [sp, #776] @@ -158,6 +159,147 @@ _dm_gate: mov sp, x29 ret +// A blocking import is a guest pause boundary too. Its 32-byte stub holds x16, +// x17 and LR while this entry reaches the same per-thread gate stack as an SVC. +// The full frame and native work never overwrite the guest stack below the stub. + .globl _dm_hle_wait_enter + .private_extern _dm_hle_wait_enter + .p2align 2 +_dm_hle_wait_enter: + adrp x17, _g_keygate@PAGE + ldr x17, [x17, _g_keygate@PAGEOFF] + mrs x30, TPIDRRO_EL0 + ldr x17, [x30, x17, lsl #3] + adrp x30, _dm_gate_stubs@PAGE + add x30, x30, _dm_gate_stubs@PAGEOFF + sub x17, x17, x30 + lsr x17, x17, #4 + adrp x30, _dm_gate_top@PAGE + add x30, x30, _dm_gate_top@PAGEOFF + ldr x17, [x30, x17, lsl #3] + sub x17, x17, #800 + stp x0, x1, [x17, #0] + stp x2, x3, [x17, #16] + stp x4, x5, [x17, #32] + stp x6, x7, [x17, #48] + stp x8, x9, [x17, #64] + stp x10, x11, [x17, #80] + stp x12, x13, [x17, #96] + stp x14, x15, [x17, #112] + str x16, [x17, #248] + stp x18, x19, [x17, #144] + stp x20, x21, [x17, #160] + stp x22, x23, [x17, #176] + stp x24, x25, [x17, #192] + stp x26, x27, [x17, #208] + stp x28, x29, [x17, #224] + ldr x16, [sp] + str x16, [x17, #128] + ldr x16, [sp, #8] + str x16, [x17, #136] + ldr x16, [sp, #16] + str x16, [x17, #240] + mov x16, sp + add x16, x16, #32 + str x16, [x17, #792] + stp q0, q1, [x17, #256] + stp q2, q3, [x17, #288] + stp q4, q5, [x17, #320] + stp q6, q7, [x17, #352] + stp q8, q9, [x17, #384] + stp q10, q11, [x17, #416] + stp q12, q13, [x17, #448] + stp q14, q15, [x17, #480] + stp q16, q17, [x17, #512] + stp q18, q19, [x17, #544] + stp q20, q21, [x17, #576] + stp q22, q23, [x17, #608] + stp q24, q25, [x17, #640] + stp q26, q27, [x17, #672] + stp q28, q29, [x17, #704] + stp q30, q31, [x17, #736] + mrs x16, nzcv + str x16, [x17, #768] + mrs x16, fpsr + str x16, [x17, #776] + mrs x16, fpcr + str x16, [x17, #784] + // A host callback into guest code must not reuse an active gate frame. + mov x9, sp + add x10, x17, #800 + cmp x9, x10 + b.hs 1f + sub x10, x10, #0x100000 + cmp x9, x10 + b.lo 1f + mov sp, x17 + mov x0, x9 + bl _dm_gate_nested +1: mov sp, x17 + ldr x19, [sp, #248] + mov x0, sp + ldr x1, [sp, #240] + bl _thr_svc_enter + ldp x0, x1, [sp, #0] + ldp x2, x3, [sp, #16] + ldp x4, x5, [sp, #32] + ldp x6, x7, [sp, #48] + mov x16, x19 + bl _dm_bigstack_enter + mov x20, x0 + bl _thr_svc_leave + str x20, [sp, #0] + b Ldm_hle_wait_restore + +Ldm_hle_wait_restore: + ldr x9, [sp, #784] + msr fpcr, x9 + ldr x9, [sp, #776] + msr fpsr, x9 + ldr x9, [sp, #768] + msr nzcv, x9 + ldp q0, q1, [sp, #256] + ldp q2, q3, [sp, #288] + ldp q4, q5, [sp, #320] + ldp q6, q7, [sp, #352] + ldp q8, q9, [sp, #384] + ldp q10, q11, [sp, #416] + ldp q12, q13, [sp, #448] + ldp q14, q15, [sp, #480] + ldp q16, q17, [sp, #512] + ldp q18, q19, [sp, #544] + ldp q20, q21, [sp, #576] + ldp q22, q23, [sp, #608] + ldp q24, q25, [sp, #640] + ldp q26, q27, [sp, #672] + ldp q28, q29, [sp, #704] + ldp q30, q31, [sp, #736] + // A gate may modify any general-purpose register: svc out-parameters are in x0..x8, and the target of mrs cntpct can be any xN (14 of the 33 sites in sdk are x19..x23) + // ⇒ read back all of x0..x28 (x18 is the Apple platform register; the guest's x18 has been rewritten to the thread slot, so skip it and leave it alone). + // x29 / x30 are the gate block's to restore (from the words it pushed): here they carry the block's sp and the return point + ldp x0, x1, [sp, #0] + ldp x2, x3, [sp, #16] + ldp x4, x5, [sp, #32] + ldp x6, x7, [sp, #48] + ldp x8, x9, [sp, #64] + ldp x10, x11, [sp, #80] + ldp x12, x13, [sp, #96] + ldp x14, x15, [sp, #112] + ldp x16, x17, [sp, #128] + ldr x19, [sp, #152] + ldp x20, x21, [sp, #160] + ldp x22, x23, [sp, #176] + ldp x24, x25, [sp, #192] + ldp x26, x27, [sp, #208] + ldp x28, x29, [sp, #224] + ldr x30, [sp, #240] + ldr x17, [sp, #792] + sub x17, x17, #32 + mov sp, x17 + ldp x16, x17, [sp] + add sp, sp, #32 + ret + // 3) dm_thread_enter(entry, arg, sp): guest thread start. Switch to the guest stack given by the SDK and call entry with x0 = argument; // Horizon threads must exit via ExitThread; returning from entry is reported as an error. .globl _dm_thread_enter diff --git a/dm/host/friends_history.h b/dm/host/friends_history.h new file mode 100644 index 0000000000..093d838479 --- /dev/null +++ b/dm/host/friends_history.h @@ -0,0 +1,25 @@ +// Local friends-service registration keys. Firmware supplies the signing keys; +// no platform key material is compiled into the engine. +#pragma once +#include +#include + +enum { DM_FRIENDS_HISTORY_KEY_SIZE = 64, DM_FRIENDS_HISTORY_KEYRING_SIZE = 256 }; +enum { DM_FRIENDS_HISTORY_OK = 0, DM_FRIENDS_HISTORY_FAIL = 0x2a2, + DM_FRIENDS_HISTORY_INVALID_UID = 0x479 }; +// Optional embedding provider, registered before guest startup. It must copy +// eight consecutive 32-byte keys and must not call guest code. NULL restores the +// default reader: DM_SYSTEM_DATA_DIR/010000000000000e/files/play-history.keyring. +typedef bool (*dm_friends_history_key_provider)(uint8_t keyring[8][32]); +void dm_friends_history_set_key_provider(dm_friends_history_key_provider provider); +// uid points to 16 bytes. The HLE wrapper also checks that this local user exists. +// input_flag is the SDK's opaque boolean, preserved as flag & 1. This host's user +// has no linked Nintendo NSA ID: that field and its presence flag remain zero. +// UUIDv4 is persisted atomically under DM_ROOT/friends-history (or the working +// directory on iOS), before success. Failure clears a non-NULL 64-byte output. +uint32_t dm_friends_history_key(void *out, const void *uid, unsigned input_flag); + +#ifdef DM_FRIENDS_HISTORY_TEST +typedef void (*dm_friends_history_random_provider)(void *out, unsigned size); +void dm_friends_history_set_random_provider(dm_friends_history_random_provider provider); +#endif diff --git a/dm/host/hle.h b/dm/host/hle.h index 37430fffb1..029dac9b81 100644 --- a/dm/host/hle.h +++ b/dm/host/hle.h @@ -42,6 +42,10 @@ void *objmap_get(const void *guest); void objmap_put(const void *guest, void *host); void *objmap_del(const void *guest); uint64_t now_ns(void); +// A host hook implementing a blocking guest call gives up its guest core while actually waiting. +// Balanced and nestable; unrelated to GPU ownership or graphics suspension. +void dm_guest_host_wait_begin(void); +void dm_guest_host_wait_end(void); // A blocking native HLE wait releases the guest core. With the condition mutex // held, enter with 1 before waiting and balance with 0 after reacquiring it. void dm_thread_native_wait(int entering); @@ -80,14 +84,14 @@ typedef struct { const char *name; void *fn; const char *why; const char *to; } " adrp x16, _" #cname "@PAGE\n add x16, x16, _" #cname "@PAGEOFF\n" \ ".if " HLE_STR(HLE_NARG(__VA_ARGS__)) " > 8\n mov x17, #(((" HLE_STR(HLE_NARG(__VA_ARGS__)) " - 8) * 8 + 15) & ~15)\n" \ " b _dm_bigstack_enter_n\n.else\n b _dm_bigstack_enter\n.endif\n"); \ - DM_REGISTER("swforce", hle_force_ent, hle_force_##cname, {mangled, (void *)(uintptr_t)cname##_bs, why}); \ + DM_REGISTER("swforce", hle_force_ent, hle_force_##cname, {mangled, (void *)(uintptr_t)cname##_bs, why, NULL}); \ static ret cname(__VA_ARGS__) // Same as above, but the implementation runs on the caller's stack. Only for a take-over that runs the game's own code (an NRO's init and fini, a JIT plugin): that code's stack // use is the game's, sized for the thread's own stack (which can be larger than the 512 KB host stack), and it may switch stacks itself (a coroutine), which would reuse the // host stack the take-over is on. A short call into the SDK (fs::IsMounted, the audio renderer's command generation) is no reason. Say why beside it #define HLE_FORCE_DIRECT(mangled, why, ret, cname, ...) \ static ret cname(__VA_ARGS__); \ - DM_REGISTER("swforce", hle_force_ent, hle_force_##cname, {mangled, (void *)cname, why}); \ + DM_REGISTER("swforce", hle_force_ent, hle_force_##cname, {mangled, (void *)cname, why, NULL}); \ static ret cname(__VA_ARGS__) // A guest alias: every reference to mangled binds to the loaded modules' own definition of target instead, as if the module had imported target. No host code runs and no // signature is restated, so the alias holds for every SDK that defines both. For a hardware class whose constructor the host takes over to build the SDK's software class in the @@ -106,6 +110,17 @@ __attribute__((weak, naked, visibility("hidden"))) void dm_bigstack_enter_n(void void *dm_bigstack_caller(void *ra); __attribute__((weak, visibility("hidden"))) void *dm_bigstack_caller(void *ra) { return ra; } +// A blocking host takeover must publish the guest's real register context before waiting: a pause signal cannot stop host code safely. +// The static stub saves a full dm_gate frame, registers it with thr_svc_enter, runs the implementation on the big host stack, and waits for resume at thr_svc_leave before returning. +// Only <=8 integer/pointer arguments and an integer/pointer return in x0; no floating-point or stack arguments, variadics, or callbacks into guest code while the frame is published. +#define HLE_FORCE_WAIT(mangled, why, ret, cname, ...) \ + static ret cname(__VA_ARGS__) __attribute__((used)); \ + extern const char cname##_wait[]; \ + __asm__(".text\n.p2align 2\n.globl _" #cname "_wait\n.private_extern _" #cname "_wait\n_" #cname "_wait:\n" \ + " stp x16, x17, [sp, #-32]!\n str x30, [sp, #16]\n adrp x16, _" #cname "@PAGE\n add x16, x16, _" #cname "@PAGEOFF\n b _dm_hle_wait_enter\n"); \ + DM_REGISTER("swforce", hle_force_ent, hle_force_##cname, {mangled, (void *)(uintptr_t)cname##_wait, why, NULL}); \ + static ret cname(__VA_ARGS__) + // Host service sessions (hle_sf.c): a request on a session the host serves, as its service sees it, and the answer it fills in. The input is the raw CMIF data after the "SFCI" // header; the buffers are the client's A (send), B (receive) and X (pointer) descriptors, read and written in place (one address space); the output is the raw data after "SFCO", // zeroed beforehand. A service may copy one kernel handle to the client (an event's read end) and move one (a new session: an out object outside a domain) diff --git a/dm/host/hle_account.c b/dm/host/hle_account.c index d212e076af..83e8bbe17f 100644 --- a/dm/host/hle_account.c +++ b/dm/host/hle_account.c @@ -1,8 +1,14 @@ // nn::account: durable local profiles, process-local open sessions, and the native user selector. -// Online accounts remain unavailable. DM_NICK names user 1 (default Player). +// Online service identity belongs to the active user (the first user the game opens) only, and requires an explicit provider and an actual unexpired NEX proof. +// Nintendo Account authorization remains unavailable; OAuth is not a game credential. +// DM_NICK names user 1 (default Player); the active user is named by the Nextendo username in Nextendo mode unless DM_NICK names it; other users are Player N. #include "hle.h" #include "front.h" #include "account_users.h" +#include "account_local.h" +#include "nextendo_account.h" +#include "net_socket.h" +#include typedef struct { uint64_t v[2]; } Uid; typedef struct { uint64_t v[3]; } UserHandle; @@ -10,6 +16,32 @@ _Static_assert(sizeof(Uid) == 16 && sizeof(UserHandle) == 24, "account ABI"); static const Uid k_uid = {{DM_UID0, DM_UID1}}; static Uid user_uid(int i) { return (Uid){{DM_UID0 + (uint64_t)i, DM_UID1}}; } #define RES_ACC_CANCELED (124u | 1u << 9) +// The Nextendo account is the active user's: the first user the game opens a session for (open_user). That is the launch user when the game opens the +// preselected user, and the player's choice when it shows the user selector first. It is kept for the rest of the run: a user opened later (a second +// local player) must not move the online identity under a game that is already online. -1 until the game opens a user, and then no user is online +static _Atomic int g_active_user = -1; +int dm_account_uid_exists(const void *uid) { int user = atomic_load(&g_active_user); return user >= 0 && dm_uid_user(uid) == user; } +int dm_account_copy_uid(void *output) { + int user = atomic_load(&g_active_user); if (!output || user < 0) return 0; + Uid uid = user_uid(user); memcpy(output, &uid, sizeof uid); return 1; +} +// A handle carries its user's Uid in its first two words (the third is the session, GetUserId below) +static int online_user(const UserHandle *h) { return h && dm_account_uid_exists(h); } +// In Nextendo mode each online account call's answer is logged the first time it is given (the call, its result, and what the availability check said; never the +// token or the account), so a device log shows which step of a game's sign-in stopped. value: -1 none, 0 / 1 not available / available, -2 not the active user's handle +enum { ACC_NONE = -1, ACC_NOT_LOCAL = -2 }; +static Result acc_note(const char *call, Result r, int value) { + if (!dm_net_nextendo_enabled()) return r; + static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static struct { const char *call; Result r; int value; } seen[64]; static unsigned count; + pthread_mutex_lock(&lock); int fresh = 1; + for (unsigned i = 0; i < count; i++) if (seen[i].call == call && seen[i].r == r && seen[i].value == value) fresh = 0; + if (fresh && count < 64) { seen[count].call = call; seen[count].r = r; seen[count].value = value; count++; } + pthread_mutex_unlock(&lock); + if (fresh) LOG("%saccount: %s -> 0x%x%s", r ? "[RED] " : "", call, r, + value == ACC_NOT_LOCAL ? " (not the active user's handle)" : value == 1 ? " (available)" : value == 0 ? " (not available)" : ""); + return r; +} +#define ACC_USER(h) (online_user(h) ? ACC_NONE : ACC_NOT_LOCAL) // The SDK's third handle word owns a session. Give each open a unique token: // copied/stale/foreign handles must not close a different open of the same UID. @@ -40,7 +72,9 @@ static Result open_user(UserHandle *h, const Uid *uid) { pthread_mutex_lock(&g_account_lock); s->user = i; s->token = ++g_account_token; s->next = g_account_sessions; g_account_sessions = s; h->v[0] = uid->v[0]; h->v[1] = uid->v[1]; h->v[2] = s->token; g_last_user = i; - pthread_mutex_unlock(&g_account_lock); return RES_OK; + pthread_mutex_unlock(&g_account_lock); + int none = -1; if (atomic_compare_exchange_strong(&g_active_user, &none, i)) LOG("account: user %d is the active user (the Nextendo account's in Nextendo mode)", i + 1); + return RES_OK; } HLE_FORCE("_ZN2nn7account10InitializeEv", "connects to the local account service", void, h_acc_Init, void) { (void)dm_account_users(); } HLE_FORCE("_ZN2nn7account13ListOpenUsersEPiPNS0_3UidEi", "only users with a live account session", Result, h_acc_ListOpen, int *n, Uid *out, int max) { @@ -110,39 +144,107 @@ HLE_FORCE("_ZN2nn7account9GetUserIdEPNS0_3UidERKNS0_10UserHandleE", "gets the Ui // word. The game's own handles (third word 2 or 8) must continue to work. out->v[0] = h->v[0]; out->v[1] = h->v[1]; return RES_OK; } -HLE_FORCE("_ZN2nn7account11GetNicknameEPNS0_8NicknameERKNS0_3UidE", "DM_NICK for user 1, Player N for other registered users", Result, h_acc_GetNick, char *nick, const Uid *uid) { - int i = dm_account_user(uid); if (i < 0) return RES_FAIL; - user_nickname(nick, i); return RES_OK; +// nn::account::Nickname = struct { char name[33]; }, UTF-8. User 1: DM_NICK first. The active user in Nextendo mode: then the signed-in account's username (what other +// players and the Nextendo site see), read once and kept, as games ask for it often. Else Player for user 1, Player N for the other registered users +// A wait hook: the first call in Nextendo mode may fetch the sign-in over the network (hle_nextendo_login_apple.m) +HLE_FORCE_WAIT("_ZN2nn7account11GetNicknameEPNS0_8NicknameERKNS0_3UidE", "user 1's DM_NICK, else the active user's Nextendo username in Nextendo mode, else Player (user 1) or Player N", Result, h_acc_GetNick, char *nick, const Uid *uid) { + int user = dm_account_user(uid); if (user < 0) return RES_FAIL; + static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static char account[33]; + const char *e = user ? NULL : getenv("DM_NICK"); + memset(nick, 0, 33); + if (e) { // whole UTF-8 characters only, as the Nextendo name is cut + size_t n = strlen(e); if (n > 32) { n = 32; while (n && ((unsigned char)e[n] & 0xc0) == 0x80) n--; } + memcpy(nick, e, n); return RES_OK; + } + if (dm_net_nextendo_enabled() && dm_account_uid_exists(uid)) { + dm_guest_host_wait_begin(); pthread_mutex_lock(&lock); // a caller behind a fetch frees its guest core + if (!account[0] && !dm_nextendo_account_username(account)) LOG("account: nickname from the Nextendo account"); + memcpy(nick, account, 33); pthread_mutex_unlock(&lock); dm_guest_host_wait_end(); + if (nick[0]) return RES_OK; + } + user_nickname(nick, user); + return RES_OK; } -// ---------- Online accounts: cut ---------- -// The host has only local accounts. Return the result of cancelling the SDK account applet, -// ResultCancelledByUser (2124-0001). See "The network account check is cancelled offline" in docs/reference/services.md. -HLE_FORCE("_ZN2nn7account36EnsureNetworkServiceAccountAvailableERKNS0_10UserHandleE", "offline network account check returns applet cancellation", Result, h_acc_EnsureNsa, const UserHandle *h) { (void)h; return RES_ACC_CANCELED; } -HLE_FORCE("_ZN2nn7account26GetNetworkServiceAccountIdEPNS0_23NetworkServiceAccountIdERKNS0_10UserHandleE", "network service account, out of scope; cut", Result, h_acc_GetNsaId, void *id, const UserHandle *h) { (void)id; (void)h; return RES_FAIL; } -HLE_FORCE("_ZN2nn7account37LoadNetworkServiceAccountIdTokenCacheEPmPcmRKNS0_10UserHandleE", "network service account token, out of scope; cut", Result, h_acc_LoadTok, uint64_t *n, char *buf, uint64_t sz, const UserHandle *h) { - (void)buf; (void)sz; (void)h; if (n) *n = 0; return RES_FAIL; -} -HLE_FORCE("_ZN2nn7account40ShowLicenseRequirementsForNetworkServiceERKNS0_10UserHandleE", "online membership notice applet, out of scope; cut", Result, h_acc_ShowLic, const UserHandle *h) { (void)h; return RES_FAIL; } -// The Nintendo Account's cached profile (birthday, country): no Nintendo Account is linked on the host, so loading fails and the game skips its getters (Big Brain Academy: Brain vs. Brain, main+0xab8bc) -HLE_FORCE("_ZN2nn7account29LoadCachedNintendoAccountInfoEPNS0_25CachedNintendoAccountInfoERKNS0_10UserHandleEPvm", "cached Nintendo Account info: none linked, fails", Result, h_acc_LoadNaInfo, - void *info, const UserHandle *h, void *buf, uint64_t sz) { (void)info; (void)h; (void)buf; (void)sz; return RES_FAIL; } +// ---------- Online accounts ---------- +// Offline the host has only local accounts and returns the result of cancelling the SDK account applet, ResultCancelledByUser (2124-0001); see "The network account +// check is cancelled offline" in docs/reference/services.md. In Nextendo mode the active user's check needs the actual unexpired Nextendo NEX proof +HLE_FORCE_WAIT("_ZN2nn7account36EnsureNetworkServiceAccountAvailableERKNS0_10UserHandleE", "offline: applet cancellation; Nextendo mode: the active user's actual unexpired Nextendo NEX proof", Result, h_acc_EnsureNsa, const UserHandle *h) { + if (!dm_net_nextendo_enabled()) return RES_ACC_CANCELED; + return acc_note("EnsureNetworkServiceAccountAvailable", online_user(h) ? dm_nextendo_account_ensure() : RES_FAIL, ACC_USER(h)); +} +HLE_FORCE_WAIT("_ZN2nn7account26GetNetworkServiceAccountIdEPNS0_23NetworkServiceAccountIdERKNS0_10UserHandleE", "real provider PID or required server-reported BAAS identity", Result, h_acc_GetNsaId, uint64_t *id, const UserHandle *h) { if (id) *id = 0; return acc_note("GetNetworkServiceAccountId", online_user(h) ? dm_nextendo_account_id(id) : RES_FAIL, ACC_USER(h)); } +HLE_FORCE_WAIT("_ZN2nn7account37LoadNetworkServiceAccountIdTokenCacheEPmPcmRKNS0_10UserHandleE", "real NEX proof in the native game's cached account token", Result, h_acc_LoadTok, uint64_t *n, char *buf, uint64_t sz, const UserHandle *h) { + if (n) *n = 0; return acc_note("LoadNetworkServiceAccountIdTokenCache", online_user(h) ? dm_nextendo_account_load_token(n, buf, sz) : RES_FAIL, ACC_USER(h)); +} +HLE_FORCE("_ZN2nn7account40ShowLicenseRequirementsForNetworkServiceERKNS0_10UserHandleE", "online membership notice applet, out of scope; cut", Result, h_acc_ShowLic, const UserHandle *h) { (void)h; return acc_note("ShowLicenseRequirementsForNetworkService", RES_FAIL, ACC_NONE); } +// The Nintendo Account's cached profile (birthday, country). Offline no Nintendo Account is linked, so loading fails and the game skips its getters (Big Brain Academy: +// Brain vs. Brain, main+0xab8bc). In Nextendo mode, with the account signed in, it loads, as Ryujinx-Nextendo and Mush8 answer the account service's 0x68-byte NasUserBase +// (birthday at 0, country at 0x20) that the SDK copies into this object. The host never writes the object, whose layout in a given SDK is unchecked: it takes over the +// object's four getters, which return a string and its length. Country: the Nextendo account's (dm_nextendo_account_country), else the device's region (DM_NEXTENDO_COUNTRY, +// which the launcher sets), else none. Birthday: the Nextendo account's (dm_nextendo_account_birthday), else the launcher's picker (DM_NEXTENDO_BIRTHDAY, YYYY-MM-DD), else 2000-01-01, the date both of those clients send. Gender and region: none +static char na_country[3], na_birthday[11] = "2000-01-01"; // set by a successful load, before the game reads the getters +static int na_country_ok(const char *c) { return c && c[0] >= 'A' && c[0] <= 'Z' && c[1] >= 'A' && c[1] <= 'Z' && !c[2]; } +static int na_birthday_ok(const char *b) { + if (!b || strlen(b) != 10 || b[4] != '-' || b[7] != '-') return 0; + for (int i = 0; i < 10; i++) if (i != 4 && i != 7 && (b[i] < '0' || b[i] > '9')) return 0; + int month = (b[5] - '0') * 10 + b[6] - '0', day = (b[8] - '0') * 10 + b[9] - '0'; return month >= 1 && month <= 12 && day >= 1 && day <= 31; +} +HLE_FORCE_WAIT("_ZN2nn7account29LoadCachedNintendoAccountInfoEPNS0_25CachedNintendoAccountInfoERKNS0_10UserHandleEPvm", "cached Nintendo Account info: the Nextendo account's country and the launcher's birthday; offline none linked, fails", Result, h_acc_LoadNaInfo, + void *info, const UserHandle *h, void *buf, uint64_t sz) { + (void)info; if (buf && sz) memset(buf, 0, sz); + uint8_t available = 0; Result r = online_user(h) ? dm_nextendo_account_available(&available) : RES_FAIL; if (!r && !available) r = RES_FAIL; + if (!r) { + char country[3] = {0}; if (dm_nextendo_account_country(country) || !na_country_ok(country)) country[0] = 0; + const char *device = getenv("DM_NEXTENDO_COUNTRY"); if (!country[0] && na_country_ok(device)) memcpy(country, device, 3); + char account[11] = {0}; int own = !dm_nextendo_account_birthday(account) && na_birthday_ok(account); + const char *birthday = own ? account : getenv("DM_NEXTENDO_BIRTHDAY"), *use = birthday && na_birthday_ok(birthday) ? birthday : "2000-01-01"; + memcpy(na_country, country, 3); memcpy(na_birthday, use, 11); // use: 10 characters and the NUL (na_birthday_ok) + static int told; if (!told++) LOG("account: Nintendo Account info: country %s, birthday %s", na_country[0] ? "set" : "none", + own ? "from the Nextendo account" : na_birthday_ok(birthday) ? "from the launcher" : "2000-01-01"); + } + return acc_note("LoadCachedNintendoAccountInfo", r, online_user(h) ? ACC_NONE : ACC_NOT_LOCAL); +} +static const char *na_string(const char *s, uint64_t *n) { if (n) *n = strlen(s); return s; } +HLE_FORCE("_ZNK2nn7account25CachedNintendoAccountInfo10GetCountryEPm", "the loaded Nintendo Account country (two letters, or none)", const char *, h_acc_NaCountry, const void *self, uint64_t *n) { (void)self; return na_string(na_country, n); } +HLE_FORCE("_ZNK2nn7account25CachedNintendoAccountInfo11GetBirthdayEPm", "the loaded Nintendo Account birthday, YYYY-MM-DD", const char *, h_acc_NaBirthday, const void *self, uint64_t *n) { (void)self; return na_string(na_birthday, n); } +HLE_FORCE("_ZNK2nn7account25CachedNintendoAccountInfo9GetGenderEPm", "Nintendo Account gender: none", const char *, h_acc_NaGender, const void *self, uint64_t *n) { (void)self; return na_string("", n); } +HLE_FORCE("_ZNK2nn7account25CachedNintendoAccountInfo9GetRegionEPm", "Nintendo Account region: none", const char *, h_acc_NaRegion, const void *self, uint64_t *n) { (void)self; return na_string("", n); } -// AsyncContext / NintendoAccountAuthorizationRequestContext: no request is sent, the completion event fires immediately, and the result is always failure. +// Online membership (NetworkServiceLicenseKind: 0 none, 1 subscribed). Ryujinx-Nextendo (LoadNetworkServiceLicenseKindAsync) and Mush8 (IManagerForApplication 170) +// answer subscribed once the id-token request completes; the request here is the same one (dm_nextendo_async_ensure), and the kind is subscribed only when it succeeded. +// AsyncNetworkServiceLicenseInfoContext derives from AsyncContext (it has no getters of its own but this one): its SDK constructor runs, and the AsyncContext takeovers +// below serve its event, completion and result. Its own move operations and deleting destructor stay the SDK's, as its fields past the AsyncContext are unchecked: if they +// do not go through AsyncContext's (taken over), the request state stays with the old object and the kind reads none, which the log shows +HLE_FORCE_WAIT("_ZN2nn7account34LoadNetworkServiceLicenseInfoAsyncEPNS0_37AsyncNetworkServiceLicenseInfoContextERKNS0_10UserHandleE", "online membership: the id-token request; subscribed when it succeeds; offline, cut", Result, h_acc_LicenseAsync, + void *ctx, const UserHandle *h) { return acc_note("LoadNetworkServiceLicenseInfoAsync", online_user(h) ? dm_nextendo_async_ensure(ctx) : RES_FAIL, ACC_USER(h)); } +HLE_FORCE_WAIT("_ZN2nn7account37AsyncNetworkServiceLicenseInfoContext28GetNetworkServiceLicenseKindEv", "subscribed only after a successful Nextendo request", uint32_t, h_acc_LicenseKind, void *self) { + uint32_t kind = dm_net_nextendo_enabled() && dm_nextendo_async_result(self) == 0 ? 1 : 0; + acc_note("GetNetworkServiceLicenseKind", kind ? RES_OK : RES_FAIL, ACC_NONE); return kind; +} + +// AsyncContext / NintendoAccountAuthorizationRequestContext. // AsyncContext is built by the SDK's own constructor, which is not taken over: it writes the class's vtable and nulls the IPC object pointer at +0x18, and sends // nothing (SDK 19.3.11: sdk+0x1ad6c8). No interface below sets that pointer, so the SDK's destructor, reached through the vtable, finds no session to close. // The object is polymorphic: Pokémon Friends' C# binding deletes it from nn.account.AsyncContext's finalizer through the virtual deleting destructor, inlined // in main (main+0x5b64f0), which the D1Ev takeover below never sees. A host constructor that wrote no memory left the allocator's bytes in the vtable word, // and that call jumped through them (docs/reference/services.md, "An account AsyncContext needs its SDK constructor"). +// With Nextendo on (dm_net_nextendo_enabled), the request state (hle_nextendo_apple.m) is created when a request starts (dm_nextendo_async_execute). With it off, +// no request ever starts, and a context answers as the offline host always has: the completion event fires immediately, it is done, and the result is failure. // NintendoAccountAuthorizationRequestContext has no vtable: its constructor writes no memory, and its contents are read and written only by the interfaces below. -HLE_FORCE("_ZN2nn7account44EnsureNetworkServiceAccountIdTokenCacheAsyncEPNS0_12AsyncContextERKNS0_10UserHandleE", "network service account token, out of scope; cut", Result, h_acc_EnsureTokAsync, void *ctx, const UserHandle *h) { (void)ctx; (void)h; return RES_FAIL; } -HLE_FORCE("_ZN2nn7account12AsyncContext14GetSystemEventEPNS_2os11SystemEventE", "async completion event; fires immediately", Result, h_acc_AcGetEv, void *self, void *ev) { (void)self; hle_signal_system_event(ev); return RES_OK; } -HLE_FORCE("_ZN2nn7account12AsyncContext9GetResultEv", "async result; networking is cut, always fails", Result, h_acc_AcGetRes, void *self) { (void)self; return RES_FAIL; } +HLE_FORCE_WAIT("_ZN2nn7account44EnsureNetworkServiceAccountIdTokenCacheAsyncEPNS0_12AsyncContextERKNS0_10UserHandleE", "cache the real Nextendo NEX game token and publish its actual completion result; offline, cut", Result, h_acc_EnsureTokAsync, void *ctx, const UserHandle *h) { return acc_note("EnsureNetworkServiceAccountIdTokenCacheAsync", online_user(h) ? dm_nextendo_async_ensure(ctx) : RES_FAIL, ACC_USER(h)); } +HLE_FORCE("_ZN2nn7account12AsyncContext14GetSystemEventEPNS_2os11SystemEventE", "account completion event with a checked kernel-event lifetime; Nextendo off, it fires immediately", Result, h_acc_AcGetEv, void *self, void *ev) { + if (!dm_net_nextendo_enabled()) { hle_signal_system_event(ev); return RES_OK; } + uint64_t lifetime = dm_nextendo_async_lifetime(self); if (!ev || !lifetime) return RES_FAIL; + hle_bind_system_event(ev, 0); return dm_nextendo_async_attach(self, lifetime, hle_system_event_binding(ev)); +} +// Nextendo off, no request has started, and dm_nextendo_async_result returns DM_ACCOUNT_FAIL, RES_FAIL's value (nextendo_account.h) +HLE_FORCE_WAIT("_ZN2nn7account12AsyncContext9GetResultEv", "actual completed account request result; Nextendo off, failure", Result, h_acc_AcGetRes, void *self) { return acc_note("AsyncContext::GetResult", dm_nextendo_async_result(self), ACC_NONE); } HLE_FORCE("_ZN2nn7account42NintendoAccountAuthorizationRequestContextC1Ev", "Nintendo Account authorization, out of scope; the constructor writes no memory", void, h_acc_NaCtor, void *self) { (void)self; } HLE_FORCE("_ZN2nn7account42NintendoAccountAuthorizationRequestContextD1Ev", "Nintendo Account authorization, out of scope", void, h_acc_NaDtor, void *self) { (void)self; } HLE_FORCE("_ZN2nn7account41CreateNintendoAccountAuthorizationRequestEPNS0_42NintendoAccountAuthorizationRequestContextERKNS0_10UserHandleERKNS0_45NintendoAccountAuthorizationRequestParametersEPvm", "Nintendo Account authorization, out of scope; cut", Result, h_acc_NaCreate, void *ctx, const UserHandle *h, const void *prm, void *buf, uint64_t sz) { - (void)ctx; (void)h; (void)prm; (void)buf; (void)sz; return RES_FAIL; + (void)ctx; (void)h; (void)prm; (void)buf; (void)sz; return acc_note("CreateNintendoAccountAuthorizationRequest", RES_FAIL, ACC_NONE); } HLE_FORCE("_ZN2nn7account42NintendoAccountAuthorizationRequestContext14GetSystemEventEPNS_2os11SystemEventE", "authorization completion event; fires immediately", Result, h_acc_NaGetEv, void *self, void *ev) { (void)self; hle_signal_system_event(ev); return RES_OK; } HLE_FORCE("_ZN2nn7account42NintendoAccountAuthorizationRequestContext34GetResultWithInteractionIfRequiredEv", "authorization result; always fails", Result, h_acc_NaGetRes, void *self) { (void)self; return RES_FAIL; } @@ -193,7 +295,11 @@ HLE_FORCE("_ZN2nn7account27StoreSaveDataThumbnailImageERKNS0_3UidEPKvm", "save-d (void)uid; (void)img; (void)n; return RES_OK; } HLE_FORCE("_ZN2nn7account28DeleteSaveDataThumbnailImageERKNS0_3UidE", "save-data thumbnail; the host keeps none", Result, h_acc_DeleteThumb, const Uid *uid) { (void)uid; return RES_OK; } -HLE_FORCE("_ZN2nn7account32IsNetworkServiceAccountAvailableEPbRKNS0_10UserHandleE", "network service account, out of scope; always unavailable", Result, h_acc_NsaAvail, uint8_t *out, const UserHandle *h) { (void)h; *out = 0; return RES_OK; } +HLE_FORCE_WAIT("_ZN2nn7account32IsNetworkServiceAccountAvailableEPbRKNS0_10UserHandleE", "only a coherent unexpired Nextendo NEX credential enables the active user's NSA; other users have none", Result, h_acc_NsaAvail, uint8_t *out, const UserHandle *h) { + if (!out) return RES_FAIL; *out = 0; + Result r = online_user(h) ? dm_nextendo_account_available(out) : RES_OK; // another user has no network service account: not available + return acc_note("IsNetworkServiceAccountAvailable", r, online_user(h) ? *out != 0 : ACC_NOT_LOCAL); +} HLE_FORCE("_ZN2nn7account9CloseUserERKNS0_10UserHandleE", "close exactly this session; other opens remain live", void, h_acc_CloseUser, const UserHandle *h) { if (!h) return; int user = dm_uid_user(h); @@ -203,7 +309,28 @@ HLE_FORCE("_ZN2nn7account9CloseUserERKNS0_10UserHandleE", "close exactly this se if (*p) { account_session *s = *p; *p = s->next; free(s); } pthread_mutex_unlock(&g_account_lock); } -HLE_FORCE("_ZN2nn7account12AsyncContext6CancelEv", "async context cancel; no request", Result, h_acc_AcCancel, void *self) { (void)self; return RES_OK; } -HLE_FORCE("_ZN2nn7account12AsyncContext7HasDoneEPb", "async context: always done", Result, h_acc_AcHasDone, void *self, uint8_t *done) { (void)self; *done = 1; return RES_OK; } -HLE_FORCE("_ZN2nn7account12AsyncContextD1Ev", "async context destructor; no session to close", void, h_acc_AcDtor, void *self) { (void)self; } -HLE_FORCE("_ZN2nn7account12AsyncContextaSEOS1_", "async context move assignment; the object holds no host state", void *, h_acc_AcMove, void *self, void *other) { (void)other; return self; } +// Nextendo off (see AsyncContext above), a context has nothing to cancel and is done +static Result acc_done(void *self, uint8_t *done) { if (dm_net_nextendo_enabled()) return dm_nextendo_async_done(self, done); if (!done) return RES_FAIL; *done = 1; return RES_OK; } +HLE_FORCE_WAIT("_ZN2nn7account12AsyncContext6CancelEv", "cancel an account request without publishing a late success; Nextendo off, nothing to cancel", Result, h_acc_AcCancel, void *self) { return dm_net_nextendo_enabled() ? dm_nextendo_async_cancel(self) : RES_OK; } +HLE_FORCE_WAIT("_ZN2nn7account12AsyncContext7HasDoneEPb", "actual account request completion; Nextendo off, done", Result, h_acc_AcHasDone, void *self, uint8_t *done) { return acc_done(self, done); } +HLE_FORCE_WAIT("_ZN2nn7account12AsyncContextD1Ev", "destroy owned account request state", void, h_acc_AcDtor, void *self) { dm_nextendo_async_destroy(self); } +HLE_FORCE_WAIT("_ZN2nn7account12AsyncContextaSEOS1_", "move account request state and its event lifetimes", void *, h_acc_AcMove, void *self, void *other) { return dm_nextendo_async_move(self, other); } + +// Additional SDK service overloads use the same provider and object lifetime. +HLE_FORCE_WAIT("_ZNK2nn7account12AsyncContext9GetResultEv", "actual completed account request result, SDK 19 const overload", Result, h_acc_AcGetResConst, void *self) { return acc_note("AsyncContext::GetResult", dm_nextendo_async_result(self), ACC_NONE); } +HLE_FORCE_WAIT("_ZNK2nn7account12AsyncContext7HasDoneEPb", "actual account request completion, SDK 19 const overload; Nextendo off, done", Result, h_acc_AcHasDoneConst, void *self, uint8_t *done) { return acc_done(self, done); } +HLE_FORCE_WAIT("_ZN2nn7account12AsyncContextD2Ev", "destroy owned account request state", void, h_acc_AcDtor2, void *self) { dm_nextendo_async_destroy(self); } +HLE_FORCE("_ZN2nn7account12AsyncContextD0Ev", "destroy account request state and release its guest allocation", void, h_acc_AcDeletingDtor, void *self) { + dm_nextendo_async_destroy(self); void (*release)(void *) = (void (*)(void *))guest_sym("_ZdlPv"); + if (release) release(self); else LOG("[RED] account: guest operator delete unavailable for AsyncContext"); +} +// A move constructor builds a new object, so it writes what the SDK constructor writes (see AsyncContext above): the vtable, taken from the source, which the SDK +// constructed, and a null IPC object pointer at +0x18 (the source's is null too: no interface here sets it). The request state then moves with the object. +static void acc_move_construct(void *self, void *other) { + if (self && other) { *(void **)self = *(void **)other; *(void **)((char *)self + 0x18) = NULL; } + dm_nextendo_async_move(self, other); +} +HLE_FORCE_WAIT("_ZN2nn7account12AsyncContextC1EOS1_", "move-construct: the SDK's vtable and request state", void, h_acc_AcMoveCtor, void *self, void *other) { acc_move_construct(self, other); } +HLE_FORCE_WAIT("_ZN2nn7account12AsyncContextC2EOS1_", "move-construct: the SDK's vtable and request state", void, h_acc_AcMoveCtor2, void *self, void *other) { acc_move_construct(self, other); } +HLE_FORCE_WAIT("_ZN2nn7account12AsyncContext4SwapERS1_", "swap owned account request state", void, h_acc_AcSwap, void *self, void *other) { dm_nextendo_async_swap(self, other); } +HLE_FORCE_WAIT("_ZNK2nn7account12AsyncContextcvbEv", "whether an account request owns an actual operation", unsigned, h_acc_AcValid, void *self) { return dm_nextendo_async_valid(self); } diff --git a/dm/host/hle_bcat.c b/dm/host/hle_bcat.c new file mode 100644 index 0000000000..88c5059419 --- /dev/null +++ b/dm/host/hle_bcat.c @@ -0,0 +1,101 @@ +// Original SDK-facing delivery cache. File/directory objects own real immutable +// file handles; synchronization progress reflects the actual public downloader. +#include "hle.h" +#include "nextendo_bcat.h" +#include +#include +#include +#include +#include + +typedef struct { char name[32]; int64_t size; unsigned char digest[16]; } BcatEntry; +typedef struct { uint64_t lo,hi; } BcatDigest; +_Static_assert(sizeof(BcatEntry)==0x38,"SDK delivery directory entry"); +_Static_assert(sizeof(BcatDigest)==16,"AAPCS64 digest returns in x0/x1"); +enum { BCAT_FILE=1,BCAT_DIRECTORY=2,BCAT_PROGRESS=3,BCAT_OBJECTS=128 }; +typedef struct { + void *object;int kind,fd;BcatEntry entries[64];int count,cursor,opened; + BcatDigest digest;unsigned status,result;uint64_t downloaded;void *observer; +} BcatObject; +static BcatObject objects[BCAT_OBJECTS]; +static pthread_mutex_t bcatLock=PTHREAD_MUTEX_INITIALIZER; +static BcatObject *find(void *object,int kind){for(int i=0;ifd>=0)close(o->fd);if(o->observer)dm_bcat_sync_release(o->observer);memset(o,0,sizeof *o);o->fd=-1;} +static void create(void *object,int kind){ + if(!object)return;pthread_mutex_lock(&bcatLock); + for(int i=0;i126||s[i]=='/'||s[i]=='\\'||s[i]==':')return 0;return 1;} +static int directory_fd(const char *directory){char root[1024];if(!component(directory)||!dm_bcat_copy_delivery(root,sizeof root))return -1;int base=open(root,O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);if(base<0)return -1;int fd=openat(base,directory,O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);close(base);return fd;} +static int file_digest(int fd,BcatDigest *digest,int64_t *size){struct stat st;if(fstat(fd,&st)||!S_ISREG(st.st_mode)||st.st_size<0||st.st_size>8*1024*1024)return 0;size_t length=(size_t)st.st_size;void *bytes=malloc(length?length:1);if(!bytes)return 0;size_t done=0;while(donename,((const BcatEntry *)b)->name);} + +HLE_FORCE("_ZN2nn4bcat17DeliveryCacheFileC1Ev","construct host-owned read-only delivery file",void,h_bcat_FileCtor,void *object){create(object,BCAT_FILE);} +HLE_FORCE("_ZN2nn4bcat17DeliveryCacheFileC2Ev","construct host-owned read-only delivery file",void,h_bcat_FileCtor2,void *object){create(object,BCAT_FILE);} +HLE_FORCE("_ZN2nn4bcat17DeliveryCacheFileD1Ev","close delivery file",void,h_bcat_FileDtor,void *object){destroy(object,BCAT_FILE);} +HLE_FORCE("_ZN2nn4bcat17DeliveryCacheFileD2Ev","close delivery file",void,h_bcat_FileDtor2,void *object){destroy(object,BCAT_FILE);} +HLE_FORCE("_ZN2nn4bcat17DeliveryCacheFile5CloseEv","close a delivery file while keeping its reusable object",void,h_bcat_FileClose,void *object){pthread_mutex_lock(&bcatLock);BcatObject *o=find(object,BCAT_FILE);if(o){if(o->fd>=0)close(o->fd);o->fd=-1;o->digest=(BcatDigest){0};}pthread_mutex_unlock(&bcatLock);} +HLE_FORCE("_ZN2nn4bcat17DeliveryCacheFile4OpenERKNS0_13DirectoryNameERKNS0_8FileNameE","open a real file in the verified immutable delivery snapshot",Result,h_bcat_FileOpen,void *object,const char *directory,const char *name){ + if(!component(name))return RES_FAIL;int parent=directory_fd(directory);if(parent<0)return RES_FAIL;int fd=openat(parent,name,O_RDONLY|O_CLOEXEC|O_NOFOLLOW);close(parent);if(fd<0)return RES_FAIL; + BcatDigest digest;if(!file_digest(fd,&digest,NULL)){close(fd);return RES_FAIL;} + pthread_mutex_lock(&bcatLock);BcatObject *o=find(object,BCAT_FILE);if(o){if(o->fd>=0)close(o->fd);o->fd=fd;o->digest=digest;}else close(fd);pthread_mutex_unlock(&bcatLock);return o?RES_OK:RES_FAIL; +} +HLE_FORCE("_ZN2nn4bcat17DeliveryCacheFile4ReadEPmlPvm","bounded positional read from a real delivery file",Result,h_bcat_FileRead,void *object,uint64_t *out,int64_t offset,void *buffer,size_t size){ + if(!out||offset<0||(!buffer&&size)||size>INT64_MAX)return RES_FAIL;*out=0;pthread_mutex_lock(&bcatLock);BcatObject *o=find(object,BCAT_FILE);ssize_t n=-1;if(o&&o->fd>=0)n=pread(o->fd,buffer,size,(off_t)offset);if(n>=0)*out=(uint64_t)n;pthread_mutex_unlock(&bcatLock);return n>=0?RES_OK:RES_FAIL; +} +HLE_FORCE("_ZN2nn4bcat17DeliveryCacheFile9GetDigestEv","MD5 of the opened delivery bytes, returned as the SDK 16-byte value",BcatDigest,h_bcat_FileDigest,void *object){pthread_mutex_lock(&bcatLock);BcatObject *o=find(object,BCAT_FILE);int opened=o&&o->fd>=0;BcatDigest result=opened?o->digest:(BcatDigest){0};pthread_mutex_unlock(&bcatLock);if(!opened)die("BCAT GetDigest requires an opened delivery file");return result;} +HLE_FORCE("_ZN2nn4bcat17DeliveryCacheFile7GetSizeEv","size of the opened delivery file",int64_t,h_bcat_FileSize,void *object){pthread_mutex_lock(&bcatLock);BcatObject *o=find(object,BCAT_FILE);struct stat st;int opened=o&&o->fd>=0&&!fstat(o->fd,&st);int64_t size=opened?st.st_size:0;pthread_mutex_unlock(&bcatLock);if(!opened)die("BCAT GetSize requires an opened delivery file");return size;} + +HLE_FORCE("_ZN2nn4bcat22DeliveryCacheDirectoryC1Ev","construct delivery directory",void,h_bcat_DirCtor,void *object){create(object,BCAT_DIRECTORY);} +HLE_FORCE("_ZN2nn4bcat22DeliveryCacheDirectoryC2Ev","construct delivery directory",void,h_bcat_DirCtor2,void *object){create(object,BCAT_DIRECTORY);} +HLE_FORCE("_ZN2nn4bcat22DeliveryCacheDirectoryD1Ev","release directory snapshot",void,h_bcat_DirDtor,void *object){destroy(object,BCAT_DIRECTORY);} +HLE_FORCE("_ZN2nn4bcat22DeliveryCacheDirectoryD2Ev","release directory snapshot",void,h_bcat_DirDtor2,void *object){destroy(object,BCAT_DIRECTORY);} +HLE_FORCE("_ZN2nn4bcat22DeliveryCacheDirectory5CloseEv","close the opened directory snapshot",void,h_bcat_DirClose,void *object){pthread_mutex_lock(&bcatLock);BcatObject *o=find(object,BCAT_DIRECTORY);if(o){o->count=o->cursor=o->opened=0;}pthread_mutex_unlock(&bcatLock);} +HLE_FORCE("_ZN2nn4bcat22DeliveryCacheDirectory8GetCountEv","count of entries in the opened real directory snapshot",int,h_bcat_DirCount,void *object){pthread_mutex_lock(&bcatLock);BcatObject *o=find(object,BCAT_DIRECTORY);int opened=o&&o->opened;int count=opened?o->count:0;pthread_mutex_unlock(&bcatLock);if(!opened)die("BCAT GetCount requires an opened delivery directory");return count;} +HLE_FORCE("_ZN2nn4bcat22DeliveryCacheDirectory4OpenERKNS0_13DirectoryNameE","snapshot real delivery entries, sizes and digests",Result,h_bcat_DirOpen,void *object,const char *directory){ + int fd=directory_fd(directory);if(fd<0)return RES_FAIL;DIR *dir=fdopendir(fd);if(!dir){close(fd);return RES_FAIL;} + BcatEntry entries[64];int count=0,ok=1;struct dirent *entry; + while((entry=readdir(dir))){if(!strcmp(entry->d_name,".")||!strcmp(entry->d_name,".."))continue;if(!component(entry->d_name)||count==64){ok=0;break;} + int file=openat(fd,entry->d_name,O_RDONLY|O_CLOEXEC|O_NOFOLLOW);BcatDigest digest;int64_t size;if(file<0||!file_digest(file,&digest,&size)){if(file>=0)close(file);ok=0;break;}close(file); + BcatEntry *e=&entries[count++];memset(e,0,sizeof *e);strlcpy(e->name,entry->d_name,sizeof e->name);e->size=size;memcpy(e->digest,&digest,16);} + closedir(dir);if(!ok)return RES_FAIL;qsort(entries,(size_t)count,sizeof entries[0],compare_entries); + pthread_mutex_lock(&bcatLock);BcatObject *o=find(object,BCAT_DIRECTORY);if(o){memcpy(o->entries,entries,(size_t)count*sizeof entries[0]);o->count=count;o->cursor=0;o->opened=1;}pthread_mutex_unlock(&bcatLock);return o?RES_OK:RES_FAIL; +} +HLE_FORCE("_ZN2nn4bcat22DeliveryCacheDirectory4ReadEPiPNS0_27DeliveryCacheDirectoryEntryEi","bounded enumeration of the opened directory snapshot",Result,h_bcat_DirRead,void *object,int *out,BcatEntry *entries,int capacity){ + if(!out||capacity<0||(!entries&&capacity))return RES_FAIL;*out=0; + pthread_mutex_lock(&bcatLock);BcatObject *o=find(object,BCAT_DIRECTORY); + if(!o||!o->opened){pthread_mutex_unlock(&bcatLock);return RES_FAIL;} + int n=o->count-o->cursor; + if(n<0){pthread_mutex_unlock(&bcatLock);return RES_FAIL;} + if(n>capacity)n=capacity; + if(n>0){ + if(!entries){pthread_mutex_unlock(&bcatLock);return RES_FAIL;} + memcpy(entries,o->entries+o->cursor,(size_t)n*sizeof *entries); + } + o->cursor+=n;*out=n;pthread_mutex_unlock(&bcatLock);return RES_OK; +} +HLE_FORCE("_ZN2nn4bcat31EnumerateDeliveryCacheDirectoryEPiPNS0_13DirectoryNameEi","enumerate real delivery directories",Result,h_bcat_Enumerate,int *out,char (*names)[32],int capacity){ + if(!out||capacity<0||(!names&&capacity))return RES_FAIL;*out=0;char root[1024];if(!dm_bcat_copy_delivery(root,sizeof root))return RES_FAIL;DIR *dir=opendir(root);if(!dir)return RES_FAIL;struct dirent *e;int total=0;char found[64][32]; + while((e=readdir(dir))){struct stat st;if(!component(e->d_name))continue;if(fstatat(dirfd(dir),e->d_name,&st,AT_SYMLINK_NOFOLLOW)||!S_ISDIR(st.st_mode))continue;if(total==64){closedir(dir);return RES_FAIL;}strlcpy(found[total++],e->d_name,32);}closedir(dir);qsort(found,(size_t)total,32,(int(*)(const void*,const void*))strcmp);int n=totalstatus=(unsigned)dm_bcat_sync_observer_status(o->observer,&result,&downloaded);o->result=o->status==9&&result?RES_FAIL:RES_OK;o->downloaded=downloaded;} +HLE_FORCE("_ZN2nn4bcat24RequestSyncDeliveryCacheEPNS0_21DeliveryCacheProgressE","observe a real background HTTPS calendar refresh",Result,h_bcat_Sync,void *object){ + pthread_mutex_lock(&bcatLock);BcatObject *o=find(object,BCAT_PROGRESS);void *observer=o?dm_bcat_sync_observe():NULL; + // SDK 3 attaches a successful request by releasing the previous service and + // replacing its state. A failed request leaves that observer untouched. + if(observer){if(o->observer)dm_bcat_sync_release(o->observer);o->observer=observer;progress_update(o);} + pthread_mutex_unlock(&bcatLock);return observer?RES_OK:RES_FAIL; +} +HLE_FORCE("_ZN2nn4bcat21DeliveryCacheProgress6UpdateEv","copy actual synchronization state",void,h_bcat_ProgressUpdate,void *object){pthread_mutex_lock(&bcatLock);BcatObject *o=find(object,BCAT_PROGRESS);if(o&&o->observer)progress_update(o);pthread_mutex_unlock(&bcatLock);} +HLE_FORCE("_ZNK2nn4bcat21DeliveryCacheProgress9GetStatusEv","SDK status: zero before request, connecting or done9 after real completion",unsigned,h_bcat_ProgressStatus,const void *object){pthread_mutex_lock(&bcatLock);BcatObject *o=find((void*)object,BCAT_PROGRESS);unsigned status=o?o->status:0;pthread_mutex_unlock(&bcatLock);return status;} +HLE_FORCE("_ZNK2nn4bcat21DeliveryCacheProgress9GetResultEv","final validation/download result; pending is not completion (status must be done9)",Result,h_bcat_ProgressResult,const void *object){pthread_mutex_lock(&bcatLock);BcatObject *o=find((void*)object,BCAT_PROGRESS);Result result=o?o->result:RES_FAIL;pthread_mutex_unlock(&bcatLock);return result;} +HLE_FORCE("_ZNK2nn4bcat21DeliveryCacheProgress18GetWholeDownloadedEv","validated delivery bytes after a completed refresh",uint64_t,h_bcat_ProgressDownloaded,const void *object){pthread_mutex_lock(&bcatLock);BcatObject *o=find((void*)object,BCAT_PROGRESS);uint64_t n=o?o->downloaded:0;pthread_mutex_unlock(&bcatLock);return n;} diff --git a/dm/host/hle_bcat_apple.m b/dm/host/hle_bcat_apple.m new file mode 100644 index 0000000000..450ab0f7be --- /dev/null +++ b/dm/host/hle_bcat_apple.m @@ -0,0 +1,426 @@ +// Original Nextendo calendar importer. Provider files are data in private caches, +// never source assets. HTTPS authenticates downloads; the signed game catalog +// authenticates eligibility, NOT the (currently unsigned) calendar ZIP itself. +#import +#include "nextendo_bcat.h" +#include +#ifdef DM_OPENSSL_X509 +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Only the pre-guest launch check shares this total network budget across its +// catalog, archive and optional static-resource requests. Tool/runtime refreshes +// retain their existing per-request limits. No wall-clock or cache-age shortcut. +static _Thread_local uint64_t launchDeadline; +static uint64_t monotonicTime(void){return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);} + +static NSString *const provider = @"https://nextendo.network"; +static NSString *const catalogURL = @"https://nextendo.network/service-catalog/v1/game-catalog"; +static NSString *const recipeCommit = @"482c182917228d69ebbbabfea44fffa4a44051be"; +static const NSUInteger zipLimit = 8 * 1024 * 1024, expandedLimit = 32 * 1024 * 1024; +static NSString *const xmlHash = @"8d8d21a93dce2f8eab1659a3bf5cdca10f61df83d50bc0a34784b1629dd215fa"; +static NSString *const dummyHash = @"5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9"; +// The titles whose calendar recipe this backend knows, as lowercase program IDs, and the one among them whose delivery has no DebugUnderPilot files. A build passes them as +// Objective-C string literals (-DDM_BCAT_TITLES=..., -DDM_BCAT_PLAIN_TITLE=...; the BCAT fixtures pass Splatoon 2's), because a game's IDs belong to its profile, not the host +// (test_architecture), and this tree has no profile of those games. Without them no title is supported and the calendar stays off +#ifndef DM_BCAT_TITLES +#define DM_BCAT_TITLES +#endif +#ifndef DM_BCAT_PLAIN_TITLE +#define DM_BCAT_PLAIN_TITLE @"" +#endif +static NSArray *titles(void) { return @[DM_BCAT_TITLES]; } +int dm_bcat_supported(const char *title) { if(!title)return 0;NSString *value=[NSString stringWithUTF8String:title];return value&&[titles() containsObject:value.lowercaseString]; } +static NSString *digest(NSData *data) { uint8_t h[32]; CC_SHA256(data.bytes, (CC_LONG)data.length, h); NSMutableString *s = [NSMutableString new]; for (int i=0;i<32;i++) [s appendFormat:@"%02x",h[i]]; return s; } +static BOOL fail(NSString **error, NSString *message) { if (error) *error = message; return NO; } +static BOOL integer(id n) { if(![n isKindOfClass:NSNumber.class]||CFGetTypeID((__bridge CFTypeRef)n)==CFBooleanGetTypeID())return NO;int64_t value;return CFNumberGetValue((__bridge CFNumberRef)n,kCFNumberSInt64Type,&value)&&[n compare:@(value)]==NSOrderedSame; } +static BOOL validETag(id tag){return [tag isKindOfClass:NSString.class]&&[tag length]&&[tag length]<=256&&[tag rangeOfCharacterFromSet:NSCharacterSet.controlCharacterSet].location==NSNotFound;} +static BOOL safePath(NSString *path) { + if (![path isKindOfClass:NSString.class] || !path.length || path.length > 240 || [path hasPrefix:@"/"] || [path containsString:@"\\"] || [path containsString:@":"]) return NO; + for (NSString *p in [path componentsSeparatedByString:@"/"]) { + if (!p.length || [p isEqual:@"."] || [p isEqual:@".."] || p.length > 128) return NO; + for (NSUInteger i=0;i126) return NO; } + } + return YES; +} +static BOOL safeDirectory(NSString *path, BOOL create) { + if (![path hasPrefix:@"/"] || path.length > 800) return NO; + NSString *walk = @"/"; + for (NSString *part in path.pathComponents) { + if ([part isEqual:@"/"]) continue; + if ([part isEqual:@"."] || [part isEqual:@".."] || !part.length) return NO; + walk = [walk stringByAppendingPathComponent:part]; struct stat st; + if (lstat(walk.fileSystemRepresentation,&st)) { + if (!create || errno != ENOENT || mkdir(walk.fileSystemRepresentation,0700)) return NO; + } else if (!S_ISDIR(st.st_mode)) return NO; + } + return YES; +} +static NSData *boundedRead(NSString *path, NSUInteger max) { + int fd=open(path.fileSystemRepresentation,O_RDONLY|O_CLOEXEC|O_NOFOLLOW); if(fd<0)return nil; + struct stat s; if(fstat(fd,&s)||!S_ISREG(s.st_mode)||s.st_size<0||(uint64_t)s.st_size>max){close(fd);return nil;} + NSMutableData *d=[NSMutableData dataWithLength:(NSUInteger)s.st_size]; size_t done=0; + while(donepn&&whitespace(s->b[s->p]))s->p++;} +static NSString *scanString(JSONScan *s){NSUInteger a=s->p;if(s->p>=s->n||s->b[s->p++]!='"')return nil;while(s->pn){uint8_t c=s->b[s->p++];if(c=='"'){NSData *d=[NSData dataWithBytes:s->b+a length:s->p-a];return [NSJSONSerialization JSONObjectWithData:d options:NSJSONReadingFragmentsAllowed error:nil];}if(c=='\\'&&s->pn)s->p++;}return nil;} +static BOOL scanValue(JSONScan *s,unsigned depth){ + if(depth>32)return NO;ws(s);if(s->p>=s->n)return NO;uint8_t c=s->b[s->p]; + if(c=='"')return scanString(s)!=nil; + if(c=='{'||c=='['){s->p++;ws(s);uint8_t end=c=='{'?'}':']';NSMutableSet *keys=[NSMutableSet new];if(s->pn&&s->b[s->p]==end){s->p++;return YES;} + for(;;){if(c=='{'){ws(s);NSString *k=scanString(s);if(!k||[keys containsObject:k])return NO;[keys addObject:k];ws(s);if(s->p>=s->n||s->b[s->p++]!=':')return NO;} + if(!scanValue(s,depth+1))return NO;ws(s);if(s->p>=s->n)return NO;uint8_t next=s->b[s->p++];if(next==end)return YES;if(next!=',')return NO;}} + NSUInteger a=s->p;while(s->pn&&s->b[s->p]!=','&&s->b[s->p]!=']'&&s->b[s->p]!='}'&&!whitespace(s->b[s->p]))s->p++;return s->p>a; +} +static NSDictionary *json(NSData *data){if(!data.length||data.length>1048576)return nil;JSONScan s={data.bytes,data.length,0};if(!scanValue(&s,0))return nil;ws(&s);if(s.p!=s.n)return nil;id v=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];return [v isKindOfClass:NSDictionary.class]?v:nil;} +static NSDate *date(id value){if(![value isKindOfClass:NSString.class]||![value hasSuffix:@"Z"]||[value length]>40)return nil;NSISO8601DateFormatter *f=[NSISO8601DateFormatter new];f.formatOptions=NSISO8601DateFormatWithInternetDateTime|NSISO8601DateFormatWithFractionalSeconds;NSDate *d=[f dateFromString:value];if(d)return d;f.formatOptions=NSISO8601DateFormatWithInternetDateTime;return [f dateFromString:value];} +static BOOL verifyCatalogSignature(NSData *key,NSData *sig,NSData *payload){ +#ifdef DM_OPENSSL_X509 + EVP_PKEY *pk=EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519,NULL,key.bytes,key.length);EVP_MD_CTX *ctx=EVP_MD_CTX_new(); + BOOL verified=pk&&ctx&&EVP_DigestVerifyInit(ctx,NULL,NULL,NULL,pk)==1&&EVP_DigestVerify(ctx,sig.bytes,sig.length,payload.bytes,payload.length)==1;EVP_MD_CTX_free(ctx);EVP_PKEY_free(pk); + return verified; +#else + // No optional crypto provider: BCAT remains unavailable. Never treat an + // unchecked local manifest or HTTPS response as verified calendar data. + (void)key;(void)sig;(void)payload;return NO; +#endif +} +static NSDictionary *catalogWithKey(NSData *envelope, NSString *title, NSString *version, BOOL fresh, NSInteger minimum, NSData *key, NSString **error){ + NSDictionary *outer=json(envelope);NSString *encoded=outer[@"payload"],*signature=outer[@"signature"]; + if(![outer[@"key_id"] isEqual:@"catalog-key-1"]||![encoded isKindOfClass:NSString.class]||![signature isKindOfClass:NSString.class]){fail(error,@"Invalid signed calendar eligibility document");return nil;} + NSData *payload=[[NSData alloc]initWithBase64EncodedString:encoded options:0],*sig=[[NSData alloc]initWithBase64EncodedString:signature options:0]; + if(!payload||sig.length!=64||![[payload base64EncodedStringWithOptions:0] isEqual:encoded]||![[sig base64EncodedStringWithOptions:0] isEqual:signature]){fail(error,@"Invalid catalog encoding");return nil;} + if(!verifyCatalogSignature(key,sig,payload)){fail(error,@"Calendar eligibility signature failed or verifier unavailable");return nil;} + NSDictionary *p=json(payload);NSDate *issued=date(p[@"issued_at"]),*expires=date(p[@"expires_at"]);NSTimeInterval now=NSDate.date.timeIntervalSince1970; + if(![p[@"document_type"] isEqual:@"game_catalog"]||!integer(p[@"schema_version"])||[p[@"schema_version"] integerValue]!=1||!integer(p[@"revision"])||[p[@"revision"] integerValue]86400||issued.timeIntervalSince1970>now+300||(fresh&&expires.timeIntervalSince1970<=now)) {fail(error,@"Calendar eligibility expired, rolled back or malformed");return nil;} + NSArray *games=p[@"games"];if(![games isKindOfClass:NSArray.class]||games.count>10000){fail(error,@"Invalid catalog games");return nil;} + NSMutableSet *seen=[NSMutableSet new];NSDictionary *match=nil; + for(id game in games){if(![game isKindOfClass:NSDictionary.class])return nil;NSArray *ids=game[@"title_ids"];if(![ids isKindOfClass:NSArray.class]||!ids.count||ids.count>32)return nil; + for(id idValue in ids){if(![idValue isKindOfClass:NSString.class]||[idValue length]!=16||[idValue rangeOfCharacterFromSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefABCDEF"] invertedSet]].location!=NSNotFound)return nil;NSString *tid=[idValue lowercaseString];if(!strtoull(tid.UTF8String,NULL,16)||[seen containsObject:tid])return nil;[seen addObject:tid];if([tid isEqual:title])match=game;}} + if(!match||![match[@"enabled"] isKindOfClass:NSNumber.class]||CFGetTypeID((__bridge CFTypeRef)match[@"enabled"])!=CFBooleanGetTypeID()||![match[@"enabled"] boolValue]){fail(error,@"No enabled BCAT game in the verified catalog");return nil;} + NSArray *caps=match[@"required_capabilities"];if(![caps isKindOfClass:NSArray.class]||caps.count>64||[NSSet setWithArray:caps].count!=caps.count)return nil; + for(id cap in caps)if(![@[@"versions.exact.v1",@"versions.any.v1"] containsObject:cap]){fail(error,@"Unsupported calendar eligibility capability");return nil;} + NSDictionary *versions=match[@"versions"];BOOL accepted=NO; + if([versions isKindOfClass:NSDictionary.class]){ + if([versions[@"policy"] isEqual:@"any"]&&[caps containsObject:@"versions.any.v1"]&&!versions[@"accepted"]&&!versions[@"recommended"])accepted=YES; + NSArray *values=versions[@"accepted"]; + if([versions[@"policy"] isEqual:@"exact"]&&[caps containsObject:@"versions.exact.v1"]&&[values isKindOfClass:NSArray.class]&&values.count&&values.count<=64&&[NSSet setWithArray:values].count==values.count){ + BOOL valid=YES;for(id v in values)if(![v isKindOfClass:NSString.class]||![v length]||[v length]>32||![[v stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet] isEqual:v]||[v rangeOfCharacterFromSet:NSCharacterSet.controlCharacterSet].location!=NSNotFound){valid=NO;break;} + id preferred=versions[@"recommended"]?:values[0];accepted=valid&&[values containsObject:preferred]&&[values containsObject:version]; + } + } + if(!accepted){fail(error,@"The game version is not accepted for calendar preparation");return nil;}return p; +} + +static NSDictionary *catalog(NSData *data, NSString *title, NSString *version, BOOL fresh, NSInteger minimum, NSString **error) { + NSData *key=[[NSData alloc]initWithBase64EncodedString:@"xI+atR6VesrCH89ZDZD4t3WQLcYOFEhk5F0HLMzgWk4=" options:0]; + return catalogWithKey(data,title,version,fresh,minimum,key,error); +} + +@interface DmBcatDownload : NSObject +@property(nonatomic,strong) NSMutableData *bytes; +@property(nonatomic) NSUInteger limit; +@property(nonatomic) NSInteger status; +@property(nonatomic,strong) NSString *etag; +@property(nonatomic) BOOL failed; +@property(nonatomic,strong) dispatch_semaphore_t done; +@end +@implementation DmBcatDownload +-(void)URLSession:(NSURLSession *)s task:(NSURLSessionTask *)t willPerformHTTPRedirection:(NSHTTPURLResponse *)r newRequest:(NSURLRequest *)q completionHandler:(void (^)(NSURLRequest *))completion {self.failed=YES;completion(nil);} +-(void)URLSession:(NSURLSession *)s dataTask:(NSURLSessionDataTask *)t didReceiveResponse:(NSURLResponse *)r completionHandler:(void (^)(NSURLSessionResponseDisposition))completion { + if(![r isKindOfClass:NSHTTPURLResponse.class]){self.failed=YES;completion(NSURLSessionResponseCancel);return;} + NSHTTPURLResponse *h=(id)r;self.status=h.statusCode; + if(r.expectedContentLength>(int64_t)self.limit||![r.URL isEqual:t.originalRequest.URL]){self.failed=YES;completion(NSURLSessionResponseCancel);return;} + id tag=h.allHeaderFields[@"Etag"]?:h.allHeaderFields[@"ETag"];if(validETag(tag))self.etag=tag; + completion(NSURLSessionResponseAllow); +} +-(void)URLSession:(NSURLSession *)s dataTask:(NSURLSessionDataTask *)t didReceiveData:(NSData *)d {if(d.length>self.limit-self.bytes.length){self.failed=YES;[t cancel];}else[self.bytes appendData:d];} +-(void)URLSession:(NSURLSession *)s task:(NSURLSessionTask *)t didCompleteWithError:(NSError *)e {if(e)self.failed=YES;dispatch_semaphore_signal(self.done);} +@end +static NSData *download(NSString *url, NSUInteger limit, NSString *etag, NSInteger *status, NSString **newTag){ + if(status)*status=0;if(newTag)*newTag=nil; + uint64_t now=monotonicTime();if(launchDeadline&&now>=launchDeadline)return nil; + NSTimeInterval remaining=launchDeadline?(launchDeadline-now)/(double)NSEC_PER_SEC:30; + NSURL *u=[NSURL URLWithString:url];if(![u.scheme isEqual:@"https"]||u.user||u.password||u.port||u.fragment)return nil; + if(!([u.host isEqual:@"nextendo.network"]||([u.host isEqual:@"raw.githubusercontent.com"]&&[u.path hasPrefix:[@"/NextendoNetwork/Prelude-Nextendo/" stringByAppendingString:recipeCommit]])))return nil; + DmBcatDownload *d=[DmBcatDownload new];d.bytes=[NSMutableData new];d.limit=limit;d.done=dispatch_semaphore_create(0); + NSURLSessionConfiguration *c=NSURLSessionConfiguration.ephemeralSessionConfiguration;c.HTTPCookieStorage=nil;c.HTTPShouldSetCookies=NO;c.URLCredentialStorage=nil;c.URLCache=nil;c.requestCachePolicy=NSURLRequestReloadIgnoringLocalCacheData;c.timeoutIntervalForRequest=MIN(15,remaining);c.timeoutIntervalForResource=MIN(25,remaining); + NSOperationQueue *queue=[NSOperationQueue new];queue.maxConcurrentOperationCount=1;NSURLSession *s=[NSURLSession sessionWithConfiguration:c delegate:d delegateQueue:queue]; + NSMutableURLRequest *r=[NSMutableURLRequest requestWithURL:u];[r setValue:@"nxnative/BCAT" forHTTPHeaderField:@"User-Agent"]; + if(validETag(etag))[r setValue:etag forHTTPHeaderField:@"If-None-Match"]; + NSURLSessionDataTask *task=[s dataTaskWithRequest:r];[task resume]; + uint64_t deadline=launchDeadline?:now+30*NSEC_PER_SEC;BOOL finished=NO; + while((now=monotonicTime())7)return NO;for(unsigned i=4;i<16;i+=4){uint32_t offset=le?u32(b+i):((uint32_t)b[i]<<24|(uint32_t)b[i+1]<<16|b[i+2]<<8|b[i+3]);if(offset&&((offset&3)||offset>=data.length))return NO;}return YES;} + if([path.pathExtension isEqual:@"bfres"])return data.length>=32&&!memcmp(data.bytes,"FRES",4); + if([path.pathExtension isEqual:@"szs"]){ + if(data.length>=16&&(!memcmp(data.bytes,"Yaz0",4)||!memcmp(data.bytes,"SARC",4)))return YES; + // The pinned provider revision also publishes two exact short marker + // resources under .szs names. They are not compressed archives. Retain + // only those authenticated bytes; never accept arbitrary text as SZS. + NSDictionary *markers=@{@"fesdata/Fld_Deli_Octa24.Nin_NX_NVN.szs":@"4be0e8f7f609db1fb9e96f58299d7bca6848208f055e7af394a0a9c65e1fe2ed",@"fesdata/Fld_Deli_Octa24_Vss.szs":@"431b9113111518d3b389d97f89eee213150959f2453f6a4edec61690ef8ae16a"}; + return markers[path]&&[digest(data) isEqual:markers[path]]; + } + return NO; +} +static BOOL scheduleName(NSString *path){return safePath(path)&&[path componentsSeparatedByString:@"/"].count==2&&[@[@"coopdata",@"vsdata",@"fesdata"] containsObject:[path componentsSeparatedByString:@"/"][0]]&&[@[@"byaml",@"bfres",@"szs"] containsObject:path.pathExtension];} +/* ZIP central directory is authoritative only after matching every local header. + * No symlinks, extras, duplicate/case-alias paths, ZIP64, encryption or overlap. + * Deflate output and CRC are checked before any file becomes visible. */ +static NSDictionary *unzip(NSData *zip, NSString **error){ + const uint8_t *b=zip.bytes;NSUInteger n=zip.length;if(n<22||n>zipLimit){fail(error,@"Calendar archive exceeds its bounds");return nil;} + NSUInteger end=NSNotFound;for(NSUInteger p=n-22;;p--){if(u32(b+p)==0x06054b50&&p+22+u16(b+p+20)==n){end=p;break;}if(!p||n-p>65557)break;} + if(end==NSNotFound||u16(b+end+4)||u16(b+end+6)||u16(b+end+8)!=u16(b+end+10)){fail(error,@"Invalid calendar ZIP directory");return nil;} + unsigned count=u16(b+end+10);NSUInteger central=u32(b+end+16),centralSize=u32(b+end+12);if(!count||count>64||central>end||centralSize!=end-central){fail(error,@"Invalid calendar ZIP bounds");return nil;} + NSMutableDictionary *files=[NSMutableDictionary new];NSMutableSet *names=[NSMutableSet new];NSMutableArray *ranges=[NSMutableArray new];NSUInteger at=central,total=0; + for(unsigned i=0;iend||u32(b+at)!=0x02014b50)goto invalid;unsigned flags=u16(b+at+8),method=u16(b+at+10),nameLen=u16(b+at+28),extra=u16(b+at+30),comment=u16(b+at+32);uint32_t packed=u32(b+at+20),size=u32(b+at+24),crc=u32(b+at+16);NSUInteger local=u32(b+at+42); + if(flags&~(8|0x800)||(method!=0&&method!=8)||u16(b+at+34)||!nameLen||nameLen>240||at+46+nameLen+extra+comment>end||size>8*1024*1024||size>expandedLimit-total||!size||(((u32(b+at+38)>>16)&0170000)&&((u32(b+at+38)>>16)&0170000)!=0100000))goto invalid; + NSString *name=[[NSString alloc]initWithBytes:b+at+46 length:nameLen encoding:NSUTF8StringEncoding];if(!scheduleName(name)||[names containsObject:name.lowercaseString])goto invalid;[names addObject:name.lowercaseString]; + if(local+30>central||u32(b+local)!=0x04034b50||u16(b+local+6)!=flags||u16(b+local+8)!=method||u16(b+local+26)!=nameLen)goto invalid; + NSUInteger start=local+30+nameLen+u16(b+local+28);if(start>central||packed>central-start||memcmp(b+local+30,b+at+46,nameLen))goto invalid; + if(!(flags&8)&&(u32(b+local+14)!=crc||u32(b+local+18)!=packed||u32(b+local+22)!=size))goto invalid; + NSUInteger stop=start+packed; + if(flags&8){BOOL signedDD=stop+4<=central&&u32(b+stop)==0x08074b50;NSUInteger dd=stop+(signedDD?4:0);if(dd+12>central||u32(b+dd)!=crc||u32(b+dd+4)!=packed||u32(b+dd+8)!=size)goto invalid;stop=dd+12;} + for(NSValue *v in ranges){NSRange r=v.rangeValue;if(local68)return nil; + NSData *signedData=boundedRead([root stringByAppendingPathComponent:@"catalog.json"],1048576); + NSDictionary *verified=catalog(signedData,title,version,NO,0,NULL); + if(!verified||![digest(signedData) isEqual:m[@"catalogSHA256"]]||![verified[@"revision"] isEqual:m[@"catalogRevision"]])return nil; + NSDictionary *files=m[@"files"];NSMutableSet *found=[NSMutableSet new];NSString *base=[root stringByAppendingPathComponent:@"files"]; + NSDirectoryEnumerator *it=[NSFileManager.defaultManager enumeratorAtPath:base];for(NSString *rel in it){NSString *path=[base stringByAppendingPathComponent:rel];struct stat st;if(!safePath(rel)||lstat(path.fileSystemRepresentation,&st)||S_ISLNK(st.st_mode))return nil;if(S_ISDIR(st.st_mode))continue;if(!S_ISREG(st.st_mode)||!files[rel])return nil;NSData *data=boundedRead(path,8*1024*1024);if(!data||![digest(data) isEqual:files[rel]])return nil;[found addObject:rel];} + if(found.count!=files.count)return nil; + for(NSString *name in @[@"coopdata/CoopSetting.byaml",@"vsdata/VSSetting_0.byaml",@"vsdata/VSSetting_1.byaml",@"fesdata/Festival.byaml",@"fesdata/HapTexture.bfres",@"fesdata/IconTexture.bfres",@"fesdata/PanelTexture.bfres"]){NSString *rel=[@"DebugUnderPilot/bcat" stringByAppendingPathComponent:name];NSData *data=boundedRead([base stringByAppendingPathComponent:rel],8*1024*1024);if(!fileFormat(name,data))return nil;} + if(![title isEqual:DM_BCAT_PLAIN_TITLE]){if(![files[@"System/GameConfigSetting.xml"] isEqual:xmlHash]||![files[@"DebugUnderPilot/bcat/dummy/dummy.txt"] isEqual:dummyHash])return nil;} + return m; +} +static NSString *snapshotIdentity(NSDictionary *m){return digest(jsonData(@{@"files":m[@"files"],@"title":m[@"titleID"],@"version":m[@"version"],@"recipe":m[@"recipe"],@"revision":m[@"catalogRevision"],@"catalog":m[@"catalogSHA256"]}));} +static NSString *current(NSString *cache,NSString *title,NSString *version){NSDictionary *p=json(boundedRead([cache stringByAppendingPathComponent:@"current.json"],4096));NSString *name=p[@"snapshot"];if(![name isKindOfClass:NSString.class]||name.length!=64||[name rangeOfCharacterFromSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdef"] invertedSet]].location!=NSNotFound)return nil;NSString *root=[[cache stringByAppendingPathComponent:@"snapshots"] stringByAppendingPathComponent:name];NSDictionary *m=snapshot(root,title,version);return m&&[snapshotIdentity(m) isEqual:name]?root:nil;} +int dm_bcat_validate(const char *title,const char *version,const char *directory){@autoreleasepool{ + if(!dm_bcat_supported(title)||!version||strcmp(version,"5.5.2")||!directory)return 0; + return current([NSString stringWithUTF8String:directory],[[NSString stringWithUTF8String:title] lowercaseString],[NSString stringWithUTF8String:version])!=nil; +}} +static BOOL publishLocked(NSString *cache,NSString *title,NSString *version,NSData *envelope,NSString *old,NSString **error){ + NSDictionary *oldManifest=old?snapshot(old,title,version):nil;NSInteger minimum=[oldManifest[@"catalogRevision"] integerValue];NSDictionary *policy=catalog(envelope,title,version,YES,minimum,error);if(!policy)return NO; + if(oldManifest){NSDictionary *previous=catalog(boundedRead([old stringByAppendingPathComponent:@"catalog.json"],1048576),title,version,NO,0,NULL); + NSDate *previousIssued=date(previous[@"issued_at"]),*issued=date(policy[@"issued_at"]); + if(!previous||!previousIssued||!issued)return fail(error,@"Calendar eligibility changed during validation; previous calendar retained"); + if([previous[@"revision"] isEqual:policy[@"revision"]]&&[issued compare:previousIssued]==NSOrderedAscending)return fail(error,@"Catalog issue time rolled back; previous calendar retained");} + NSInteger status=0;NSString *etag=nil;NSData *zip=download([provider stringByAppendingFormat:@"/api/bcat/%@",title],zipLimit,oldManifest[@"etag"],&status,&etag); + BOOL unchanged=zip&&status==304&&oldManifest&&[oldManifest[@"etag"] isKindOfClass:NSString.class]&&[oldManifest[@"etag"] length]&&(!etag||[etag isEqual:oldManifest[@"etag"]]);NSMutableDictionary *contents=[NSMutableDictionary new]; + if(unchanged){ + for(NSString *path in oldManifest[@"files"]){NSData *data=boundedRead([[old stringByAppendingPathComponent:@"files"] stringByAppendingPathComponent:path],8*1024*1024);if(!data)return fail(error,@"Calendar cache changed during validation");contents[path]=data;} + etag=etag?:oldManifest[@"etag"]; + }else{ + if(!zip||status!=200)return fail(error,status==204?@"No calendar has been published for this title":@"Calendar download unavailable; previous validated snapshot retained"); + NSDictionary *entries=unzip(zip,error);if(!entries)return NO; + for(NSString *name in entries)contents[[@"DebugUnderPilot/bcat" stringByAppendingPathComponent:name]]=entries[name]; + if(![title isEqual:DM_BCAT_PLAIN_TITLE]){ + NSDictionary *staticFiles=@{@"System/GameConfigSetting.xml":xmlHash,@"DebugUnderPilot/bcat/dummy/dummy.txt":dummyHash}; + for(NSString *path in staticFiles){NSData *data=nil;NSString *oldPath=[[old stringByAppendingPathComponent:@"files"] stringByAppendingPathComponent:path];if(old)data=boundedRead(oldPath,131072); + if(!data||![digest(data) isEqual:staticFiles[path]]){NSString *u=[NSString stringWithFormat:@"https://raw.githubusercontent.com/NextendoNetwork/Prelude-Nextendo/%@/romfs/bcatdata/%@/romfs/%@",recipeCommit,title.uppercaseString,path];data=download(u,131072,nil,&status,NULL);if(status!=200)data=nil;} + if(!data||![digest(data) isEqual:staticFiles[path]])return fail(error,@"Static calendar resource integrity check failed");contents[path]=data;} + } + } + NSMutableDictionary *hashes=[NSMutableDictionary new];for(NSString *path in contents)hashes[path]=digest(contents[path]); + NSMutableDictionary *manifest=[@{@"formatVersion":@1,@"titleID":title,@"version":version,@"recipe":recipeCommit,@"source":[provider stringByAppendingFormat:@"/api/bcat/%@",title],@"archiveSHA256":unchanged?oldManifest[@"archiveSHA256"]:digest(zip),@"catalogRevision":policy[@"revision"],@"catalogSHA256":digest(envelope),@"fetchedAt":@(NSDate.date.timeIntervalSince1970),@"files":hashes} mutableCopy];if(etag)manifest[@"etag"]=etag; + NSData *m=jsonData(manifest);NSString *name=snapshotIdentity(manifest),*snapshots=[cache stringByAppendingPathComponent:@"snapshots"],*destination=[snapshots stringByAppendingPathComponent:name]; + if(!safeDirectory(snapshots,YES))return fail(error,@"Unsafe calendar cache directory"); + if(snapshot(destination,title,version))return atomicWrite(jsonData(@{@"snapshot":name}),[cache stringByAppendingPathComponent:@"current.json"]); + NSString *temporary=[snapshots stringByAppendingPathComponent:[@".stage-" stringByAppendingString:NSUUID.UUID.UUIDString]];if(!safeDirectory(temporary,YES))return fail(error,@"Cannot stage calendar snapshot"); + BOOL ok=YES;for(NSString *path in contents)if(!atomicWrite(contents[path],[[temporary stringByAppendingPathComponent:@"files"] stringByAppendingPathComponent:path])){ok=NO;break;} + if(ok)ok=atomicWrite(envelope,[temporary stringByAppendingPathComponent:@"catalog.json"])&&atomicWrite(m,[temporary stringByAppendingPathComponent:@"manifest.json"])&&snapshot(temporary,title,version)!=nil; + if(ok&&rename(temporary.fileSystemRepresentation,destination.fileSystemRepresentation))ok=NO; + if(!ok){[NSFileManager.defaultManager removeItemAtPath:temporary error:nil];return fail(error,@"Calendar snapshot publication failed; previous snapshot retained");} + if(!atomicWrite(jsonData(@{@"snapshot":name}),[cache stringByAppendingPathComponent:@"current.json"]))return fail(error,@"Cannot publish calendar snapshot pointer");return YES; +} +static BOOL publish(NSString *cache,NSString *title,NSString *version,NSData *envelope,NSString *old,NSString **error){ + if(!safeDirectory(cache,YES))return fail(error,@"Unsafe calendar cache directory"); + NSString *lockPath=[cache stringByAppendingPathComponent:@".update.lock"]; + int fd=open(lockPath.fileSystemRepresentation,O_RDWR|O_CREAT|O_CLOEXEC|O_NOFOLLOW,0600); + if(fd<0)return fail(error,@"Calendar cache lock unavailable"); + struct stat st;BOOL acquired=!fstat(fd,&st)&&S_ISREG(st.st_mode)&&st.st_uid==geteuid()&&!flock(fd,LOCK_EX|LOCK_NB); + if(!acquired){close(fd);return fail(error,@"Another calendar refresh is in progress");} + // Only the exclusive updater removes its own abandoned staging directories. + // Published snapshots and the currently running game's resources stay intact. + NSString *snapshots=[cache stringByAppendingPathComponent:@"snapshots"]; + for(NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:snapshots error:nil]){ + if(![name hasPrefix:@".stage-"]||![[NSUUID alloc]initWithUUIDString:[name substringFromIndex:7]])continue; + NSString *path=[snapshots stringByAppendingPathComponent:name];if(!lstat(path.fileSystemRepresentation,&st)&&S_ISDIR(st.st_mode))[NSFileManager.defaultManager removeItemAtPath:path error:nil]; + } + NSString *newer=current(cache,title,version); + if(newer){NSDictionary *have=snapshot(newer,title,version),*before=old?snapshot(old,title,version):nil; + if(!before||[have[@"catalogRevision"] longLongValue]>=[before[@"catalogRevision"] longLongValue])old=newer;} + BOOL ok=publishLocked(cache,title,version,envelope,old,error);flock(fd,LOCK_UN);close(fd);return ok; +} +int dm_bcat_prepare(const char *titleC,const char *versionC,const char *catalogC,const char *destinationC,char *error,size_t errorSize){@autoreleasepool{ + NSString *title=titleC?[[NSString stringWithUTF8String:titleC] lowercaseString]:nil,*version=versionC?[NSString stringWithUTF8String:versionC]:nil,*destination=destinationC?[NSString stringWithUTF8String:destinationC]:nil,*why=nil; + BOOL ok=dm_bcat_supported(titleC)&&[version isEqual:@"5.5.2"]&&safeDirectory(destination,YES); + if(ok){NSString *old=current(destination,title,version);ok=publish(destination,title,version,catalogC?boundedRead([NSString stringWithUTF8String:catalogC],1048576):nil,old,&why);} + if(!ok&&error&&errorSize)snprintf(error,errorSize,"%s",(why?:@"Unsupported calendar recipe or unsafe destination").UTF8String);return ok; +}} +@interface DmBcatRefresh : NSObject +@property(nonatomic) unsigned status; +@property(nonatomic) unsigned result; +@property(nonatomic) uint64_t bytes; +@end +@implementation DmBcatRefresh +@end +static char overlayPath[1024],deliveryPath[1024];static pthread_once_t startOnce=PTHREAD_ONCE_INIT; +static pthread_mutex_t refreshLock=PTHREAD_MUTEX_INITIALIZER; +static pthread_mutex_t startupLock=PTHREAD_MUTEX_INITIALIZER;static BOOL startupAccepted; +static NSString *startModules,*startTitle,*activeVersion,*activeCache,*activeRoot,*latestRoot; +static BOOL startOnline,refreshRunning;static DmBcatRefresh *activeRefresh;static NSTimeInterval lastRefresh; +static NSString *refreshSnapshot(NSString **error){ + if(!safeDirectory(activeCache,YES)){fail(error,@"Unsafe calendar cache directory");return nil;} + NSInteger status=0;NSData *envelope=download(catalogURL,1048576,nil,&status,NULL); + if(!envelope||status!=200){fail(error,@"Calendar eligibility check unavailable");return nil;} + NSString *previous=current(activeCache,startTitle,activeVersion)?:activeRoot; + if(!publish(activeCache,startTitle,activeVersion,envelope,previous,error))return nil; + return current(activeCache,startTitle,activeVersion); +} +static uint64_t snapshotBytes(NSString *root){ + NSDictionary *m=root?snapshot(root,startTitle,activeVersion):nil;uint64_t bytes=0; + for(NSString *path in m[@"files"]){struct stat st;if(!stat([[[root stringByAppendingPathComponent:@"files"] stringByAppendingPathComponent:path] fileSystemRepresentation],&st))bytes+=(uint64_t)st.st_size;} + return bytes; +} +static void refresh(void) { + pthread_mutex_lock(&refreshLock); + if(!startOnline||!activeVersion||refreshRunning||NSDate.date.timeIntervalSince1970-lastRefresh<300){pthread_mutex_unlock(&refreshLock);return;} + DmBcatRefresh *job=[DmBcatRefresh new];job.status=2;job.result=1;activeRefresh=job; + refreshRunning=YES;lastRefresh=NSDate.date.timeIntervalSince1970; + pthread_mutex_unlock(&refreshLock); + dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY,0),^{@autoreleasepool{ + NSString *why=nil,*selected=refreshSnapshot(&why);uint64_t bytes=snapshotBytes(selected); + BOOL delivered=selected!=nil; + pthread_mutex_lock(&refreshLock);if(delivered)latestRoot=selected;refreshRunning=NO;job.status=9;job.result=delivered?0:1;job.bytes=delivered?bytes:0;pthread_mutex_unlock(&refreshLock); + fprintf(stderr,"BCAT: %s\n",delivered?"calendar refresh validated; delivery opens use the new snapshot, RomFS overlay remains fixed for this session":"refresh unavailable or invalid; previous validated calendar retained"); + }}); +} +// Runs on the pre-guest boot thread, never on a UI thread or during rendering. +// Every new process checks again, even when +// a previous launch has just populated the cache. Only the completed, validated +// selection becomes the immutable RomFS overlay seen by the game's first open. +static void selectAtLaunch(NSString *seed){ + activeRoot=current(activeCache,startTitle,activeVersion)?:current(seed,startTitle,activeVersion);latestRoot=activeRoot; + if(startOnline){ + launchDeadline=monotonicTime()+12*NSEC_PER_SEC; + fprintf(stderr,"BCAT: checking calendar for this launch before game startup\n"); + NSDictionary *before=activeRoot?snapshot(activeRoot,startTitle,activeVersion):nil; + NSString *why=nil,*selected=refreshSnapshot(&why);BOOL timedOut=monotonicTime()>=launchDeadline; + launchDeadline=0; + DmBcatRefresh *job=[DmBcatRefresh new];job.status=9;job.result=selected?0:1;job.bytes=snapshotBytes(selected); + pthread_mutex_lock(&refreshLock);activeRefresh=job;lastRefresh=NSDate.date.timeIntervalSince1970;pthread_mutex_unlock(&refreshLock); + if(selected){ + NSDictionary *after=snapshot(selected,startTitle,activeVersion);BOOL same=[before[@"archiveSHA256"] isEqual:after[@"archiveSHA256"]]; + activeRoot=selected;latestRoot=selected; + fprintf(stderr,"BCAT: calendar check validated (%s); selected before game startup\n",same?"unchanged":"updated"); + }else fprintf(stderr,"BCAT: calendar check %s; %s (freshness not confirmed)\n",timedOut?"timed out":"unavailable or invalid",activeRoot?"last validated snapshot retained":"no validated calendar available"); + }else fprintf(stderr,"BCAT: offline mode; %s (freshness not checked)\n",activeRoot?"validated local calendar selected":"no validated calendar available"); + if(activeRoot){strlcpy(overlayPath,[activeRoot stringByAppendingPathComponent:@"files"].fileSystemRepresentation,sizeof overlayPath);strlcpy(deliveryPath,[[activeRoot stringByAppendingPathComponent:@"files"] stringByAppendingPathComponent:@"DebugUnderPilot/bcat"].fileSystemRepresentation,sizeof deliveryPath);} +} +static void start(void){@autoreleasepool{ + // Valid local data remains useful without online services. Only refresh and + // synchronization requests depend on the network preference. + if(!dm_bcat_supported(startTitle.UTF8String))return; +#ifndef DM_OPENSSL_X509 + return; // no signature verifier => unavailable, without any HTTP request +#endif + const char *override=getenv("DM_NEXTENDO_BCAT_DIR"); + NSString *seed=override?[NSString stringWithUTF8String:override]:[startModules stringByAppendingPathComponent:@"bcat"]; + if(!safeDirectory(seed,NO))return; // absent/unsafe recipe => no network request + NSDictionary *setup=json(boundedRead([seed stringByAppendingPathComponent:@"setup.json"],4096));NSString *version=setup[@"version"]; + if(!integer(setup[@"formatVersion"])||[setup[@"formatVersion"] integerValue]!=1||![setup[@"titleID"] isEqual:startTitle]||![version isKindOfClass:NSString.class]||![version isEqual:@"5.5.2"])return; + NSString *bundleVersion=[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; + if(bundleVersion&&![bundleVersion isEqual:version])return; + // iOS returns container paths through /var, a system symlink. Canonicalize + // only the OS-provided home root, then reject symlinks in our own cache tree. + // This is ordinary private-container access, not an alternate permission path. + char *home=realpath(NSHomeDirectory().fileSystemRepresentation,NULL);if(!home)return; + NSString *support=[[NSString stringWithUTF8String:home] stringByAppendingPathComponent:@"Library/Application Support"];free(home); + activeVersion=version;activeCache=[[[support stringByAppendingPathComponent:@"nxnative/BCAT"] stringByAppendingPathComponent:startTitle] stringByAppendingPathComponent:version]; + selectAtLaunch(seed); +}} +void dm_bcat_start(const char *modules,const char *title,int online){ + // Oodle's helper modes can enter guest_main only to expose a decoder; they + // are not game launches and must not initiate calendar/network preparation. + const char *job=getenv("DM_OODLE_JOB");if(getenv("DM_OODLE_SERVE")||(job&&*job))return; + pthread_mutex_lock(&startupLock); + if(startupAccepted){pthread_mutex_unlock(&startupLock);return;} + startupAccepted=YES; + char *resolved=modules?realpath(modules,NULL):NULL;startModules=resolved?[NSString stringWithUTF8String:resolved]:nil;free(resolved); + startTitle=title?[[NSString stringWithUTF8String:title] lowercaseString]:nil;startOnline=online; + pthread_once(&startOnce,start);pthread_mutex_unlock(&startupLock); +} +// This backend can be reviewed/used independently of the online-service series. +// An absent provider is offline; merely linking BCAT never enables networking. +__attribute__((weak)) int dm_bcat_online_enabled(void){return 0;} +void dm_bcat_pre_guest_start(const char *modules,const char *title){ + dm_bcat_start(modules,title,dm_bcat_online_enabled()); +} +const char *dm_bcat_overlay(void){return overlayPath[0]?overlayPath:NULL;} +const char *dm_bcat_delivery(void){return deliveryPath[0]?deliveryPath:NULL;} +int dm_bcat_copy_delivery(char *out,size_t size){@autoreleasepool{ + pthread_mutex_lock(&refreshLock);NSString *root=latestRoot;pthread_mutex_unlock(&refreshLock); + if(!root||!out||!size)return 0;NSString *path=[[root stringByAppendingPathComponent:@"files"] stringByAppendingPathComponent:@"DebugUnderPilot/bcat"]; + return strlcpy(out,path.fileSystemRepresentation,size) +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void dm_guest_host_wait_begin(void); +void dm_guest_host_wait_end(void); +static pthread_mutex_t history_lock = PTHREAD_MUTEX_INITIALIZER; +static dm_friends_history_key_provider key_provider; +static void history_clear(void *memory, size_t size) { + volatile uint8_t *bytes = memory; while (size--) *bytes++ = 0; +} +#ifdef DM_FRIENDS_HISTORY_TEST +static dm_friends_history_random_provider random_provider; +void dm_friends_history_set_random_provider(dm_friends_history_random_provider provider) { + pthread_mutex_lock(&history_lock); random_provider = provider; pthread_mutex_unlock(&history_lock); +} +#endif +static void history_random(void *out, unsigned size) { +#ifdef DM_FRIENDS_HISTORY_TEST + if (random_provider) { random_provider(out, size); return; } +#endif + arc4random_buf(out, size); +} +void dm_friends_history_set_key_provider(dm_friends_history_key_provider provider) { + pthread_mutex_lock(&history_lock); key_provider = provider; pthread_mutex_unlock(&history_lock); +} +static int exact_read(int fd, void *out, size_t size) { + size_t done = 0; + while (done < size) { + ssize_t n = read(fd, (char *)out + done, size - done); + if (n < 0 && errno == EINTR) continue; + if (n <= 0) return 0; + done += (size_t)n; + } + char extra; ssize_t n; + do { n = read(fd, &extra, 1); } while (n < 0 && errno == EINTR); + return n == 0; +} +static int exact_write(int fd, const void *bytes, size_t size) { + size_t done = 0; + while (done < size) { + ssize_t n = write(fd, (const char *)bytes + done, size - done); + if (n < 0 && errno == EINTR) continue; + if (n <= 0) return 0; + done += (size_t)n; + } + return fsync(fd) == 0; +} +static bool firmware_keys(uint8_t keys[8][32]) { + const char *root = getenv("DM_SYSTEM_DATA_DIR"); + if (!root || !*root) return false; + int base = open(root, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (base < 0) return false; + int archive = openat(base, "010000000000000e", O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + close(base); if (archive < 0) return false; + int files = openat(archive, "files", O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + close(archive); if (files < 0) return false; + int fd = openat(files, "play-history.keyring", O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK); + close(files); if (fd < 0) return false; + struct stat st; int ok = !fstat(fd, &st) && S_ISREG(st.st_mode) && + st.st_size == DM_FRIENDS_HISTORY_KEYRING_SIZE && exact_read(fd, keys, DM_FRIENDS_HISTORY_KEYRING_SIZE); + close(fd); return ok; +} +static int uuid_valid(const uint8_t uuid[16]) { + return (uuid[6] & 0xf0) == 0x40 && (uuid[8] & 0xc0) == 0x80; +} +static int read_uuid(int directory, const char *name, uint8_t uuid[16]) { + int fd = openat(directory, name, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK); + if (fd < 0) return errno == ENOENT ? 0 : -1; + struct stat st; int ok = !fstat(fd, &st) && S_ISREG(st.st_mode) && st.st_uid == geteuid() && + !(st.st_mode & 077) && st.st_nlink == 1 && st.st_size == 16 && exact_read(fd, uuid, 16) && uuid_valid(uuid); + close(fd); return ok ? 1 : -1; +} +static void hex_bytes(char *out, const uint8_t *bytes, unsigned count) { + static const char hex[] = "0123456789abcdef"; + for (unsigned i = 0; i < count; ++i) { out[2*i] = hex[bytes[i] >> 4]; out[2*i+1] = hex[bytes[i] & 15]; } + out[2*count] = 0; +} +static int local_uuid(const uint8_t uid[16], uint8_t uuid[16]) { + const char *root = getenv("DM_ROOT"); if (!root || !*root) root = "."; + int base = open(root, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (base < 0) return 0; + int made = mkdirat(base, "friends-history", 0700); + if (made && errno != EEXIST) { close(base); return 0; } + int directory = openat(base, "friends-history", O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + close(base); if (directory < 0) return 0; + struct stat st; + if (fstat(directory, &st) || st.st_uid != geteuid() || (st.st_mode & 077)) { close(directory); return 0; } + char name[42]; hex_bytes(name, uid, 16); memcpy(name+32, ".uuid.bin", 10); + int exists = read_uuid(directory, name, uuid); + if (exists) { close(directory); return exists > 0; } + uint8_t random[16]; history_random(uuid, 16); uuid[6] = (uuid[6] & 15) | 0x40; uuid[8] = (uuid[8] & 63) | 0x80; + history_random(random, sizeof random); char temporary[38] = ".tmp-"; hex_bytes(temporary+5, random, 16); + int fd = openat(directory, temporary, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600); + if (fd < 0) { close(directory); return 0; } + int ok = exact_write(fd, uuid, 16), committed = 0; close(fd); + if (ok) { + if (!renameatx_np(directory, temporary, directory, name, RENAME_EXCL)) committed = 1; + else if (errno != EEXIST) ok = 0; + } + if (!committed && unlinkat(directory, temporary, 0)) ok = 0; + if (ok && fsync(directory)) ok = 0; + // Another process may have committed first. Always use the committed file. + if (ok) ok = read_uuid(directory, name, uuid) == 1; + close(directory); return ok; +} +uint32_t dm_friends_history_key(void *out, const void *uid_pointer, unsigned input_flag) { + if (!out) return DM_FRIENDS_HISTORY_FAIL; + uint8_t uid[16] = {0}; if (uid_pointer) memcpy(uid, uid_pointer, sizeof uid); + memset(out, 0, DM_FRIENDS_HISTORY_KEY_SIZE); + uint8_t present = 0; for (unsigned i = 0; i < sizeof uid; ++i) present |= uid[i]; + if (!present) return DM_FRIENDS_HISTORY_INVALID_UID; + uint8_t keys[8][32] = {{0}}, result[64] = {1, 1}, uuid[16]; uint32_t status = DM_FRIENDS_HISTORY_FAIL; + dm_guest_host_wait_begin(); pthread_mutex_lock(&history_lock); + if ((key_provider ? key_provider(keys) : firmware_keys(keys)) && local_uuid(uid, uuid)) { + uint8_t index; history_random(&index, 1); result[2] = index & 7; result[4] = input_flag & 1; + memcpy(result+16, uuid, sizeof uuid); + CCHmac(kCCHmacAlgSHA256, keys[result[2]], 32, result, 32, result+32); + memcpy(out, result, sizeof result); status = DM_FRIENDS_HISTORY_OK; + } + history_clear(keys, sizeof keys); history_clear(result, sizeof result); + pthread_mutex_unlock(&history_lock); dm_guest_host_wait_end(); + return status; +} diff --git a/dm/host/hle_fs.c b/dm/host/hle_fs.c index 025b37dc5f..1fb668939e 100644 --- a/dm/host/hle_fs.c +++ b/dm/host/hle_fs.c @@ -20,6 +20,19 @@ #include "romfs_image.h" #include "save_sync.h" +// The data importer is absent in source-only FS fixtures; production links it. +extern const char *dm_bcat_overlay(void) __attribute__((weak_import)); +extern const char *dm_bcat_delivery(void) __attribute__((weak_import)); +extern int dm_bcat_copy_delivery(char *, size_t) __attribute__((weak_import)); +static _Atomic int bcat_mounted; +static int mount_visible(const char *name) { return strcmp(name, "bcat") || atomic_load(&bcat_mounted); } +static void rom_overlays(char *out, size_t size) { + const char *custom = getenv("DM_ROMFS_OVERLAY"), *calendar = dm_bcat_overlay ? dm_bcat_overlay() : NULL; + out[0] = 0; + if (custom && *custom) strlcpy(out, custom, size); + if (calendar && *calendar) { if (out[0]) strlcat(out, ":", size); strlcat(out, calendar, size); } +} + #define RES_PATH_NOT_FOUND 0x202u // fs module 2, description 1 #define RES_PATH_EXISTS 0x402u // fs module 2, description 2 #define RES_RENAME_OTHER_FS 0x2F2402u // fs module 2, description 6034: ResultRenameToOtherFileSystem @@ -168,7 +181,7 @@ static int img_path(const char *p, int *mi, int64_t *k) { PATH_LOCK(); char fwd[1024]; p = fwd_slashes(p, fwd, sizeof fwd); const char *c = p ? strchr(p, ':') : NULL; if (!c) return 0; size_t ln = c - p; for (int i = 0; i < g_nmnt; i++) { - if (!mnt_is(&g_mnt[i], p, ln)) continue; + if (!mount_visible(g_mnt[i].name) || !mnt_is(&g_mnt[i], p, ln)) continue; if (!g_mnt[i].img) return 0; char normed[1024]; const char *rest = c + 1; *mi = i; if (strstr(rest, "/.")) { if (!norm_rest(rest, normed, sizeof normed)) { *k = -1; return 1; } rest = normed; } @@ -208,8 +221,8 @@ static Result mount_impl(const char *name, const char *dir, int ro, int txn, int g_mnt[g_nmnt].txn_root = -1; atomic_store(&g_mnt[g_nmnt].poison, 0); atomic_store(&g_mnt[g_nmnt].first_write_ns, 0); - const char *overlay = !strcmp(name, "rom") ? getenv("DM_ROMFS_OVERLAY") : NULL; - if (overlay) strlcpy(g_mnt[g_nmnt].overlay, overlay, sizeof g_mnt[0].overlay); + if (!strcmp(name, "rom")) + rom_overlays(g_mnt[g_nmnt].overlay, sizeof g_mnt[0].overlay); // The transaction directory cannot be set up (leftovers cannot be cleared / clone failed, which really happens on a full disk): do not exit; mount the committed directory read-only -- saves still read, every write fails, commits are no-ops, the committed version is untouched, and the front end is told // (each of these three failures used to call die: with the phone's storage full the game exited as soon as it mounted its saves) int txn_err = 0, k = 0; @@ -433,7 +446,7 @@ static int host_path_ex(const char *p, char *out, size_t n, int *ro, int create) if (!c) { errno = ENOENT; return 0; } size_t ln = c - p; for (int i = 0; i < g_nmnt; i++) { - if (!mnt_is(&g_mnt[i], p, ln)) continue; + if (!mount_visible(g_mnt[i].name) || !mnt_is(&g_mnt[i], p, ln)) continue; if (ro) *ro = g_mnt[i].ro; char normed[1024]; const char *rest = c + 1; if (strstr(rest, "/.")) { if (!norm_rest(rest, normed, sizeof normed)) return 0; rest = normed; } // only paths with "." components are normalized; the rest walk component by component as before @@ -549,15 +562,38 @@ HLE_FORCE("_ZN2nn2fs22QueryMountRomCacheSizeEPm", "fsp-srv; rom reads the host d HLE_FORCE("_ZN2nn2fs8MountRomEPKcPvm", "fsp-srv; rom → host RomFS directory", Result, h_fs_MountRom, const char *name, void *cache, size_t sz) { dm_thread_service_request(); (void)cache; (void)sz; char b[1024]; Result r = mount(name, envdir("DM_ROMFS", "romfs", b, sizeof b), 1); - const char *overlay = getenv("DM_ROMFS_OVERLAY"); - if (r == RES_OK && overlay) { + if (r == RES_OK) { PATH_LOCK(); for (int i = 0; i < g_nmnt; i++) if (mnt_named(&g_mnt[i], name)) { - strlcpy(g_mnt[i].overlay, overlay, sizeof g_mnt[i].overlay); break; + rom_overlays(g_mnt[i].overlay, sizeof g_mnt[i].overlay); break; } } return r; } +// BCAT's SDK mount is read-only. Missing/unvalidated delivery data remains a +// real failure; mounting an empty successful stand-in hides synchronization bugs. +HLE_FORCE("_ZN2nn4bcat25MountDeliveryCacheStorageEv", "mount a validated immutable delivery snapshot as bcat:", Result, h_bcat_Mount, void) { dm_thread_service_request(); + char selected[1024]; + const char *root = dm_bcat_copy_delivery && dm_bcat_copy_delivery(selected, sizeof selected) ? selected : + dm_bcat_delivery ? dm_bcat_delivery() : NULL; + struct stat st; + if (!root || stat(root, &st) || !S_ISDIR(st.st_mode)) return RES_PATH_NOT_FOUND; + Result r = mount("bcat", root, 1); + if (r == RES_OK) { + PATH_LOCK(); + // A fresh mount may select the new snapshot. Existing file descriptors + // continue to reference their original immutable files after unmount. + for (int i=0;i/, extracted from the player's DLC NSPs by the packing script; mounted read-only, using the directory index like rom. // The owned index list is reported by the aoc calls in hle_misc.c from the same directory; the game only mounts indices it was given, and a missing directory answers "target not found" (fs 2-1002, as on hardware without that DLC) #define RES_TARGET_NOT_FOUND 0x7D402u // fs module 2, description 1002 @@ -650,7 +686,7 @@ HLE_FORCE("_ZN2nn2fs15MountSystemDataEPKcNS_3ncm12SystemDataIdEPvm", "fsp-srv; s } static int host_mounted(const char *name) { PATH_LOCK(); - for (int i = 0; name && i < g_nmnt; i++) if (mnt_named(&g_mnt[i], name)) return 1; + for (int i = 0; name && i < g_nmnt; i++) if (mount_visible(g_mnt[i].name) && mnt_named(&g_mnt[i], name)) return 1; return 0; } // ---------- Mounts in the SDK's own table ---------- @@ -724,7 +760,7 @@ HLE_FORCE("_ZN2nn2fs9IsMountedEPKc", "fsp-srv; looks up the host mount table, th HLE_FORCE("_ZN2nn2fs13IsPathMountedEPKc", "fsp-srv; looks up the host mount table, then the SDK's own (a RAM disk)", int, h_fs_IsPathMounted, const char *path) { // bool in w0: 1 / 0 const char *c = path ? strchr(path, ':') : NULL; { PATH_LOCK(); - for (int i = 0; c && i < g_nmnt; i++) if (mnt_is(&g_mnt[i], path, (size_t)(c - path))) return 1; + for (int i = 0; c && i < g_nmnt; i++) if (mount_visible(g_mnt[i].name) && mnt_is(&g_mnt[i], path, (size_t)(c - path))) return 1; } char name[0x30]; // the SDK is asked with no host lock held if (path_mount_name(path, name, sizeof name) && sdk_mounted(name)) return 1; diff --git a/dm/host/hle_grpc.c b/dm/host/hle_grpc.c new file mode 100644 index 0000000000..d7cb5016e6 --- /dev/null +++ b/dm/host/hle_grpc.c @@ -0,0 +1,33 @@ +// gRPC's internal errors, seen through observation gate OBS_GRPC_ERROR (dm.h) on grpc_error_create's entry, which a game profile's patches.py places in a main that +// links gRPC: Super Mario Bros. Wonder 1.2.1 (main+0xb57b40, dm/games/010015100B514000/patches.py). Nintendo's build of gRPC has its logging compiled out (no trace +// strings, nothing reads gpr_log's function), so GRPC_VERBOSITY and GRPC_TRACE print nothing; a call that fails as UNAVAILABLE before any socket (no root certificates, +// no subchannel) otherwise leaves no line at all. Each distinct source file and line logs once, with the error's text, up to 96 of them. +// grpc_error_create(const char *file, int line, const grpc_slice &desc, grpc_error **referencing, size_t count): x0 the file (a string in main), w1 the line, x2 the +// slice. A grpc_slice is {refcount, data}: with no refcount the bytes are inline (length byte +8, bytes +9, at most 23), otherwise length +8 and a pointer +0x10. +// The text is gRPC's own description (a server name or address at most, never a token or a payload); printable ASCII only, cut at 160 characters +#include "hle.h" +#include +#include + +static void grpc_error_seen(uint64_t *r, int param) { + (void)param; + const char *file = (const char *)r[0]; int line = (int)(uint32_t)r[1]; const uint8_t *slice = (const uint8_t *)r[2]; + static struct { const char *file; int line; } seen[96]; static unsigned count; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + pthread_mutex_lock(&lock); int fresh = count < 96; + for (unsigned i = 0; i < count && fresh; i++) if (seen[i].file == file && seen[i].line == line) fresh = 0; + if (fresh) { seen[count].file = file; seen[count].line = line; count++; } + pthread_mutex_unlock(&lock); + if (!fresh) return; + char text[161] = ""; size_t n = 0; + if (slice) { + uint64_t refcount; memcpy(&refcount, slice, 8); + const uint8_t *bytes; uint64_t length; + if (!refcount) { length = slice[8]; bytes = slice + 9; if (length > 23) length = 23; } + else { memcpy(&length, slice + 8, 8); memcpy(&bytes, slice + 16, 8); } + for (uint64_t i = 0; bytes && i < length && n < sizeof text - 1; i++) text[n++] = bytes[i] >= 32 && bytes[i] < 127 ? (char)bytes[i] : '?'; + text[n] = 0; + } + const char *short_file = file ? file : "?", *core = file ? strstr(file, "src/core/") : NULL; if (core) short_file = core + 9; + LOG("grpc: error at %s:%d: %s", short_file, line, text); +} +__attribute__((constructor)) static void grpc_attach(void) { gate_obs_set(OBS_GRPC_ERROR, grpc_error_seen); } diff --git a/dm/host/hle_ldn.c b/dm/host/hle_ldn.c new file mode 100644 index 0000000000..2a310b3096 --- /dev/null +++ b/dm/host/hle_ldn.c @@ -0,0 +1,470 @@ +// Native LDN discovery/session bridge. The service owns control-plane sockets; +// game packets use nn::socket and the actual adapter IPv4 addresses in NodeInfo. +// ldn_mitm authenticates neither its control TCP connection nor the passphrase: +// this is a local-network transport, not a replacement for Nintendo security. +#include "hle_ldn.h" +#include "net_socket.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef DM_LDN_TEST +#include "hle.h" +#endif + +enum { LDN_NONE, LDN_INITIALIZED, LDN_AP, LDN_CREATED, LDN_STATION, LDN_CONNECTED }; +#define LDN_ERROR(n) (((uint32_t)(n) << 9) | 203u) +enum { LDN_INVALID_STATE = LDN_ERROR(32), LDN_NODE_NOT_FOUND = LDN_ERROR(48), LDN_CONNECT_FAILED = LDN_ERROR(64), + LDN_NOT_FOUND = LDN_ERROR(65), LDN_TIMEOUT = LDN_ERROR(66), LDN_REJECTED = LDN_ERROR(67), LDN_INVALID = LDN_ERROR(96), + LDN_VERSION_LOW = LDN_ERROR(113), LDN_VERSION_HIGH = LDN_ERROR(114), LDN_FULL = LDN_ERROR(144) }; +enum { LDN_ROOM_MAX = 24, LDN_TX_MAX = 8192 }; +typedef struct { + int fd, node, active; uint64_t generation, deadline; + uint8_t rx[DM_LDN_PACKET_MAX], tx[LDN_TX_MAX]; size_t received, queued, sent; +} ldn_peer; +typedef struct { dm_ldn_network network; struct sockaddr_in endpoint; } ldn_room; +struct dm_ldn_context { + pthread_mutex_t lock; pthread_cond_t changed; pthread_t worker; + dm_ldn_transport transport; dm_ldn_notify notify; void *opaque; + int udp, listener, wake[2], stopping, state, reason, scanning; + dm_net_discovery_plan scan_plan,scan_supplement; uint64_t scan_next; int scan_tx_failed; + uint64_t generation; dm_ldn_network network; dm_ldn_network_config config; + dm_ldn_update updates[8]; ldn_peer peers[8]; ldn_room rooms[LDN_ROOM_MAX]; int room_count; + uint8_t filters[8][6]; int filter_count; dm_ldn_address private_addresses[8]; int private_count; +}; +// Opt-in, bounded control-plane diagnostics. Only operation names and numeric +// sizes/states/results are recorded: never addresses, names, IDs or payloads. +static int ldn_trace_enabled(void) { + const char *flag = getenv("DM_LDN_TRACE"), *net = getenv("DM_NET_TRACE"); + return (flag && !strcmp(flag, "1")) || (net && !strcmp(net, "1")); +} +static void ldn_trace(const char *format, ...) { + int saved = errno; + static unsigned records; + if (!ldn_trace_enabled()) { errno = saved; return; } + unsigned record = __atomic_fetch_add(&records, 1, __ATOMIC_RELAXED); + if (record < 2048) { + char message[384]; va_list args; va_start(args, format); + vsnprintf(message, sizeof message, format, args); va_end(args); + fprintf(stderr, "ldn: %s\n", message); + } + errno = saved; +} +static uint64_t ldn_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000; } +static struct timespec ldn_deadline(unsigned ms) { struct timespec t; clock_gettime(CLOCK_REALTIME, &t); t.tv_sec += ms / 1000; t.tv_nsec += (ms % 1000) * 1000000L; if (t.tv_nsec >= 1000000000L) { ++t.tv_sec; t.tv_nsec -= 1000000000L; } return t; } +static struct sockaddr_in ldn_endpoint(uint32_t address, unsigned port) { struct sockaddr_in a = {0}; a.sin_family = AF_INET; a.sin_addr.s_addr = address; a.sin_port = htons((uint16_t)port); return a; } +static void ldn_nonblock(int fd) { fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); fcntl(fd, F_SETFD, FD_CLOEXEC); +#ifdef SO_NOSIGPIPE + int yes = 1; setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof yes); +#endif +} +static void ldn_wake(dm_ldn_context *c) { uint8_t b = 1; (void)write(c->wake[1], &b, 1); } +static void ldn_changed(dm_ldn_context *c) { pthread_cond_broadcast(&c->changed); if (c->notify) c->notify(c->opaque); } +static void ldn_state_set(dm_ldn_context *c, int state) { if (c->state != state) { ldn_trace("state from=%d to=%d reason=%d", c->state, state, c->reason); c->state = state; ldn_changed(c); } } +static void ldn_network_set(dm_ldn_context *c, const dm_ldn_network *n) { + if (!memcmp(&c->network, n, sizeof *n)) return; + for (int i = 0; i < 8; ++i) { + if (c->network.nodes[i].connected && (!n->nodes[i].connected || memcmp(c->network.nodes[i].mac, n->nodes[i].mac, 6))) c->updates[i].change |= 2; + if (n->nodes[i].connected && (!c->network.nodes[i].connected || memcmp(c->network.nodes[i].mac, n->nodes[i].mac, 6))) c->updates[i].change |= 1; + } + c->network = *n; ldn_changed(c); +} +static void ldn_mac(uint8_t out[6], uint32_t address) { out[0] = 2; out[1] = 0; memcpy(out + 2, &address, 4); } +static void ldn_local_mac(dm_ldn_context *c, uint8_t out[6]) { static const uint8_t zero[6]; if (memcmp(c->transport.mac, zero, 6)) memcpy(out, c->transport.mac, 6); else ldn_mac(out, c->transport.address); } +static dm_ldn_node ldn_node(dm_ldn_context *c, const dm_ldn_user *user, int version, int id) { + dm_ldn_node n = {0}; n.ip = ntohl(c->transport.address); ldn_local_mac(c, n.mac); n.id = id; n.connected = 1; + memcpy(n.name, user->name, 33); n.version = (int16_t)version; return n; +} +static void ldn_peer_close(dm_ldn_context *c, int i) { ldn_peer *p = &c->peers[i]; if (p->fd >= 0) close(p->fd); p->fd = -1; p->active = 0; p->generation = ++c->generation; p->received = p->queued = p->sent = 0; } +static int ldn_queue(dm_ldn_context *c, int i, unsigned type, const void *data, size_t size) { + ldn_peer *p = &c->peers[i]; uint8_t packet[DM_LDN_PACKET_MAX]; int n = dm_ldn_packet_encode(packet, sizeof packet, type, data, size, 1); + if (n < 0 || p->fd < 0) return -1; + if (p->sent) { memmove(p->tx, p->tx + p->sent, p->queued - p->sent); p->queued -= p->sent; p->sent = 0; } + if ((size_t)n > sizeof p->tx - p->queued) return -1; + memcpy(p->tx + p->queued, packet, (size_t)n); p->queued += n; return 0; +} +static void ldn_sync(dm_ldn_context *c) { + // An update that cannot be delivered means the member has left. Rebuild + // the roster before queuing a new snapshot to all surviving members. + for (;;) { + dm_ldn_network n = c->network; n.node_count = 1; + for (int i = 1; i < 8; i++) { if (c->peers[i].active) ++n.node_count; else memset(&n.nodes[i], 0, sizeof n.nodes[i]); } + ldn_network_set(c, &n); int removed = 0; + for (int i = 1; i < 8; ++i) if (c->peers[i].active && ldn_queue(c, i, DM_LDN_SYNC, &c->network, sizeof c->network)) { ldn_peer_close(c, i); removed = 1; } + if (!removed) break; + } + ldn_wake(c); +} +static void ldn_drop(dm_ldn_context *c, int i) { + int active = c->peers[i].active; ldn_peer_close(c, i); + if (c->state == LDN_CREATED && active) ldn_sync(c); + else if ((c->state == LDN_CONNECTED || c->state == LDN_STATION) && i == 0) { + c->reason = 6; dm_ldn_network empty = {0}; ldn_network_set(c, &empty); ldn_state_set(c, LDN_STATION); ldn_changed(c); + } +} +static int ldn_mac_in_list(const uint8_t mac[6], uint8_t list[8][6], int count) { for (int i = 0; i < count; ++i) if (!memcmp(mac, list[i], 6)) return 1; return 0; } +static int ldn_accept_node(dm_ldn_context *c, int slot, dm_ldn_node *n) { + static const uint8_t zero_mac[6]; + if (!n->ip || !memcmp(n->mac, zero_mac, 6) || (n->mac[0] & 1) || !memchr(n->name, 0, 33) || n->version != c->network.nodes[0].version || n->platform > 1) return 0; + unsigned policy = c->network.accept_policy; int listed = ldn_mac_in_list(n->mac, c->filters, c->filter_count); + if (policy == 1 || (policy == 2 && listed) || (policy == 3 && !listed)) return 0; + if (c->private_count) { int allowed = 0; for (int i = 0; i < c->private_count; ++i) if (c->private_addresses[i].ip == n->ip && !memcmp(c->private_addresses[i].mac, n->mac, 6)) allowed = 1; if (!allowed) return 0; } + for (int i = 0; i < 8; ++i) if (c->network.nodes[i].connected && (c->network.nodes[i].ip == n->ip || !memcmp(c->network.nodes[i].mac, n->mac, 6))) { + // Production peers have different adapter addresses. Loopback fixtures + // deliberately share an address and still use distinct locally assigned MACs. + if (!memcmp(c->network.nodes[i].mac, n->mac, 6)) return 0; + } + n->id = slot; n->connected = 1; dm_ldn_network next = c->network; next.nodes[slot] = *n; ++next.node_count; c->peers[slot].active = 1; ldn_network_set(c, &next); ldn_sync(c); return 1; +} +static int ldn_frame(dm_ldn_context *c, int i, const uint8_t *data, size_t size) { + dm_ldn_network payload; unsigned type; int n = dm_ldn_packet_decode(data, size, &type, &payload, sizeof payload); + if (n < 0) { ldn_trace("tcp-frame invalid size=%zu", size); return -1; } + ldn_trace("tcp-frame type=%u expanded=%d state=%d slot=%d", type, n, c->state, i); + if (c->state == LDN_CREATED && i > 0 && type == DM_LDN_CONNECT && !c->peers[i].active) { + dm_ldn_node node; memcpy(&node, &payload, sizeof node); + struct sockaddr_in endpoint; socklen_t len = sizeof endpoint; + if (getpeername(c->peers[i].fd, (struct sockaddr *)&endpoint, &len) || node.ip != ntohl(endpoint.sin_addr.s_addr)) return -1; + return ldn_accept_node(c, i, &node) ? 0 : -1; + } + if ((c->state == LDN_STATION || c->state == LDN_CONNECTED) && i == 0 && type == DM_LDN_SYNC && dm_ldn_network_valid(&payload) && + !memcmp(&payload.id, &c->network.id, sizeof payload.id) && payload.nodes[0].ip == c->network.nodes[0].ip) { + uint8_t mac[6]; ldn_local_mac(c, mac); int found = 0; + for (int j = 1; j < 8; ++j) if (payload.nodes[j].connected && !memcmp(payload.nodes[j].mac, mac, 6) && payload.nodes[j].ip == ntohl(c->transport.address)) found = 1; + if (!found) return -1; + ldn_network_set(c, &payload); c->peers[0].active = 1; ldn_state_set(c, LDN_CONNECTED); return 0; + } + return -1; +} +static int ldn_read_peer(dm_ldn_context *c, int i) { + ldn_peer *p = &c->peers[i]; uint8_t data[2048]; ssize_t n = recv(p->fd, data, sizeof data, 0); + if (n <= 0) { if (!n || (errno != EAGAIN && errno != EINTR)) ldn_trace("tcp-read slot=%d result=%ld errno=%d active=%d", i, (long)n, n < 0 ? errno : 0, p->active); return n < 0 && (errno == EAGAIN || errno == EINTR) ? 0 : -1; } + for (size_t at = 0; at < (size_t)n;) { + size_t wanted = 12; if (p->received >= 12) { int total = dm_ldn_packet_size(p->rx); if (total < 0) return -1; wanted = (size_t)total; } + size_t copy = wanted - p->received; if (copy > (size_t)n - at) copy = (size_t)n - at; + memcpy(p->rx + p->received, data + at, copy); p->received += copy; at += copy; + if (p->received >= 12) { int total = dm_ldn_packet_size(p->rx); if (total < 0) return -1; if (p->received == (size_t)total) { if (ldn_frame(c, i, p->rx, p->received)) return -1; p->received = 0; } } + } + return 0; +} +static void ldn_read_udp(dm_ldn_context *c) { + uint8_t data[DM_LDN_PACKET_MAX + 1], payload[sizeof(dm_ldn_network)]; struct sockaddr_in from; socklen_t len = sizeof from; + ssize_t size = recvfrom(c->udp, data, sizeof data, 0, (struct sockaddr *)&from, &len); unsigned type; + if (size < 12 || size > DM_LDN_PACKET_MAX || from.sin_family != AF_INET) return; + int n = dm_ldn_packet_decode(data, (size_t)size, &type, payload, sizeof payload); if (n < 0) return; + if (type == DM_LDN_SCAN && c->state == LDN_CREATED && !(from.sin_addr.s_addr == c->transport.address && ntohs(from.sin_port) == c->transport.port)) { + int count = dm_ldn_packet_encode(data, sizeof data, DM_LDN_SCAN_RESPONSE, &c->network, sizeof c->network, 1); + if (count > 0) (void)sendto(c->udp, data, count, 0, (struct sockaddr *)&from, len); + } else if (type == DM_LDN_SCAN_RESPONSE && c->scanning) { + dm_ldn_network room; memcpy(&room, payload, sizeof room); + if (!dm_ldn_network_valid(&room) || room.nodes[0].ip != ntohl(from.sin_addr.s_addr)) return; + for (int i = 0; i < c->room_count; ++i) if (!memcmp(&room.id, &c->rooms[i].network.id, sizeof room.id)) { c->rooms[i].network = room; c->rooms[i].endpoint = from; return; } + if (c->room_count < LDN_ROOM_MAX) c->rooms[c->room_count++] = (ldn_room){room, from}; + } +} +static void *ldn_worker(void *opaque) { + dm_ldn_context *c = opaque; + for (;;) { + struct pollfd fds[11]; uint64_t generations[8]; + pthread_mutex_lock(&c->lock); if (c->stopping) { pthread_mutex_unlock(&c->lock); break; } + fds[0] = (struct pollfd){c->wake[0], POLLIN, 0}; fds[1] = (struct pollfd){c->udp, POLLIN, 0}; fds[2] = (struct pollfd){c->listener, POLLIN, 0}; + for (int i = 0; i < 8; ++i) { ldn_peer *p = &c->peers[i]; fds[3+i] = (struct pollfd){p->fd, POLLIN | (p->queued > p->sent ? POLLOUT : 0), 0}; generations[i] = p->generation; } + int timeout = 100; + if (c->scanning && (c->scan_plan.count||c->scan_supplement.count)) { + uint64_t now = ldn_ms(); timeout = c->scan_next > now ? (int)(c->scan_next - now) : 0; + if (timeout > 100) timeout = 100; + } + pthread_mutex_unlock(&c->lock); int ready = poll(fds, 11, timeout); + if (ready < 0 && errno != EINTR) break; + pthread_mutex_lock(&c->lock); + if (fds[0].revents & POLLIN) { uint8_t drain[64]; while (read(c->wake[0], drain, sizeof drain) > 0) {} } + if (c->scanning && (c->scan_plan.count||c->scan_supplement.count) && ldn_ms() >= c->scan_next) { + uint8_t packet[12]; dm_ldn_packet_encode(packet, sizeof packet, DM_LDN_SCAN, NULL, 0, 0); + for (unsigned i = 0; i < DM_DISCOVERY_BATCH; ++i) { + dm_net_discovery_plan *plan=c->scan_plan.count?&c->scan_plan:&c->scan_supplement; + if(!plan->count)break; + dm_net_discovery_plan saved = *plan; uint32_t address; + if (!dm_net_discovery_next(plan, &address)) { plan->count=0;continue; } + ssize_t result=dm_net_discovery_send_native(c->udp,packet,sizeof packet,0,address,htons(c->transport.discovery_port)); + if (result < 0 && (errno == EAGAIN || errno == ENOBUFS || errno == EINTR)) { *plan=saved;break; } + if (result < 0 && (!plan->automatic||!dm_net_discovery_unreachable(errno))) { + // A supplemental failure must not replace an accepted + // original broadcast's result; native errors stay visible. + if(plan==&c->scan_supplement) { plan->count=0;break; } + c->scan_tx_failed=1;c->scan_plan.count=c->scan_supplement.count=0;pthread_cond_broadcast(&c->changed);break; + } + } + c->scan_next = ldn_ms() + DM_DISCOVERY_TICK_MS; + } + if (fds[1].revents & POLLIN) ldn_read_udp(c); + if (fds[2].revents & POLLIN && c->listener == fds[2].fd) { + int fd = accept(c->listener, NULL, NULL); + if (fd >= 0) { int slot = -1; for (int i = 1; i < c->network.max_nodes; ++i) if (c->peers[i].fd < 0) { slot = i; break; } + ldn_trace("tcp-accept slot=%d state=%d policy=%u", slot, c->state, c->network.accept_policy); + if (slot < 0 || c->state != LDN_CREATED || c->network.accept_policy == 1) close(fd); + else { ldn_nonblock(fd); c->peers[slot].fd = fd; c->peers[slot].node = slot; c->peers[slot].generation = ++c->generation; c->peers[slot].deadline = ldn_ms() + c->transport.connect_ms; } + } + } + for (int i = 0; i < 8; ++i) { + ldn_peer *p = &c->peers[i]; if (p->fd < 0 || p->generation != generations[i] || p->fd != fds[i+3].fd) continue; + int drop = fds[i+3].revents & (POLLERR | POLLHUP | POLLNVAL); + if (!drop && fds[i+3].revents & POLLIN) drop = ldn_read_peer(c, i) != 0; + if (!drop && fds[i+3].revents & POLLOUT && p->queued > p->sent) { + ssize_t sent = send(p->fd, p->tx + p->sent, p->queued - p->sent, 0); + if (sent > 0) { p->sent += sent; if (p->sent == p->queued) p->sent = p->queued = 0; } + else if (sent == 0 || (errno != EAGAIN && errno != EINTR)) drop = 1; + } + if (!p->active && ldn_ms() >= p->deadline) { ldn_trace("tcp-handshake-timeout slot=%d state=%d", i, c->state); drop = 1; } + if (drop) ldn_drop(c, i); + } + pthread_mutex_unlock(&c->lock); + } + return NULL; +} +dm_ldn_context *dm_ldn_start(const dm_ldn_transport *t, dm_ldn_notify notify, void *opaque) { + if (!t || !t->address || !t->mask || !t->port || !t->discovery_port || !t->scan_ms || !t->connect_ms) return NULL; + ldn_trace("start port=%u discovery-port=%u scan-ms=%u connect-ms=%u multicast=%d", t->port, t->discovery_port, t->scan_ms, t->connect_ms, dm_net_multicast_allowed()); + dm_ldn_context *c = calloc(1, sizeof *c); if (!c) return NULL; + c->transport = *t; c->notify = notify; c->opaque = opaque; c->udp = c->listener = c->wake[0] = c->wake[1] = -1; + for (int i = 0; i < 8; ++i) c->peers[i].fd = -1; + pthread_mutex_init(&c->lock, NULL); pthread_cond_init(&c->changed, NULL); + c->udp = socket(AF_INET, SOCK_DGRAM, 0); if (c->udp < 0 || pipe(c->wake)) goto fail; + ldn_nonblock(c->udp); ldn_nonblock(c->wake[0]); ldn_nonblock(c->wake[1]); int yes = 1; + if (dm_net_multicast_allowed()) setsockopt(c->udp, SOL_SOCKET, SO_BROADCAST, &yes, sizeof yes); + struct sockaddr_in a = ldn_endpoint(t->bind_address, t->port); + if (bind(c->udp, (struct sockaddr *)&a, sizeof a)) goto fail; + c->state = LDN_INITIALIZED; + if (pthread_create(&c->worker, NULL, ldn_worker, c)) goto fail; + return c; +fail: + ldn_trace("start failed errno=%d", errno); + if (c->udp >= 0) close(c->udp); if (c->wake[0] >= 0) close(c->wake[0]); if (c->wake[1] >= 0) close(c->wake[1]); + pthread_cond_destroy(&c->changed); pthread_mutex_destroy(&c->lock); free(c); return NULL; +} +void dm_ldn_stop(dm_ldn_context *c) { + if (!c) return; pthread_mutex_lock(&c->lock); c->stopping = 1; ldn_wake(c); pthread_cond_broadcast(&c->changed); pthread_mutex_unlock(&c->lock); + pthread_join(c->worker, NULL); for (int i = 0; i < 8; ++i) ldn_peer_close(c, i); + if (c->listener >= 0) close(c->listener); close(c->udp); close(c->wake[0]); close(c->wake[1]); pthread_cond_destroy(&c->changed); pthread_mutex_destroy(&c->lock); free(c); +} +int dm_ldn_state(dm_ldn_context *c) { if (!c) return 0; pthread_mutex_lock(&c->lock); int n = c->state; pthread_mutex_unlock(&c->lock); return n; } +int dm_ldn_reason(dm_ldn_context *c) { if (!c) return 0; pthread_mutex_lock(&c->lock); int n = c->reason; pthread_mutex_unlock(&c->lock); return n; } +uint32_t dm_ldn_open(dm_ldn_context *c, int ap) { + if (!c) return LDN_INVALID_STATE; pthread_mutex_lock(&c->lock); uint32_t r = LDN_INVALID_STATE; + if (c->state == LDN_INITIALIZED) { ldn_state_set(c, ap ? LDN_AP : LDN_STATION); r = 0; } + pthread_mutex_unlock(&c->lock); return r; +} +static uint32_t ldn_disconnect_locked(dm_ldn_context *c, int host, int reason) { + if (c->state != (host ? LDN_CREATED : LDN_CONNECTED)) return LDN_INVALID_STATE; + if (c->listener >= 0) { close(c->listener); c->listener = -1; } + for (int i = 0; i < 8; ++i) ldn_peer_close(c, i); + dm_ldn_network empty = {0}; c->reason = reason; ldn_network_set(c, &empty); ldn_state_set(c, host ? LDN_AP : LDN_STATION); ldn_wake(c); return 0; +} +uint32_t dm_ldn_disconnect(dm_ldn_context *c, int host) { if (!c) return LDN_INVALID_STATE; pthread_mutex_lock(&c->lock); uint32_t r = ldn_disconnect_locked(c, host, host ? 3 : 1); pthread_mutex_unlock(&c->lock); return r; } +uint32_t dm_ldn_close(dm_ldn_context *c, int ap) { + if (!c) return LDN_INVALID_STATE; pthread_mutex_lock(&c->lock); uint32_t r = LDN_INVALID_STATE; + if (c->state == (ap ? LDN_CREATED : LDN_CONNECTED)) ldn_disconnect_locked(c, ap, ap ? 3 : 1); + if (c->state == (ap ? LDN_AP : LDN_STATION)) { ldn_state_set(c, LDN_INITIALIZED); r = 0; } + pthread_mutex_unlock(&c->lock); return r; +} +uint32_t dm_ldn_scan(dm_ldn_context *c, dm_ldn_network *out, int *count, int max, const dm_ldn_filter *f, int channel) { + if (count) *count = 0; + if (!c || !out || !count || !f || max < 1 || f->flags & ~63u || ((f->flags & 16) && f->ssid.len > 32) || ((f->flags & 4) && f->type > 3) || channel < 0 || channel > 255) return LDN_INVALID; + if (max > 24) max = 24; pthread_mutex_lock(&c->lock); + if ((c->state != LDN_STATION && c->state != LDN_CONNECTED && c->state != LDN_CREATED) || c->scanning) { pthread_mutex_unlock(&c->lock); return LDN_INVALID_STATE; } + dm_net_discovery_plan plan = {.target = c->transport.discovery, .count = 1}; + uint32_t host = ntohl(c->transport.discovery); + if ((host == UINT32_MAX || (host & 0xf0000000u) == 0xe0000000u || + c->transport.discovery == (c->transport.address | ~c->transport.mask)) && + dm_net_discovery_prepare(c->transport.discovery, &plan)) { pthread_mutex_unlock(&c->lock); return LDN_CONNECT_FAILED; } + dm_net_discovery_plan extra={0}; + if(!plan.automatic)dm_net_discovery_supplement(c->transport.discovery,&extra); + c->scanning=1;c->room_count=0;c->scan_plan=plan;c->scan_supplement=extra;c->scan_next=0;c->scan_tx_failed=0;ldn_wake(c); + // Keep the ordinary response window after the paced sweep, rather than + // penalizing a console near the end of a larger (at most /20) subnet. + struct timespec until=ldn_deadline(c->transport.scan_ms+dm_net_discovery_duration(&plan)+dm_net_discovery_duration(&extra)); + while (!c->stopping && !c->scan_tx_failed && (c->state == LDN_STATION || c->state == LDN_CONNECTED || c->state == LDN_CREATED)) + if (pthread_cond_timedwait(&c->changed, &c->lock, &until) == ETIMEDOUT) break; + c->scan_plan.count=c->scan_supplement.count=0; + if (c->scan_tx_failed) { c->scanning = 0; pthread_mutex_unlock(&c->lock); return LDN_CONNECT_FAILED; } + if (c->stopping || (c->state != LDN_STATION && c->state != LDN_CONNECTED && c->state != LDN_CREATED)) { c->scanning = 0; pthread_mutex_unlock(&c->lock); return LDN_INVALID_STATE; } + for (int i = 0; i < c->room_count && *count < max; ++i) if (dm_ldn_filter_match(&c->rooms[i].network, f, channel)) out[(*count)++] = c->rooms[i].network; + ldn_trace("scan complete rooms=%d matched=%d", c->room_count, *count); + c->scanning = 0; pthread_mutex_unlock(&c->lock); return 0; +} +uint32_t dm_ldn_create(dm_ldn_context *c, const dm_ldn_network_config *cfg, const dm_ldn_security_config *sec, const dm_ldn_user *user, const dm_ldn_security_parameter *parameter, int count, const dm_ldn_address *addresses) { + if (cfg && sec) ldn_trace("create-config channel=%d max-nodes=%d version=%d security-mode=%u passphrase-size=%u private-count=%d", cfg->channel, cfg->max_nodes, cfg->version, sec->mode, sec->size, count); + if (!c || !cfg || !sec || !user || cfg->max_nodes < 1 || cfg->max_nodes > 8 || cfg->version < 0 || cfg->channel < 0 || cfg->channel > 255 || sec->size > 64 || count < 0 || count > 8 || (count && !addresses) || !memchr(user->name, 0, 33)) return LDN_INVALID; + pthread_mutex_lock(&c->lock); if (c->state != LDN_AP) { pthread_mutex_unlock(&c->lock); return LDN_INVALID_STATE; } + int fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { pthread_mutex_unlock(&c->lock); return LDN_CONNECT_FAILED; } + ldn_nonblock(fd); int yes = 1; setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes); struct sockaddr_in a = ldn_endpoint(c->transport.address, c->transport.port); + if (bind(fd, (struct sockaddr *)&a, sizeof a) || listen(fd, 8)) { ldn_trace("create-listener failed errno=%d", errno); close(fd); pthread_mutex_unlock(&c->lock); return LDN_CONNECT_FAILED; } + dm_ldn_network n = {0}; n.id.intent = cfg->intent; n.max_nodes = cfg->max_nodes; n.security_mode = sec->mode; + n.common.channel = cfg->channel ? cfg->channel : 6; n.common.link = 3; n.common.type = 2; n.common.ssid.len = 32; + ldn_local_mac(c, n.common.mac); n.nodes[0] = ldn_node(c, user, cfg->version, 0); n.node_count = 1; + arc4random_buf(n.id.session, 16); arc4random_buf(n.security, 16); + if (parameter) { memcpy(n.id.session, parameter->session, 16); memcpy(n.security, parameter->server_random, 16); } + static const char hex[] = "0123456789abcdef"; + for (int i = 0; i < 16; i++) { n.common.ssid.text[i*2] = hex[n.id.session[i] >> 4]; n.common.ssid.text[i*2+1] = hex[n.id.session[i] & 15]; } + n.accept_policy = c->network.accept_policy; n.advertise_size = c->network.advertise_size; memcpy(n.advertise, c->network.advertise, sizeof n.advertise); + c->private_count = count; if (count) memcpy(c->private_addresses, addresses, count * sizeof *addresses); + c->config = *cfg; c->listener = fd; c->reason = 0; memset(c->updates, 0, sizeof c->updates); ldn_network_set(c, &n); ldn_state_set(c, LDN_CREATED); ldn_wake(c); + pthread_mutex_unlock(&c->lock); return 0; +} +uint32_t dm_ldn_connect(dm_ldn_context *c, const dm_ldn_network *network, const dm_ldn_security_config *security, const dm_ldn_user *user, int version, int option) { + ldn_trace("connect-config version=%d option=%d network-valid=%d remote-version=%d", version, option, dm_ldn_network_valid(network), network ? network->nodes[0].version : -1); + if (!c || !network || !security || !user || !dm_ldn_network_valid(network) || security->size > 64 || !memchr(user->name, 0, 33) || option < 0 || option > 1 || version < 0 || version > 32767) return LDN_INVALID; + if (version < network->nodes[0].version) return LDN_VERSION_LOW; if (version > network->nodes[0].version) return LDN_VERSION_HIGH; + // Node count can change between Scan and Connect. Admission uses the + // listener's current roster, rather than rejecting a stale full snapshot. + pthread_mutex_lock(&c->lock); if (c->state != LDN_STATION || c->peers[0].fd >= 0) { pthread_mutex_unlock(&c->lock); return LDN_INVALID_STATE; } + struct sockaddr_in dest = ldn_endpoint(htonl(network->nodes[0].ip), 11452); + for (int i = 0; i < c->room_count; ++i) if (!memcmp(&network->id, &c->rooms[i].network.id, sizeof network->id)) dest = c->rooms[i].endpoint; + int fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { pthread_mutex_unlock(&c->lock); return LDN_CONNECT_FAILED; } + ldn_nonblock(fd); struct sockaddr_in local = ldn_endpoint(c->transport.address, 0); + if (bind(fd, (struct sockaddr *)&local, sizeof local)) { close(fd); pthread_mutex_unlock(&c->lock); return LDN_CONNECT_FAILED; } + int connected = connect(fd, (struct sockaddr *)&dest, sizeof dest); int error = errno; + if (connected && error != EINPROGRESS) { ldn_trace("connect-native failed errno=%d", error); close(fd); pthread_mutex_unlock(&c->lock); return LDN_NOT_FOUND; } + // Complete connect outside the context lock. The descriptor has not been + // published to the worker yet, so it cannot be reused underneath this wait. + pthread_mutex_unlock(&c->lock); struct pollfd pollfd = {fd, POLLOUT, 0}; int ready; do { ready = poll(&pollfd, 1, (int)c->transport.connect_ms); } while (ready < 0 && errno == EINTR); + socklen_t error_len = sizeof error; if (ready <= 0 || getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &error_len) || error) { ldn_trace("connect-complete failed ready=%d errno=%d socket-error=%d", ready, errno, error); close(fd); return ready == 0 ? LDN_TIMEOUT : LDN_CONNECT_FAILED; } + pthread_mutex_lock(&c->lock); if (c->state != LDN_STATION || c->peers[0].fd >= 0) { close(fd); pthread_mutex_unlock(&c->lock); return LDN_INVALID_STATE; } + c->network = *network; memset(c->updates, 0, sizeof c->updates); c->reason = 0; + ldn_peer *p = &c->peers[0]; p->fd = fd; p->generation = ++c->generation; p->deadline = ldn_ms() + c->transport.connect_ms; + dm_ldn_node node = ldn_node(c, user, version, 0); + if (ldn_queue(c, 0, DM_LDN_CONNECT, &node, sizeof node)) { ldn_peer_close(c, 0); pthread_mutex_unlock(&c->lock); return LDN_CONNECT_FAILED; } + ldn_wake(c); struct timespec until = ldn_deadline(c->transport.connect_ms); int timedout = 0; + while (!c->stopping && c->state == LDN_STATION && p->fd >= 0) if (pthread_cond_timedwait(&c->changed, &c->lock, &until) == ETIMEDOUT) { timedout = 1; break; } + uint32_t result = c->state == LDN_CONNECTED ? 0 : timedout ? LDN_TIMEOUT : LDN_REJECTED; + if (result) ldn_peer_close(c, 0); pthread_mutex_unlock(&c->lock); return result; +} +uint32_t dm_ldn_get_network(dm_ldn_context *c, dm_ldn_network *network, dm_ldn_update *updates, int count) { + if (!c || !network || count < 0 || count > 8 || (count && !updates)) return LDN_INVALID; + pthread_mutex_lock(&c->lock); uint32_t result = LDN_INVALID_STATE; + if (c->state == LDN_CREATED || c->state == LDN_CONNECTED) { *network = c->network; if (count) { memcpy(updates, c->updates, count * sizeof *updates); memset(c->updates, 0, count * sizeof *updates); } result = 0; } + pthread_mutex_unlock(&c->lock); return result; +} +uint32_t dm_ldn_advertise(dm_ldn_context *c, const void *data, size_t size) { + if (!c || size > 384 || (size && !data)) return LDN_INVALID; pthread_mutex_lock(&c->lock); uint32_t result = LDN_INVALID_STATE; + if (c->state == LDN_AP || c->state == LDN_CREATED) { memset(c->network.advertise, 0, 384); if (size) memcpy(c->network.advertise, data, size); c->network.advertise_size = size; if (c->state == LDN_CREATED) { ldn_changed(c); ldn_sync(c); } result = 0; } + pthread_mutex_unlock(&c->lock); return result; +} +uint32_t dm_ldn_policy(dm_ldn_context *c, int policy) { + if (!c || policy < 0 || policy > 3) return LDN_INVALID; pthread_mutex_lock(&c->lock); uint32_t result = LDN_INVALID_STATE; + if (c->state == LDN_AP || c->state == LDN_CREATED) { c->network.accept_policy = policy; if (c->state == LDN_CREATED) { ldn_changed(c); ldn_sync(c); } result = 0; } + pthread_mutex_unlock(&c->lock); return result; +} +uint32_t dm_ldn_filter_add(dm_ldn_context *c, const uint8_t mac[6]) { + if (!c || !mac) return LDN_INVALID; pthread_mutex_lock(&c->lock); uint32_t result = LDN_INVALID_STATE; + if (c->state == LDN_AP || c->state == LDN_CREATED) { result = 0; if (!ldn_mac_in_list(mac, c->filters, c->filter_count)) { if (c->filter_count == 8) result = LDN_FULL; else memcpy(c->filters[c->filter_count++], mac, 6); } } + pthread_mutex_unlock(&c->lock); return result; +} +uint32_t dm_ldn_filter_clear(dm_ldn_context *c) { if (!c) return LDN_INVALID_STATE; pthread_mutex_lock(&c->lock); uint32_t r = LDN_INVALID_STATE; if (c->state == LDN_AP || c->state == LDN_CREATED) { c->filter_count = 0; r = 0; } pthread_mutex_unlock(&c->lock); return r; } +uint32_t dm_ldn_reject(dm_ldn_context *c, uint32_t ip) { + if (!c) return LDN_INVALID_STATE; pthread_mutex_lock(&c->lock); uint32_t result = c->state == LDN_CREATED ? LDN_NODE_NOT_FOUND : LDN_INVALID_STATE; + if (c->state == LDN_CREATED) for (int i = 1; i < 8; ++i) if (c->peers[i].active && c->network.nodes[i].ip == ip) { ldn_drop(c, i); result = 0; break; } + pthread_mutex_unlock(&c->lock); return result; +} + +#ifndef DM_LDN_TEST +// Every operation that takes these locks uses WAIT, including brief getters: +// a getter arriving behind a Finalize writer can wait for an in-flight scan. +// Attach only creates a guest event and publishes an atomic lifetime ID; it +// takes no context lock and must retain the SDK callback-capable entry path. +// Readers retain the context for the complete operation. Finalize joins the +// worker only after in-flight scans/connects release their read lock. The +// worker notification never acquires this lock or invokes guest code. +static dm_ldn_context *g_ldn; +static pthread_rwlock_t g_ldn_lock = PTHREAD_RWLOCK_INITIALIZER; +static void ldn_unlock(int *held) { if (*held) pthread_rwlock_unlock(&g_ldn_lock); } +static int ldn_lock(int write) { dm_guest_host_wait_begin(); if (write) pthread_rwlock_wrlock(&g_ldn_lock); else pthread_rwlock_rdlock(&g_ldn_lock); dm_guest_host_wait_end(); return 1; } +#define LDN_USE() int ldn_lock_held __attribute__((cleanup(ldn_unlock))) = ldn_lock(0) +#define LDN_WRITE() int ldn_lock_held __attribute__((cleanup(ldn_unlock))) = ldn_lock(1) +static uint64_t g_ldn_events[64]; +static void ldn_event(void *opaque) { + (void)opaque; + for (int i = 0; i < 64; ++i) { + uint64_t id = __atomic_load_n(&g_ldn_events[i], __ATOMIC_ACQUIRE); + if (id && !hle_signal_system_event_binding(id)) __atomic_compare_exchange_n(&g_ldn_events[i], &id, 0, 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED); + } +} +static Result ldn_hook_result(const char *operation, Result result) { + if (!ldn_trace_enabled() || (!result && (!strcmp(operation,"Info") || !strcmp(operation,"InfoUpdates")))) return result; + ldn_trace("op=%s result=0x%08x state=%d reason=%d", operation, result, + dm_ldn_state(g_ldn), dm_ldn_reason(g_ldn)); + return result; +} +static Result ldn_hook_info(dm_ldn_network *out, dm_ldn_update *updates, int count) { + Result result = dm_ldn_get_network(g_ldn, out, updates, count); + if (!result && ldn_trace_enabled()) { + unsigned connected = 0, own = 0; + for (int i = 0; i < 8; ++i) { + if (out->nodes[i].connected) connected |= 1u << i; + if (out->nodes[i].connected && out->nodes[i].ip == ntohl(g_ldn->transport.address)) own |= 1u << i; + } + ldn_trace("info nodes=%u max=%d connected-mask=0x%x own-mask=0x%x updates=%d host-version=%d", out->node_count, out->max_nodes, connected, own, count, out->nodes[0].version); + } + return ldn_hook_result("Info", result); +} +static int ldn_enabled(void) { const char *m = getenv("DM_NETWORK"); return m && (!strcmp(m, "ldn") || !strcmp(m, "auto")); } +HLE_FORCE_WAIT("_ZN2nn3ldn10InitializeEv", "native ldn_mitm control transport", Result, h_ldn_Init, void) { LDN_WRITE(); + if (!ldn_enabled()) return ldn_hook_result("InitDisabled", LDN_ERROR(22)); if (g_ldn) return ldn_hook_result("InitExisting",0); + dm_ldn_transport t = {.port=11452, .discovery_port=11452, .scan_ms=1000, .connect_ms=4000}; + if (dm_net_ipconfig(&t.address, &t.mask, NULL, NULL, NULL)) return LDN_ERROR(16); + t.discovery = t.address | ~t.mask; dm_net_discovery_plan plan; + if (dm_net_discovery_prepare(t.discovery, &plan)) { + LOG("[RED] LDN discovery unavailable (errno %d): no eligible bounded IPv4 LAN or valid explicit peer", dm_net_errno()); + return LDN_ERROR(22); + } + g_ldn = dm_ldn_start(&t, ldn_event, NULL); if (g_ldn) ldn_event(NULL); return ldn_hook_result("Init",g_ldn ? 0 : LDN_ERROR(16)); +} +HLE_FORCE_WAIT("_ZN2nn3ldn8FinalizeEv", "stop native LDN workers and peers", void, h_ldn_Fini, void) { LDN_WRITE(); dm_ldn_context *c = g_ldn; g_ldn = NULL; for (int i = 0; i < 64; ++i) __atomic_store_n(&g_ldn_events[i], 0, __ATOMIC_RELEASE); dm_guest_host_wait_begin(); dm_ldn_stop(c); dm_guest_host_wait_end(); } +HLE_FORCE_WAIT("_ZN2nn3ldn8GetStateEv", "native LDN service state", int, h_ldn_State, void) { LDN_USE(); return dm_ldn_state(g_ldn); } +HLE_FORCE("_ZN2nn3ldn22AttachStateChangeEventEPNS_2os15SystemEventTypeE", "real native LDN state event", void, h_ldn_Attach, void *ev) { + if (!ev) return; + hle_bind_system_event(ev, 1); uint64_t id = hle_system_event_binding(ev); + for (int i = 0; i < 64; ++i) if (__atomic_load_n(&g_ldn_events[i], __ATOMIC_ACQUIRE) == id) return; + for (int i = 0; i < 64; ++i) { uint64_t empty = 0; if (__atomic_compare_exchange_n(&g_ldn_events[i], &empty, id, 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED) || empty == id) return; } + die("LDN state event binding table full"); +} +HLE_FORCE_WAIT("_ZN2nn3ldn11OpenStationEv", "native LDN station lifecycle", Result, h_ldn_OpenSt, void) { LDN_USE(); return ldn_hook_result("OpenSt", dm_ldn_open(g_ldn, 0)); } +HLE_FORCE_WAIT("_ZN2nn3ldn12CloseStationEv", "native LDN station lifecycle", Result, h_ldn_CloseSt, void) { LDN_USE(); return ldn_hook_result("CloseSt", dm_ldn_close(g_ldn, 0)); } +HLE_FORCE_WAIT("_ZN2nn3ldn15OpenAccessPointEv", "native LDN access point lifecycle", Result, h_ldn_OpenAp, void) { LDN_USE(); return ldn_hook_result("OpenAp", dm_ldn_open(g_ldn, 1)); } +HLE_FORCE_WAIT("_ZN2nn3ldn16CloseAccessPointEv", "native LDN access point lifecycle", Result, h_ldn_CloseAp, void) { LDN_USE(); return ldn_hook_result("CloseAp", dm_ldn_close(g_ldn, 1)); } +HLE_FORCE_WAIT("_ZN2nn3ldn10DisconnectEv", "close native LDN station session", Result, h_ldn_Disconnect, void) { LDN_USE(); return ldn_hook_result("Disconnect", dm_ldn_disconnect(g_ldn, 0)); } +HLE_FORCE_WAIT("_ZN2nn3ldn14DestroyNetworkEv", "close native LDN access point sessions", Result, h_ldn_Destroy, void) { LDN_USE(); return ldn_hook_result("Destroy", dm_ldn_disconnect(g_ldn, 1)); } +HLE_FORCE_WAIT("_ZN2nn3ldn4ScanEPNS0_11NetworkInfoEPiiRKNS0_10ScanFilterEi", "real UDP LDN discovery", Result, h_ldn_Scan, dm_ldn_network *o, int *n, int max, const dm_ldn_filter *f, int channel) { LDN_USE(); if (!f) return LDN_INVALID; dm_ldn_filter public_filter = *f; public_filter.flags &= 0x37; dm_guest_host_wait_begin(); Result r = dm_ldn_scan(g_ldn, o, n, max, &public_filter, channel); dm_guest_host_wait_end(); return ldn_hook_result("Scan", r); } +HLE_FORCE_WAIT("_ZN2nn3ldn11ScanPrivateEPNS0_11NetworkInfoEPiiRKNS0_10ScanFilterEi", "real filtered UDP LDN discovery", Result, h_ldn_ScanPrivate, dm_ldn_network *o, int *n, int max, const dm_ldn_filter *f, int channel) { LDN_USE(); dm_guest_host_wait_begin(); Result r = dm_ldn_scan(g_ldn, o, n, max, f, channel); dm_guest_host_wait_end(); return ldn_hook_result("ScanPrivate", r); } +HLE_FORCE_WAIT("_ZN2nn3ldn13CreateNetworkERKNS0_13NetworkConfigERKNS0_14SecurityConfigERKNS0_10UserConfigE", "native LDN access point creation", Result, h_ldn_Create, const dm_ldn_network_config *n, const dm_ldn_security_config *s, const dm_ldn_user *u) { LDN_USE(); return ldn_hook_result("Create", dm_ldn_create(g_ldn, n, s, u, NULL, 0, NULL)); } +HLE_FORCE_WAIT("_ZN2nn3ldn20CreateNetworkPrivateERKNS0_13NetworkConfigERKNS0_14SecurityConfigERKNS0_17SecurityParameterERKNS0_10UserConfigEiPKNS0_12AddressEntryE", "native LDN private session and accept list", Result, h_ldn_CreatePrivate, const dm_ldn_network_config *n, const dm_ldn_security_config *s, const dm_ldn_security_parameter *p, const dm_ldn_user *u, int count, const dm_ldn_address *addresses) { LDN_USE(); if (!p) return LDN_INVALID; return ldn_hook_result("CreatePrivate", dm_ldn_create(g_ldn, n, s, u, p, count, addresses)); } +HLE_FORCE_WAIT("_ZN2nn3ldn7ConnectERKNS0_11NetworkInfoERKNS0_14SecurityConfigERKNS0_10UserConfigEiNS0_13ConnectOptionE", "real TCP LDN station handshake", Result, h_ldn_Connect, const dm_ldn_network *n, const dm_ldn_security_config *s, const dm_ldn_user *u, int version, int option) { LDN_USE(); dm_guest_host_wait_begin(); Result r = dm_ldn_connect(g_ldn, n, s, u, version, option); dm_guest_host_wait_end(); return ldn_hook_result("Connect", r); } +HLE_FORCE_WAIT("_ZN2nn3ldn7ConnectERKNS0_11NetworkInfoERKNS0_14SecurityConfigERKNS0_10UserConfigEi", "SDK legacy LDN connect overload", Result, h_ldn_ConnectLegacy, const dm_ldn_network *n, const dm_ldn_security_config *s, const dm_ldn_user *u, int version) { LDN_USE(); dm_guest_host_wait_begin(); Result r = dm_ldn_connect(g_ldn, n, s, u, version, 1); dm_guest_host_wait_end(); return ldn_hook_result("ConnectLegacy", r); } +static Result ldn_connect_private(const dm_ldn_network_config *n, const dm_ldn_security_config *s, const dm_ldn_security_parameter *p, const dm_ldn_user *u, int version, int option) { + if (!n || !p) return LDN_INVALID; + dm_ldn_filter f = {.flags=35}; f.id.intent = n->intent; memcpy(f.id.session, p->session, 16); dm_ldn_network rooms[24]; int count; + dm_guest_host_wait_begin(); Result r = dm_ldn_scan(g_ldn, rooms, &count, 24, &f, n->channel); + if (!r) { r = LDN_NOT_FOUND; for (int i = 0; i < count; ++i) if (!memcmp(rooms[i].security, p->server_random, 16)) { r = dm_ldn_connect(g_ldn, &rooms[i], s, u, version, option); break; } } + dm_guest_host_wait_end(); return r; +} +HLE_FORCE_WAIT("_ZN2nn3ldn14ConnectPrivateERKNS0_13NetworkConfigERKNS0_14SecurityConfigERKNS0_17SecurityParameterERKNS0_10UserConfigEiNS0_13ConnectOptionE", "real private-session LDN discovery and handshake", Result, h_ldn_ConnectPrivate, const dm_ldn_network_config *n, const dm_ldn_security_config *s, const dm_ldn_security_parameter *p, const dm_ldn_user *u, int version, int option) { LDN_USE(); return ldn_hook_result("ConnectPrivate",ldn_connect_private(n, s, p, u, version, option)); } +HLE_FORCE_WAIT("_ZN2nn3ldn14ConnectPrivateERKNS0_13NetworkConfigERKNS0_14SecurityConfigERKNS0_17SecurityParameterERKNS0_10UserConfigEi", "SDK legacy private LDN connect overload", Result, h_ldn_ConnectPrivateLegacy, const dm_ldn_network_config *n, const dm_ldn_security_config *s, const dm_ldn_security_parameter *p, const dm_ldn_user *u, int version) { LDN_USE(); return ldn_hook_result("ConnectPrivateLegacy",ldn_connect_private(n, s, p, u, version, 1)); } +HLE_FORCE_WAIT("_ZN2nn3ldn14GetNetworkInfoEPNS0_11NetworkInfoE", "read real LDN network snapshot", Result, h_ldn_Info, dm_ldn_network *o) { LDN_USE(); return ldn_hook_info(o, NULL, 0); } +HLE_FORCE_WAIT("_ZN2nn3ldn14GetNetworkInfoEPNS0_11NetworkInfoEPNS0_16NodeLatestUpdateEi", "read and consume real LDN node changes", Result, h_ldn_InfoUpdates, dm_ldn_network *o, dm_ldn_update *u, int count) { LDN_USE(); return ldn_hook_info(o, u, count); } +HLE_FORCE_WAIT("_ZN2nn3ldn14GetIpv4AddressEPNS0_11Ipv4AddressEPNS0_10SubnetMaskE", "actual adapter addresses for LDN game sockets", Result, h_ldn_Ip, uint32_t *a, uint32_t *m) { LDN_USE(); if (!a || !m) return LDN_INVALID; dm_ldn_network n; Result r = dm_ldn_get_network(g_ldn, &n, NULL, 0); if (r) return ldn_hook_result("Ip",r); *a = ntohl(g_ldn->transport.address); *m = ntohl(g_ldn->transport.mask); return ldn_hook_result("Ip",0); } +HLE_FORCE_WAIT("_ZN2nn3ldn20GetSecurityParameterEPNS0_17SecurityParameterE", "read native LDN session identifiers", Result, h_ldn_Security, dm_ldn_security_parameter *o) { LDN_USE(); if (!o) return LDN_INVALID; dm_ldn_network n; Result r = dm_ldn_get_network(g_ldn, &n, NULL, 0); if (!r) { memcpy(o->server_random, n.security, 16); memcpy(o->session, n.id.session, 16); } return ldn_hook_result("Security", r); } +HLE_FORCE_WAIT("_ZN2nn3ldn16SetAdvertiseDataEPKvm", "publish actual LDN advertise bytes", Result, h_ldn_Advert, const void *d, uint64_t size) { LDN_USE(); return ldn_hook_result("Advert", dm_ldn_advertise(g_ldn, d, size)); } +HLE_FORCE_WAIT("_ZN2nn3ldn19GetDisconnectReasonEv", "native LDN disconnect reason", int, h_ldn_Reason, void) { LDN_USE(); return dm_ldn_reason(g_ldn); } +HLE_FORCE_WAIT("_ZN2nn3ldn20AddAcceptFilterEntryENS0_10MacAddressE", "native LDN MAC accept filter", Result, h_ldn_Add, uint64_t mac) { LDN_USE(); return ldn_hook_result("Add", dm_ldn_filter_add(g_ldn, (uint8_t *)&mac)); } +HLE_FORCE_WAIT("_ZN2nn3ldn20AddAcceptFilterEntryERKNS0_8NodeInfoE", "native LDN node accept filter", Result, h_ldn_AddNode, const dm_ldn_node *node) { LDN_USE(); return node ? dm_ldn_filter_add(g_ldn, node->mac) : LDN_INVALID; } +HLE_FORCE_WAIT("_ZN2nn3ldn17ClearAcceptFilterEv", "clear native LDN accept filter", Result, h_ldn_Clear, void) { LDN_USE(); return ldn_hook_result("Clear", dm_ldn_filter_clear(g_ldn)); } +HLE_FORCE_WAIT("_ZN2nn3ldn22SetStationAcceptPolicyENS0_12AcceptPolicyE", "enforce native LDN accept policy", Result, h_ldn_Policy, int policy) { LDN_USE(); return ldn_hook_result("Policy", dm_ldn_policy(g_ldn, policy)); } +HLE_FORCE_WAIT("_ZN2nn3ldn6RejectENS0_11Ipv4AddressE", "disconnect actual native LDN member", Result, h_ldn_Reject, uint32_t ip) { LDN_USE(); return ldn_hook_result("Reject", dm_ldn_reject(g_ldn, ip)); } +HLE_FORCE_WAIT("_ZN2nn3ldn16GetNetworkConfigEPNS0_13NetworkConfigE", "read native LDN network configuration", Result, h_ldn_Config, dm_ldn_network_config *o) { LDN_USE(); if (!o) return LDN_INVALID; dm_ldn_network n; Result r = dm_ldn_get_network(g_ldn, &n, NULL, 0); if (!r) { memset(o, 0, sizeof *o); o->intent = n.id.intent; o->channel = n.common.channel; o->max_nodes = n.max_nodes; o->version = n.nodes[0].version; } return ldn_hook_result("Config", r); } +#endif diff --git a/dm/host/hle_ldn.h b/dm/host/hle_ldn.h new file mode 100644 index 0000000000..7deb708a9e --- /dev/null +++ b/dm/host/hle_ldn.h @@ -0,0 +1,62 @@ +// LDN service ABI and the ldn_mitm LAN wire format. Original implementation; +// layout references: switchbrew/libnx ldn.h and the ldn_mitm protocol headers. +#pragma once +#include +#include + +typedef struct { uint8_t len; char text[33]; } dm_ldn_ssid; +typedef struct { int64_t local_id; uint8_t reserved[2]; uint16_t scene; uint8_t reserved2[4]; } dm_ldn_intent; +typedef struct { dm_ldn_intent intent; uint8_t session[16]; } dm_ldn_id; +typedef struct { uint32_t ip; uint8_t mac[6]; int8_t id; uint8_t connected; char name[33]; uint8_t platform; int16_t version; uint8_t reserved[16]; } dm_ldn_node; +typedef struct { uint8_t mac[6]; dm_ldn_ssid ssid; int16_t channel; int8_t link; uint8_t type; uint8_t reserved[4]; } dm_ldn_common; +typedef struct { + dm_ldn_id id; dm_ldn_common common; uint8_t security[16]; + uint16_t security_mode; uint8_t accept_policy, version; uint8_t reserved[2]; + int8_t max_nodes; uint8_t node_count; dm_ldn_node nodes[8]; uint8_t reserved2[2]; + uint16_t advertise_size; uint8_t advertise[384], reserved3[140]; uint64_t reserved4; +} dm_ldn_network; +typedef struct { dm_ldn_intent intent; int16_t channel; int8_t max_nodes; uint8_t reserved; int16_t version; uint8_t reserved2[10]; } dm_ldn_network_config; +typedef struct { uint16_t mode, size; uint8_t passphrase[64]; } dm_ldn_security_config; +typedef struct { uint8_t server_random[16], session[16]; } dm_ldn_security_parameter; +typedef struct { char name[33]; uint8_t reserved[15]; } dm_ldn_user; +typedef struct { dm_ldn_id id; uint32_t type; uint8_t mac[6]; dm_ldn_ssid ssid; uint8_t reserved[16]; uint32_t flags; } dm_ldn_filter; +typedef struct { uint32_t ip; uint8_t mac[6], reserved[2]; } dm_ldn_address; +typedef struct { uint8_t change, reserved[7]; } dm_ldn_update; +_Static_assert(sizeof(dm_ldn_node) == 0x40, "LDN NodeInfo ABI"); +_Static_assert(sizeof(dm_ldn_network) == 0x480, "LDN NetworkInfo ABI"); +_Static_assert(offsetof(dm_ldn_network, nodes) == 0x68, "LDN node array offset"); +_Static_assert(offsetof(dm_ldn_network, advertise) == 0x26c, "LDN advertise offset"); +_Static_assert(sizeof(dm_ldn_network_config) == 0x20 && sizeof(dm_ldn_filter) == 0x60, "LDN config ABI"); + +enum { DM_LDN_PACKET_MAX = 2048, DM_LDN_SCAN = 0, DM_LDN_SCAN_RESPONSE = 1, DM_LDN_CONNECT = 2, DM_LDN_SYNC = 3 }; +// Wire integers are little endian. A zero byte followed by N expands to N+1 +// zeros. Nonzero bytes are literals. Unknown types and non-exact sizes fail. +int dm_ldn_packet_encode(uint8_t *out, size_t capacity, unsigned type, const void *payload, size_t size, int compress); +int dm_ldn_packet_size(const uint8_t header[12]); +int dm_ldn_packet_decode(const uint8_t *packet, size_t size, unsigned *type, void *payload, size_t capacity); +int dm_ldn_network_valid(const dm_ldn_network *network); +int dm_ldn_filter_match(const dm_ldn_network *network, const dm_ldn_filter *filter, int channel); + +typedef struct dm_ldn_context dm_ldn_context; +// Addresses use native in_addr byte order; guest NodeInfo/Ipv4Address values +// use the SDK's host numeric order. A zero bind address listens on all adapters. +// A supplied locally administered MAC identifies a virtual adapter; zero derives +// the conventional ldn_mitm identity from its IPv4 address. +typedef struct { uint32_t address, mask, discovery, bind_address; uint16_t port, discovery_port; unsigned scan_ms, connect_ms; uint8_t mac[6]; } dm_ldn_transport; +typedef void (*dm_ldn_notify)(void *opaque); +dm_ldn_context *dm_ldn_start(const dm_ldn_transport *transport, dm_ldn_notify notify, void *opaque); +void dm_ldn_stop(dm_ldn_context *context); +uint32_t dm_ldn_open(dm_ldn_context *context, int access_point); +uint32_t dm_ldn_close(dm_ldn_context *context, int access_point); +int dm_ldn_state(dm_ldn_context *context); +int dm_ldn_reason(dm_ldn_context *context); +uint32_t dm_ldn_scan(dm_ldn_context *context, dm_ldn_network *out, int *count, int maximum, const dm_ldn_filter *filter, int channel); +uint32_t dm_ldn_create(dm_ldn_context *context, const dm_ldn_network_config *network, const dm_ldn_security_config *security, const dm_ldn_user *user, const dm_ldn_security_parameter *parameter, int address_count, const dm_ldn_address *addresses); +uint32_t dm_ldn_connect(dm_ldn_context *context, const dm_ldn_network *network, const dm_ldn_security_config *security, const dm_ldn_user *user, int version, int option); +uint32_t dm_ldn_disconnect(dm_ldn_context *context, int host); +uint32_t dm_ldn_get_network(dm_ldn_context *context, dm_ldn_network *network, dm_ldn_update *updates, int count); +uint32_t dm_ldn_advertise(dm_ldn_context *context, const void *data, size_t size); +uint32_t dm_ldn_policy(dm_ldn_context *context, int policy); +uint32_t dm_ldn_filter_add(dm_ldn_context *context, const uint8_t mac[6]); +uint32_t dm_ldn_filter_clear(dm_ldn_context *context); +uint32_t dm_ldn_reject(dm_ldn_context *context, uint32_t ip); diff --git a/dm/host/hle_ldn_protocol.c b/dm/host/hle_ldn_protocol.c new file mode 100644 index 0000000000..3503fc2ed0 --- /dev/null +++ b/dm/host/hle_ldn_protocol.c @@ -0,0 +1,70 @@ +// Original bounded encoder/decoder for the public ldn_mitm wire format. +// No discovery/state implementation from another project is included here. +#include "hle_ldn.h" +#include + +static unsigned payload_size(unsigned type) { + return type == DM_LDN_SCAN ? 0 : type == DM_LDN_CONNECT ? sizeof(dm_ldn_node) : + type == DM_LDN_SCAN_RESPONSE || type == DM_LDN_SYNC ? sizeof(dm_ldn_network) : UINT32_MAX; +} +static unsigned le16(const uint8_t *p) { return p[0] | (unsigned)p[1] << 8; } +static void put16(uint8_t *p, unsigned n) { p[0] = n; p[1] = n >> 8; } +int dm_ldn_packet_size(const uint8_t *h) { + if (!h || h[0] != 0 || h[1] != 0x14 || h[2] != 0x45 || h[3] != 0x11 || h[5] > 1 || h[10] || h[11]) return -1; + unsigned expected = payload_size(h[4]), n = le16(h + 6), expanded = le16(h + 8); + if (expected == UINT32_MAX || n > DM_LDN_PACKET_MAX - 12 || (h[5] ? expanded != expected || !n || !expanded : n != expected || expanded)) return -1; + return (int)n + 12; +} +int dm_ldn_packet_encode(uint8_t *out, size_t cap, unsigned type, const void *payload, size_t size, int compress) { + if (!out || size != payload_size(type) || (size && !payload) || cap < 12 || size > DM_LDN_PACKET_MAX - 12) return -1; + uint8_t encoded[DM_LDN_PACKET_MAX]; size_t n = 0; + const uint8_t *p = payload; + if (compress && size) for (size_t i = 0; i < size;) { + uint8_t b = p[i++]; encoded[n++] = b; + if (!b) { unsigned zeros = 0; while (i < size && !p[i] && zeros < 255) { ++i; ++zeros; } encoded[n++] = (uint8_t)zeros; } + } + int compressed = compress && size && n < size; + if (!compressed) n = size; + if (n + 12 > cap) return -1; + memset(out, 0, 12); out[1] = 0x14; out[2] = 0x45; out[3] = 0x11; out[4] = type; out[5] = compressed; + put16(out + 6, (unsigned)n); put16(out + 8, compressed ? (unsigned)size : 0); + if (n) memcpy(out + 12, compressed ? encoded : p, n); + return (int)n + 12; +} +int dm_ldn_packet_decode(const uint8_t *packet, size_t size, unsigned *type, void *payload, size_t cap) { + if (!packet || size < 12 || dm_ldn_packet_size(packet) != (int)size) return -1; + unsigned expected = payload_size(packet[4]); + if (expected > cap || (expected && !payload)) return -1; + uint8_t *out = payload; size_t n = 0; + if (!packet[5]) { if (expected) memcpy(out, packet + 12, expected); } + else for (size_t i = 12; i < size;) { + uint8_t b = packet[i++]; unsigned run = 1; + if (!b) { if (i == size) return -1; run += packet[i++]; } + if (run > expected - n) return -1; + memset(out + n, b, run); n += run; + } + if (packet[5] && n != expected) return -1; + if (type) *type = packet[4]; + return (int)expected; +} +int dm_ldn_network_valid(const dm_ldn_network *n) { + if (!n || n->max_nodes < 1 || n->max_nodes > 8 || n->node_count < 1 || n->node_count > n->max_nodes || + n->advertise_size > 384 || n->common.ssid.len > 32 || n->common.type != 2 || !n->nodes[0].connected || !n->nodes[0].ip || + n->common.ssid.text[n->common.ssid.len]) return 0; + unsigned connected = 0; + for (int i = 0; i < 8; i++) if (n->nodes[i].connected) { + if (n->nodes[i].connected != 1 || n->nodes[i].id != i || !n->nodes[i].ip || n->nodes[i].version < 0 || !memchr(n->nodes[i].name, 0, 33)) return 0; + ++connected; + } + return connected == n->node_count; +} +int dm_ldn_filter_match(const dm_ldn_network *n, const dm_ldn_filter *f, int channel) { + if (!dm_ldn_network_valid(n) || !f || f->flags & ~63u || ((f->flags & 16) && f->ssid.len > 32) || (channel && channel != n->common.channel)) return 0; + if ((f->flags & 1) && f->id.intent.local_id != n->id.intent.local_id) return 0; + if ((f->flags & 2) && memcmp(f->id.session, n->id.session, 16)) return 0; + if ((f->flags & 4) && f->type != 3 && f->type != n->common.type) return 0; + if ((f->flags & 8) && memcmp(f->mac, n->common.mac, 6)) return 0; + if ((f->flags & 16) && (f->ssid.len != n->common.ssid.len || memcmp(f->ssid.text, n->common.ssid.text, f->ssid.len))) return 0; + if ((f->flags & 32) && f->id.intent.scene != n->id.intent.scene) return 0; + return 1; +} diff --git a/dm/host/hle_mii.c b/dm/host/hle_mii.c index 00afe9e3ac..353ad47b58 100644 --- a/dm/host/hle_mii.c +++ b/dm/host/hle_mii.c @@ -116,6 +116,20 @@ static int mii_host_save(void) { // under g_mii_mu: the host's Miis, written t if (!ok) { unlink(t); LOG("[RED] mii: cannot write %s: the Mii is kept for this run only", p); } return ok; } +// The Nextendo account's Mii (its profile's StoreData) joins the console's Miis in Nextendo mode, unless one of them has its create ID. hle_nextendo_social_apple.m has +// the strong definition: 1 and the StoreData in Nextendo mode with a Mii on the account, else 0. A StoreData's data CRC is the CRC-16 of the bytes before the device CRC, big-endian, so those 0x42 bytes give 0 when +// it is whole; the device CRC belongs to the console that made the Mii and is not checked +__attribute__((weak)) int dm_nextendo_account_mii(uint8_t store[MII_STORE]) { (void)store; return 0; } +static void mii_account_add(void) { + uint8_t sd[MII_STORE]; mii_charinfo c; + if (!dm_nextendo_account_mii(sd)) return; + if (mii_crc16(sd, MII_STORE - 2)) { LOG("[RED] mii: the Nextendo account's Mii fails its data CRC: it is not listed"); return; } + mii_from_store(&c, sd); + for (int i = 0; i < g_mii_n; i++) if (!memcmp(g_mii_db[i].create_id, c.create_id, sizeof c.create_id)) { LOG("mii: the Nextendo account's Mii is the console database's entry %d", i); return; } + if (g_mii_n >= MII_DB_MAX) { LOG("[RED] mii: the console's database is full: the Nextendo account's Mii is not listed"); return; } + g_mii_db[g_mii_n] = c; g_mii_own = ++g_mii_n; // counted with the console's Miis, so the host's file never keeps it + LOG("mii: the Nextendo account's Mii is database entry %d", g_mii_n - 1); +} static void mii_db_load(void) { char t[1024], p[1100]; const char *sys = dm_system_dir(t, sizeof t); g_mii_n = g_mii_own = 0; snprintf(p, sizeof p, "%s/save/8000000000000030/MiiDatabase.dat", sys); @@ -127,6 +141,7 @@ static void mii_db_load(void) { if (r < 0) LOG("[RED] mii: %s is %s: the database stays empty", p, why[-r]); else { g_mii_n = g_mii_own = r; LOG("mii: %d Miis of the console's database from %s", r, p); } } + mii_account_add(); if (!mii_host_path(p, sizeof p) || !(f = fopen(p, "rb"))) return; size_t cap = MII_HOST_HEAD + MII_DB_MAX * sizeof(mii_charinfo) + 1; uint8_t *b = malloc(cap); size_t n = b ? fread(b, 1, cap, f) : 0; fclose(f); diff --git a/dm/host/hle_misc.c b/dm/host/hle_misc.c index adcc360878..2028ad42fe 100644 --- a/dm/host/hle_misc.c +++ b/dm/host/hle_misc.c @@ -173,8 +173,6 @@ HLE_FORCE("_ZN2nn3ngc15ProfanityFilter11SetMaskModeENS1_8MaskModeE", "profanity HLE_FORCE("_ZN2nn3ngc15ProfanityFilter8FinalizeEv", "profanity filter shutdown; the host mounted no word list", void, h_ngc_Fini, void *self) { (void)self; } // ---------- nsd server name resolution / pctl free communication: networking, out of scope ---------- -HLE_FORCE("_ZN2nn3nsd7ResolveEPNS0_4FqdnERKS1_", "server name resolution, networking out of scope; cut", Result, h_nsd_Resolve, void *out, const void *in) { (void)out; (void)in; return RES_FAIL; } -HLE_FORCE("_ZN2nn3nsd9ResolveExEPNS0_4FqdnERKS1_", "server name resolution, networking out of scope; cut", Result, h_nsd_ResolveEx, void *out, const void *in) { (void)out; (void)in; return RES_FAIL; } // bool arguments only look at the low 8 bits; returns bool // The permission query answers as TryBegin / IsFreeCommunicationAvailable do: the SDK's version calls the pctl service (pctl::detail::ipc::GetService), which the host never opens (DRAGON QUEST XI S imports it; from PR #38) HLE_FORCE("_ZN2nn4pctl32CheckFreeCommunicationPermissionEb", "parental controls · permission to communicate with others, networking out of scope; never, no system UI", unsigned, h_pctl_CheckFree, unsigned show_ui) { (void)show_ui; return 0; } diff --git a/dm/host/hle_net.c b/dm/host/hle_net.c index 305d8429ae..cc062f397a 100644 --- a/dm/host/hle_net.c +++ b/dm/host/hle_net.c @@ -1,8 +1,11 @@ -// Network services stay offline. The BSD service additionally supplies process-local UDP and EventFd transports, which offline engines use for their own threads. +// Network services: offline by default. Offline, the BSD service supplies process-local UDP and EventFd transports, which offline engines use for their own threads; an +// explicit network mode translates the guest's sockets to Darwin's instead (net_socket.h). #include "hle.h" #include "hle_net.h" +#include "net_socket.h" #include #include +void dm_guest_sleep_ns(int64_t ns); HLE_FORCE("_ZN2nn6socket10InitializeERKNS0_6ConfigE", "connects to the bsd socket service; offline, creates no session (cut)", Result, h_socket_Initialize, const void *cfg) { (void)cfg; return RES_OK; } // SDK 21 (Star Fox) inlines nn::socket::Initialize(const Config &) into the game, and the service connection is this call @@ -17,35 +20,62 @@ HLE_FORCE("_ZN2nn4nifm10InitializeEv", "connects to the nifm network management // the submission and settled at the next. The hold used to be 50 ms of host time: Hades' NetworkPollThread (main+0x27aaa0) polls with SleepThread(0) and cancels after 2,000 // queries, 2,000 IPCs on the Switch but 0.1 ms here, so it cancelled and submitted again forever (1.17 billion queries a minute, a host core). Its stamp, now_ns() | 1, also read // as settled at once whenever the next query came within the same 42 ns clock tick (30% of Hades' submissions) +static _Atomic int g_nifm_pending; static _Atomic int g_nifm_hold; // queries the pending request still answers "on hold" (0 = none, or settled) -HLE_FORCE("_ZN2nn4nifm20SubmitNetworkRequestEv", "offline: the request is on hold for the first query, then settles as unavailable", void, h_nifm_Submit, void) { atomic_store(&g_nifm_hold, 1); } -HLE_FORCE("_ZN2nn4nifm20CancelNetworkRequestEv", "offline: drops the pending request", void, h_nifm_Cancel, void) { atomic_store(&g_nifm_hold, 0); } +HLE_FORCE("_ZN2nn4nifm20SubmitNetworkRequestEv", "offline: the request is on hold for the first query, then settles as unavailable", void, h_nifm_Submit, void) { atomic_store(&g_nifm_pending, 1); atomic_store(&g_nifm_hold, 1); } +HLE_FORCE("_ZN2nn4nifm20CancelNetworkRequestEv", "offline: drops the pending request", void, h_nifm_Cancel, void) { atomic_store(&g_nifm_pending, 0); atomic_store(&g_nifm_hold, 0); } HLE_FORCE("_ZN2nn4nifm22IsNetworkRequestOnHoldEv", "offline: on hold for the first query after the submission", int, h_nifm_OnHold, void) { int h = atomic_load(&g_nifm_hold); while (h > 0 && !atomic_compare_exchange_weak(&g_nifm_hold, &h, h - 1)) {} return h > 0; } -HLE_FORCE("_ZN2nn4nifm18IsNetworkAvailableEv", "offline: the network is always unavailable", int, h_nifm_Available, void) { return 0; } -// Returns bool (`and w0, w0, #1`, Metroid Dread's sdk+0x336210): whether the system's network screen resolved the error -HLE_FORCE("_ZN2nn4nifm31HandleNetworkRequestErrorResultEv", "offline: not resolved, shows no system network screen", unsigned, h_nifm_HandleErr, void) { return 0; } -HLE_FORCE("_ZN2nn4nifm26GetCurrentPrimaryIpAddressEPNS_6socket6InAddrE", "offline: no IP", Result, h_nifm_GetIp, uint32_t *a) { if (a) *a = 0; return RES_FAIL; } -HLE_FORCE("_ZN2nn4nifm22GetCurrentProxySettingEPNS0_12ProxySettingE", "offline: no proxy setting", Result, h_nifm_GetProxy, void *p) { (void)p; return RES_FAIL; } -HLE_FORCE("nnsslInitialize", "connects to the ssl service; the network library's global init needs it to succeed, offline creates no session (cut)", Result, h_ssl_Initialize, void) { return RES_OK; } -HLE_FORCE("nnsslFinalize", "pairs with nnsslInitialize (cut)", Result, h_ssl_Finalize, void) { return RES_OK; } +int dm_nifm_available(void) { return dm_net_enabled() && atomic_load(&g_nifm_pending) && !atomic_load(&g_nifm_hold) && !dm_net_ipconfig(NULL, NULL, NULL, NULL, NULL); } +void dm_nifm_submit_wait(void) { if (dm_net_enabled()) { h_nifm_Submit(); while (h_nifm_OnHold()) dm_guest_sleep_ns(0); } } +HLE_FORCE("_ZN2nn4nifm18IsNetworkAvailableEv", "offline by default; explicit LAN reports the actual IPv4 request state", int, h_nifm_Available, void) { return dm_nifm_available(); } +HLE_FORCE("_ZN2nn4nifm31HandleNetworkRequestErrorResultEv", "whether the network request was resolved without a system UI", unsigned, h_nifm_HandleErr, void) { return dm_nifm_available() != 0; } +HLE_FORCE("_ZN2nn4nifm26HandleNetworkRequestResultEv", "SDK 4 network request result without a system UI", Result, h_nifm_HandleResult, void) { return dm_nifm_available() ? RES_OK : RES_FAIL; } +HLE_FORCE("_ZN2nn4nifm26GetCurrentPrimaryIpAddressEPNS_6socket6InAddrE", "offline by default; explicit LAN returns the actual interface IPv4 address", Result, h_nifm_GetIp, uint32_t *a) { if (!a) return RES_FAIL; *a = 0; return dm_net_ipconfig(a, NULL, NULL, NULL, NULL) ? RES_FAIL : RES_OK; } +// The proxy setting (nifm::ProxySetting, 0xaa bytes: enabled +0, port +2, server +4, auto-auth +0x68, user +0x69, password +0x89, as Super Mario Bros. Wonder 1.2.1 +// reads it: libcurl's proxy code at main+0xf7aa40 clears 0xaa bytes first, and gRPC's proxy mapper at main+0xb31760 asks too). In a network mode the host uses no +// proxy, so it answers as a console without one: success, every field zero. Offline it still fails +HLE_FORCE("_ZN2nn4nifm22GetCurrentProxySettingEPNS0_12ProxySettingE", "network mode: no proxy (every field zero); offline: no proxy setting", Result, h_nifm_GetProxy, void *p) { + if (!p || !dm_net_enabled()) return RES_FAIL; + memset(p, 0, 0xaa); static int told; if (!told++) LOG("nifm: proxy setting asked: none (the host uses no proxy)"); return RES_OK; +} -// ---------- BSD service: local UDP/EventFd work offline; remote networking stays unavailable ---------- +// ---------- BSD service: local UDP/EventFd offline (remote networking unavailable); an explicit network mode translates the guest ABI to Darwin ---------- // Local transports are used even by offline games: RakNet sends a startup datagram to itself in Divinity: Original Sin 2. No host socket is opened. Descriptors belong to // this service, not Darwin's fd table, and stay small enough for games' fd_set arrays. Address/flag/error constants below are the Horizon/FreeBSD ABI (libnx's BSD service passes // these structures/flags unchanged; FreeBSD11 sys/socket.h and netinet/in.h). IPv4 payloads retain packet boundaries; the per-endpoint queue holds at most256 packets/1MiB. -#define SK_ENETDOWN 50 -static __thread int t_skerr = SK_ENETDOWN; -static int sk_error(int error) { t_skerr = error; return -1; } -static int sk_fail(void) { return sk_error(SK_ENETDOWN); } -int dm_sk_errno(void) { return t_skerr; } -#define SKF(m, cname, ...) HLE_FORCE(m, "local BSD descriptor service; remote networking unavailable", int, cname, __VA_ARGS__) +// Not cut: Inet* / nnsocketInet* byte order and address text conversion (pure computation). +// Both keep one errno (dm_net_errno). The network transport sets the Linux numbers hle_net_backend.c documents, and remote networking offline is Linux's ENETDOWN +// too, as Horizon's BSD IPC errno reaches the game unchanged (MK8 SDK 4 detail::Socket / GetLastErrno). The local service's other numbers below are FreeBSD's. +#define SK_ENETDOWN 100 +// The game's errno. On Horizon nn::socket's errno is the C library's: detail::SetLastErrno and GetLastErrno write and read *__errno_location(), and code such +// as gRPC's reads errno itself. Super Mario Bros. Wonder's gRPC sets 97 when it leaves IPv6 (main+0xb61480) and reads errno after its non-blocking connect +// (main+0xb61e38, tcp_client_posix.cc:299): with only the host's copy set, it took that connect's EINPROGRESS for the stale 97 and gave the address up. +// A failed hook writes it on the game's thread, at the hook boundary; a game without __errno_location keeps only the host's copy +static int *(*_Atomic g_guest_errno)(void); static _Atomic int g_guest_errno_looked; +static int *guest_errno_location(void) { + if (!atomic_load(&g_guest_errno_looked)) { g_guest_errno = (int *(*)(void))guest_sym("__errno_location"); atomic_store(&g_guest_errno_looked, 1); } + int *(*loc)(void) = g_guest_errno; return loc ? loc() : NULL; +} +long dm_net_guest_errno(long r) { if (r < 0) { int *e = guest_errno_location(); if (e) *e = dm_net_errno(); } return r; } +int dm_net_guest_errno_get(void) { int *e = guest_errno_location(); return e ? *e : dm_net_errno(); } +static int sk_error(int error) { dm_net_set_errno(error); return -1; } +static int sk_fail(void) { return sk_error(dm_net_enabled() ? 95 : SK_ENETDOWN); } +int dm_sk_unavailable(void) { return sk_fail(); } +int dm_sk_errno(void) { return dm_net_errno(); } +#define SKF(m, cname, ...) HLE_FORCE(m, "socket call: the local BSD descriptor service offline, translated Darwin sockets in an explicit network mode", int, cname, __VA_ARGS__) +#define SKW(m, cname, ...) HLE_FORCE_WAIT(m, "blocking socket call with a pausable guest context: the local service offline, Darwin sockets in a network mode", int, cname, __VA_ARGS__) +// A call with both forms: the network transport in an explicit network mode, the local service otherwise; a failure also sets the game's errno +#define SKD(net, local) dm_net_guest_errno(dm_net_enabled() ? (long)(net) : (long)(local)) void dm_guest_sleep_ns(int64_t ns); -void dm_guest_cond_wait_ns(pthread_cond_t *c, pthread_mutex_t *m, int64_t ns); -static int sk_idle(int64_t ms) { dm_guest_sleep_ns((ms < 0 ? 100 : ms) * 1000000); return 0; } +void dm_guest_cond_wait_ns(pthread_cond_t *c, pthread_mutex_t *m, int64_t ns); // hle_thread.c +// Poll / Select with nothing to wait on waits out the timeout and returns 0, as POSIX and Horizon's bsd service ignore negative descriptors (Dark Souls Remastered's +// "NexusRevolution Socket" thread spun a core on Poll(fds, 0, 33 ms) when it failed at once). An endless wait on nothing never returns; HLE_FORCE_WAIT publishes the guest +// context, so a collector can pause the thread while it waits +static int sk_idle(int64_t ms) { if (ms < 0) return dm_net_idle(); if (ms > INT64_MAX / 1000000) return sk_error(22); /* EINVAL */ dm_guest_sleep_ns(ms * 1000000); return 0; } typedef struct { int32_t fd; int16_t events, revents; } sk_pollfd; enum { EFD_MAX = 64, SK_POLLIN = 1, SK_POLLOUT = 4, SK_POLLRDNORM = 0x40, SK_POLLWRNORM = 4, SK_POLLNVAL = 0x20, SK_EBADF = 9, SK_EAGAIN = 35, SK_EINVAL = 22, SK_EMSGSIZE = 40, SK_EOPNOTSUPP = 45, SK_EADDRINUSE = 48, SK_ENOTCONN = 57, @@ -93,10 +123,10 @@ static int efd_read(int fd, uint64_t *out) { dm_host_mutex_lock(&g_efd_m); int r = -1; uint64_t gen = efd_used(fd) ? g_efd[fd].generation : 0; for (;;) { - if (!efd_used(fd) || g_efd[fd].generation != gen) { t_skerr = SK_EBADF; break; } + if (!efd_used(fd) || g_efd[fd].generation != gen) { dm_net_set_errno(SK_EBADF); break; } uint64_t *c = &g_efd[fd].count; int f = g_efd[fd].flags; if (*c) { if (f & 1) { *out = 1; *c -= 1; } else { *out = *c; *c = 0; } r = 0; break; } - if (f & 6) { t_skerr = SK_EAGAIN; break; } + if (f & 6) { dm_net_set_errno(SK_EAGAIN); break; } dm_guest_cond_wait_ns(&g_efd_c, &g_efd_m, dm_detclock_enabled() ? 1000000 : 100000000); } pthread_mutex_unlock(&g_efd_m); return r; @@ -224,10 +254,10 @@ long dm_sk_sendto(int fd, const void *data, unsigned long n, int flags, const vo if (flags & ~(SK_MSG_DONTWAIT | 4 | 0x20000)) return sk_error(SK_EOPNOTSUPP); uint32_t addr = 0; uint16_t port = 0; if (a && sk_addr_read(a, al, &addr, &port)) return -1; dm_host_mutex_lock(&g_efd_m); long r = -1; - if (!sk_udp_locked(fd)) { t_skerr = SK_EBADF; goto done; } - if (g_efd[fd].shut_write) { t_skerr = 32; goto done; } - if (!a) { if (!g_efd[fd].connected) { t_skerr = 39; goto done; } addr = g_efd[fd].peer_addr; port = g_efd[fd].peer_port; } - if (!port) { t_skerr = SK_EINVAL; goto done; } + if (!sk_udp_locked(fd)) { dm_net_set_errno(SK_EBADF); goto done; } + if (g_efd[fd].shut_write) { dm_net_set_errno(32); goto done; } + if (!a) { if (!g_efd[fd].connected) { dm_net_set_errno(39); goto done; } addr = g_efd[fd].peer_addr; port = g_efd[fd].peer_port; } + if (!port) { dm_net_set_errno(SK_EINVAL); goto done; } if (!addr) addr = 0x7f000001; if (!g_efd[fd].port && sk_bind_locked(fd, 0, 0)) goto done; uint32_t src = g_efd[fd].addr ? g_efd[fd].addr : 0x7f000001; @@ -241,7 +271,7 @@ long dm_sk_sendto(int fd, const void *data, unsigned long n, int flags, const vo // UDP drops a datagram when the receive queue is full; the sender still succeeds, as it has no delivery acknowledgement. if (g_efd[i].packets < SK_PACKET_MAX && n <= (size_t)g_efd[i].rcvbuf && g_efd[i].queued <= (size_t)g_efd[i].rcvbuf - n) { sk_packet *p = malloc(sizeof *p + n); - if (!p) { t_skerr = 55; goto done; } // ENOBUFS + if (!p) { dm_net_set_errno(55); goto done; } // ENOBUFS p->next = NULL; p->addr = src; p->port = g_efd[fd].port; p->size = n; if (n) memcpy(p->data, data, n); if (g_efd[i].tail) g_efd[i].tail->next = p; else g_efd[i].head = p; g_efd[i].tail = p; g_efd[i].queued += n; g_efd[i].packets++; pthread_cond_broadcast(&g_efd_c); @@ -267,10 +297,10 @@ long dm_sk_recvfrom(int fd, void *data, unsigned long n, int flags, void *a, uns if ((!data && n) || (a && !al)) return sk_error(SK_EINVAL); if (flags & ~(SK_MSG_DONTWAIT | SK_MSG_PEEK)) return sk_error(SK_EOPNOTSUPP); dm_host_mutex_lock(&g_efd_m); long r = -1; - if (!sk_udp_locked(fd)) { t_skerr = SK_EBADF; goto done; } + if (!sk_udp_locked(fd)) { dm_net_set_errno(SK_EBADF); goto done; } uint64_t gen = g_efd[fd].generation, start = guest_ns(); for (;;) { - if (!sk_udp_locked(fd) || g_efd[fd].generation != gen) { t_skerr = SK_EBADF; break; } + if (!sk_udp_locked(fd) || g_efd[fd].generation != gen) { dm_net_set_errno(SK_EBADF); break; } sk_packet *p = g_efd[fd].head; if (p) { size_t copied = n < p->size ? n : p->size; if (copied) memcpy(data, p->data, copied); sk_addr_write(a, al, p->addr, p->port); r = (long)copied; @@ -278,9 +308,9 @@ long dm_sk_recvfrom(int fd, void *data, unsigned long n, int flags, void *a, uns break; } if (g_efd[fd].shut_read) { r = 0; break; } - if (flags & SK_MSG_DONTWAIT || g_efd[fd].flags & SK_NONBLOCK) { t_skerr = SK_EAGAIN; break; } + if (flags & SK_MSG_DONTWAIT || g_efd[fd].flags & SK_NONBLOCK) { dm_net_set_errno(SK_EAGAIN); break; } int64_t left = g_efd[fd].recv_timeout ? g_efd[fd].recv_timeout - (int64_t)(guest_ns() - start) : 100000000; - if (left <= 0) { t_skerr = SK_EAGAIN; break; } + if (left <= 0) { dm_net_set_errno(SK_EAGAIN); break; } if (dm_detclock_enabled() && left > 1000000) left = 1000000; dm_guest_cond_wait_ns(&g_efd_c, &g_efd_m, left); } @@ -300,9 +330,10 @@ static int efd_ready(sk_pollfd *p, uint64_t n, uint64_t open, const uint64_t gen } return ready; } -int dm_sk_poll(void *fds, uint64_t n, int ms) { +int dm_sk_poll(void *fds, uint64_t n, int ms) { // also hle_offline.c's plain pollfd form + if (dm_net_enabled()) return dm_net_poll(fds, n, ms); // the transport's sockets and event descriptors sk_pollfd *p = fds; uint64_t open = 0, generation[EFD_MAX] = {0}; - if (!p && n) return sk_error(SK_EINVAL); + if (n > 1024 || (!p && n)) return sk_error(!p && n ? 14 : SK_EINVAL); // EFAULT for a missing array dm_host_mutex_lock(&g_efd_m); for (uint64_t i = 0; i < n; i++) if (p[i].fd >= 0 && sk_used(p[i].fd)) { open |= 1ull << p[i].fd; generation[p[i].fd] = g_efd[p[i].fd].generation; } for (uint64_t i = 0; i < n; i++) p[i].revents = 0; @@ -315,8 +346,9 @@ int dm_sk_poll(void *fds, uint64_t n, int ms) { } pthread_mutex_unlock(&g_efd_m); return ready; } -// fd_set is1024 bits; timeval is {i64 seconds, i64 microseconds}. Only this service's small descriptors can become ready. +// fd_set is1024 bits; timeval is {i64 seconds, i64 microseconds}. Only this service's small descriptors can become ready. An explicit network mode goes to the transport's Select instead int dm_sk_select(int nfds, uint64_t *r, uint64_t *w, uint64_t *e, const int64_t *tv) { + if (dm_net_enabled()) return dm_net_select(nfds, r, w, e, tv); uint64_t *sets[3] = {r, w, e}; static const int16_t ask[3] = {SK_POLLIN, SK_POLLOUT, 0}; sk_pollfd p[EFD_MAX]; int np = 0; if (nfds < 0 || (tv && (tv[0] < 0 || tv[1] < 0 || tv[1] >= 1000000))) return sk_error(SK_EINVAL); if (nfds > 1024) nfds = 1024; @@ -336,99 +368,81 @@ int dm_sk_select(int nfds, uint64_t *r, uint64_t *w, uint64_t *e, const int64_t } return n; } -SKF("_ZN2nn6socket6SocketENS0_6FamilyENS0_4TypeENS0_8ProtocolE", h_sk_Socket, int a, int b, int c) { return dm_sk_socket(a, b, c); } -SKF("_ZN2nn6socket4BindEiPKNS0_8SockAddrEj", h_sk_Bind, int s, const void *a, unsigned n) { return dm_sk_bind(s, a, n); } -SKF("_ZN2nn6socket7ConnectEiPKNS0_8SockAddrEj", h_sk_Connect, int s, const void *a, unsigned n) { return dm_sk_connect(s, a, n); } -SKF("_ZN2nn6socket6ListenEii", h_sk_Listen, int s, int n) { (void)s; (void)n; return sk_fail(); } -SKF("_ZN2nn6socket6AcceptEiPNS0_8SockAddrEPj", h_sk_Accept, int s, void *a, unsigned *n) { (void)s; (void)a; (void)n; return sk_fail(); } -SKF("_ZN2nn6socket5CloseEi", h_sk_Close, int s) { return dm_sk_close(s); } -SKF("_ZN2nn6socket11GetPeerNameEiPNS0_8SockAddrEPj", h_sk_GetPeerName, int s, void *a, unsigned *n) { return dm_sk_name(s, a, n, 1); } -SKF("_ZN2nn6socket11GetSockNameEiPNS0_8SockAddrEPj", h_sk_GetSockName, int s, void *a, unsigned *n) { return dm_sk_name(s, a, n, 0); } -SKF("_ZN2nn6socket10GetSockOptEiNS0_5LevelENS0_6OptionEPvPj", h_sk_GetSockOpt, int s, int l, int o, void *v, unsigned *n) { return dm_sk_getopt(s, l, o, v, n); } -SKF("_ZN2nn6socket10SetSockOptEiNS0_5LevelENS0_6OptionEPKvj", h_sk_SetSockOpt, int s, int l, int o, const void *v, unsigned n) { return dm_sk_setopt(s, l, o, v, n); } -SKF("_ZN2nn6socket5FcntlEiNS0_12FcntlCommandEz", h_sk_Fcntl, int s, int c, int v) { return dm_sk_fcntl(s, c, v); } -// SDK 21 overloads Star Fox imports: plain sockaddr, the ShutdownMethod enum, Read / Write and a name lookup without options; SetAllocator keeps nothing, as no session is created -SKF("_ZN2nn6socket11GetPeerNameEiP8sockaddrPj", h_sk_GetPeerName21, int s, void *a, unsigned *n) { return dm_sk_name(s, a, n, 1); } -SKF("_ZN2nn6socket8ShutdownEiNS0_14ShutdownMethodE", h_sk_Shutdown21, int s, int how) { return dm_sk_shutdown(s, how); } -HLE_FORCE("_ZN2nn6socket4ReadEiPvm", "local UDP/EventFd (offline BSD service)", long, h_sk_Read, int s, void *b, unsigned long n) { return dm_sk_read(s, b, n); } -HLE_FORCE("_ZN2nn6socket5WriteEiPKvm", "local UDP/EventFd (offline BSD service)", long, h_sk_Write, int s, const void *b, unsigned long n) { return dm_sk_write(s, b, n); } -HLE_FORCE("_ZN2nn6socket16GetHostEntByNameEPKc", "name resolution (cut): NULL", void *, h_sk_GetHostEnt21, const char *n) { (void)n; t_skerr = SK_ENETDOWN; return NULL; } +SKF("_ZN2nn6socket6SocketENS0_6FamilyENS0_4TypeENS0_8ProtocolE", h_sk_Socket, int a, int b, int c) { return SKD(dm_net_socket(a, b, c), dm_sk_socket(a, b, c)); } +SKF("_ZN2nn6socket4BindEiPKNS0_8SockAddrEj", h_sk_Bind, int s, const void *a, unsigned n) { return SKD(dm_net_bind(s, a, n), dm_sk_bind(s, a, n)); } +SKW("_ZN2nn6socket7ConnectEiPKNS0_8SockAddrEj", h_sk_Connect, int s, const void *a, unsigned n) { return SKD(dm_net_connect(s, a, n), dm_sk_connect(s, a, n)); } +SKF("_ZN2nn6socket6ListenEii", h_sk_Listen, int s, int n) { return SKD(dm_net_listen(s, n), sk_fail()); } +SKW("_ZN2nn6socket6AcceptEiPNS0_8SockAddrEPj", h_sk_Accept, int s, void *a, unsigned *n) { return SKD(dm_net_accept(s, a, n), sk_fail()); } +SKW("_ZN2nn6socket5CloseEi", h_sk_Close, int s) { return SKD(dm_net_close(s), dm_sk_close(s)); } +SKF("_ZN2nn6socket11GetPeerNameEiPNS0_8SockAddrEPj", h_sk_GetPeerName, int s, void *a, unsigned *n) { return SKD(dm_net_name(s, a, n, 1), dm_sk_name(s, a, n, 1)); } +SKF("_ZN2nn6socket11GetSockNameEiPNS0_8SockAddrEPj", h_sk_GetSockName, int s, void *a, unsigned *n) { return SKD(dm_net_name(s, a, n, 0), dm_sk_name(s, a, n, 0)); } +SKF("_ZN2nn6socket10GetSockOptEiNS0_5LevelENS0_6OptionEPvPj", h_sk_GetSockOpt, int s, int l, int o, void *v, unsigned *n) { return SKD(dm_net_sockopt(s, l, o, v, n, 0), dm_sk_getopt(s, l, o, v, n)); } +SKF("_ZN2nn6socket10SetSockOptEiNS0_5LevelENS0_6OptionEPKvj", h_sk_SetSockOpt, int s, int l, int o, const void *v, unsigned n) { return SKD(dm_net_sockopt(s, l, o, (void *)v, &n, 1), dm_sk_setopt(s, l, o, v, n)); } +SKF("_ZN2nn6socket5FcntlEiNS0_12FcntlCommandEz", h_sk_Fcntl, int s, int c, int v) { return SKD(dm_net_fcntl(s, c, v), dm_sk_fcntl(s, c, v)); } +SKW("_ZN2nn6socket4PollEPNS0_6PollFdEmi", h_sk_Poll, void *f, unsigned long n, int t) { return dm_net_guest_errno(dm_sk_poll(f, n, t)); } +SKW("_ZN2nn6socket6SelectEiPNS0_5FdSetES2_S2_PNS0_7TimeValE", h_sk_Select, int n, void *r, void *w, void *e, void *t) { return dm_net_guest_errno(dm_sk_select(n, r, w, e, t)); } +// SDK 21 overloads Star Fox imports: plain sockaddr, the ShutdownMethod enum, Read / Write and a name lookup without options; SetAllocator keeps nothing, as no session is created. All go where their SockAddr forms do (the overloads only differ in the C type they spell) +SKF("_ZN2nn6socket11GetPeerNameEiP8sockaddrPj", h_sk_GetPeerName21, int s, void *a, unsigned *n) { return SKD(dm_net_name(s, a, n, 1), dm_sk_name(s, a, n, 1)); } +SKF("_ZN2nn6socket8ShutdownEiNS0_14ShutdownMethodE", h_sk_Shutdown21, int s, int how) { return SKD(dm_net_shutdown(s, how), dm_sk_shutdown(s, how)); } +HLE_FORCE_WAIT("_ZN2nn6socket4ReadEiPvm", "socket read: local UDP/EventFd offline, the transport in a network mode", long, h_sk_Read, int s, void *b, unsigned long n) { return SKD(dm_net_recv(s, b, n, 0, NULL, NULL), dm_sk_read(s, b, n)); } +HLE_FORCE_WAIT("_ZN2nn6socket5WriteEiPKvm", "socket write: local UDP/EventFd offline, the transport in a network mode", long, h_sk_Write, int s, const void *b, unsigned long n) { return SKD(dm_net_send(s, b, n, 0, NULL, 0), dm_sk_write(s, b, n)); } +HLE_FORCE_WAIT("_ZN2nn6socket16GetHostEntByNameEPKc", "name resolution, offline by default", void *, h_sk_GetHostEnt21, const char *n) { return dm_net_gethostbyname(n); } HLE_FORCE("_ZN2nn6socket12SetAllocatorEPNS_14MemoryResourceE", "socket library allocator; no session is created, ignored", void, h_sk_SetAlloc, void *r) { (void)r; } -SKF("_ZN2nn6socket4PollEPNS0_6PollFdEmi", h_sk_Poll, void *f, unsigned long n, int t) { return dm_sk_poll(f, n, t); } // The C library's poll (SDK 21's nnmusl, Star Fox): it needs the socket state of the initialization cut above and fails with EFAULT without it, which the game's loop takes as fatal, so it goes // to the host's Poll too -SKF("poll", h_libc_Poll, void *f, unsigned long n, int t) { return dm_sk_poll(f, n, t); } -SKF("_ZN2nn6socket6SelectEiPNS0_5FdSetES2_S2_PNS0_7TimeValE", h_sk_Select, int n, void *r, void *w, void *e, void *t) { return dm_sk_select(n, r, w, e, t); } -HLE_FORCE("_ZN2nn6socket7EventFdEmNS0_12EventFdFlagsE", "a descriptor of the bsd service that works offline: a host counter", int, h_sk_EventFd, unsigned long v, int f) { return efd_create(v, f); } -HLE_FORCE("_ZN2nn6socket11EventFdReadEiPm", "reads the host counter", int, h_sk_EventFdRead, int s, unsigned long *v) { uint64_t c = 0; int r = efd_read(s, &c); if (!r && v) *v = c; return r; } -HLE_FORCE("_ZN2nn6socket12EventFdWriteEim", "adds to the host counter and wakes its pollers", int, h_sk_EventFdWrite, int s, unsigned long v) { return efd_write(s, v); } -SKF("_ZN2nn6socket17ResolverGetOptionEPNS0_14ResolverOptionENS0_17ResolverOptionKeyE", h_sk_ResGet, void *o, int k) { (void)o; (void)k; return sk_fail(); } -SKF("_ZN2nn6socket17ResolverSetOptionERKNS0_14ResolverOptionE", h_sk_ResSet, const void *o) { (void)o; return sk_fail(); } -HLE_FORCE("_ZN2nn6socket4RecvEiPvmNS0_7MsgFlagE", "local UDP (offline BSD service)", long, h_sk_Recv, int s, void *b, unsigned long n, int f) { return dm_sk_recvfrom(s, b, n, f, NULL, NULL); } -HLE_FORCE("_ZN2nn6socket8RecvFromEiPvmNS0_7MsgFlagEPNS0_8SockAddrEPj", "local UDP (offline BSD service)", long, h_sk_RecvFrom, int s, void *b, unsigned long n, int f, void *a, unsigned *al) { return dm_sk_recvfrom(s, b, n, f, a, al); } -HLE_FORCE("_ZN2nn6socket4SendEiPKvmNS0_7MsgFlagE", "local UDP (offline BSD service)", long, h_sk_Send, int s, const void *b, unsigned long n, int f) { return dm_sk_sendto(s, b, n, f, NULL, 0); } -HLE_FORCE("_ZN2nn6socket11GetAddrInfoEPKcS2_PKNS0_8AddrInfoEPPS3_", "name resolution (cut): EAI_FAIL", int, h_sk_GetAddrInfo, const char *h, const char *s, const void *hint, void **res) { - (void)h; (void)s; (void)hint; if (res) *res = NULL; return 4; // EAI_FAIL +SKF("poll", h_libc_Poll, void *f, unsigned long n, int t) { return dm_net_guest_errno(dm_sk_poll(f, n, t)); } +// EventFd works in every mode. Offline it is the counter table above (a garbage collector of the game's own wakes its pollers, Ocarina of Time at startup). In a network mode it is a +// descriptor of the transport's socket table (dm_net_eventfd, hle_net_backend.c), numbered with the sockets, so the transport's Poll and Select see both: gRPC polls its sockets and +// its wakeup descriptor together (nn::npln). A blocking read waits as the host's other waits do: dm_guest_cond_wait_ns offline, the transport's bracketed host waits otherwise +HLE_FORCE("_ZN2nn6socket7EventFdEmNS0_12EventFdFlagsE", "a counter descriptor: the host's table offline, the transport's socket table in a network mode", int, h_sk_EventFd, unsigned long v, int f) { int rv = dm_net_enabled() ? dm_net_eventfd(v, f) : efd_create(v, f); return (int)dm_net_guest_errno(rv); } +HLE_FORCE("_ZN2nn6socket11EventFdReadEiPm", "reads the counter; blocks unless the descriptor never blocks", int, h_sk_EventFdRead, int s, unsigned long *v) { uint64_t c = 0; int rv = dm_net_enabled() ? dm_net_eventfd_read(s, &c) : efd_read(s, &c); if (!rv && v) *v = c; return (int)dm_net_guest_errno(rv); } +HLE_FORCE("_ZN2nn6socket12EventFdWriteEim", "adds to the counter and wakes its pollers", int, h_sk_EventFdWrite, int s, unsigned long v) { int rv = dm_net_enabled() ? dm_net_eventfd_write(s, v) : efd_write(s, v); return (int)dm_net_guest_errno(rv); } +// Resolver options (nn::socket::ResolverOption: its key is the first word). The host resolver has none to apply: setting one is accepted and not applied, and reading one fails, +// as there is no value to give. Each key is logged once, so a game that depends on one shows it +static int sk_res_option(const void *o, int key, int set) { + if (set) key = o ? *(const int32_t *)o : -1; + static _Atomic uint64_t seen[2]; uint64_t bit = key >= 0 && key < 64 ? 1ull << key : 1ull << 63; + if (!(atomic_fetch_or(&seen[set], bit) & bit)) LOG("%ssocket: resolver option %d %s", set ? "" : "[RED] ", key, set ? "set: accepted, the host resolver does not apply it" : "read: the host resolver has none, fails"); + if (set && dm_net_enabled() && o) return 0; + return sk_fail(); } -HLE_FORCE("_ZN2nn6socket12FreeAddrInfoEPNS0_8AddrInfoE", "pairs with GetAddrInfo (cut)", void, h_sk_FreeAddrInfo, void *ai) { (void)ai; } -HLE_FORCE("_ZN2nn6socket16GetHostEntByNameEPKcPKNS0_14ResolverOptionEm", "name resolution (cut): NULL", void *, h_sk_GetHostEnt, const char *n, const void *o, unsigned long c) { (void)n; (void)o; (void)c; t_skerr = SK_ENETDOWN; return NULL; } -HLE_FORCE("_ZN2nn6socket12GetLastErrorEv", "socket error code kept by the host", int, h_sk_GetLastError, void) { return t_skerr; } +SKF("_ZN2nn6socket17ResolverGetOptionEPNS0_14ResolverOptionENS0_17ResolverOptionKeyE", h_sk_ResGet, void *o, int k) { (void)o; return sk_res_option(NULL, k, 0); } +SKF("_ZN2nn6socket17ResolverSetOptionERKNS0_14ResolverOptionE", h_sk_ResSet, const void *o) { return sk_res_option(o, 0, 1); } +HLE_FORCE_WAIT("_ZN2nn6socket4RecvEiPvmNS0_7MsgFlagE", "socket call: local UDP offline, the transport in a network mode", long, h_sk_Recv, int s, void *b, unsigned long n, int f) { return SKD(dm_net_recv(s, b, n, f, NULL, NULL), dm_sk_recvfrom(s, b, n, f, NULL, NULL)); } +HLE_FORCE_WAIT("_ZN2nn6socket8RecvFromEiPvmNS0_7MsgFlagEPNS0_8SockAddrEPj", "socket call: local UDP offline, the transport in a network mode", long, h_sk_RecvFrom, int s, void *b, unsigned long n, int f, void *a, unsigned *al) { return SKD(dm_net_recv(s, b, n, f, a, al), dm_sk_recvfrom(s, b, n, f, a, al)); } +HLE_FORCE_WAIT("_ZN2nn6socket4SendEiPKvmNS0_7MsgFlagE", "socket call: local UDP offline, the transport in a network mode", long, h_sk_Send, int s, const void *b, unsigned long n, int f) { return SKD(dm_net_send(s, b, n, f, NULL, 0), dm_sk_sendto(s, b, n, f, NULL, 0)); } +HLE_FORCE_WAIT("_ZN2nn6socket11GetAddrInfoEPKcS2_PKNS0_8AddrInfoEPPS3_", "name resolution (cut): EAI_FAIL", int, h_sk_GetAddrInfo, const char *h, const char *s, const void *hint, void **res) { + return dm_net_getaddrinfo(h, s, hint, res); +} +HLE_FORCE("_ZN2nn6socket12FreeAddrInfoEPNS0_8AddrInfoE", "release only resolver allocations owned by the host", void, h_sk_FreeAddrInfo, void *ai) { dm_net_freeaddrinfo(ai); } +HLE_FORCE_WAIT("_ZN2nn6socket16GetHostEntByNameEPKcPKNS0_14ResolverOptionEm", "name resolution, offline by default", void *, h_sk_GetHostEnt, const char *n, const void *o, unsigned long c) { (void)o; (void)c; return dm_net_gethostbyname(n); } +HLE_FORCE("_ZN2nn6socket12GetLastErrorEv", "socket error code kept by the host", int, h_sk_GetLastError, void) { return dm_net_errno(); } // C interface -SKF("nnsocketSocket", h_nsk_Socket, int a, int b, int c) { return dm_sk_socket(a, b, c); } -SKF("nnsocketBind", h_nsk_Bind, int s, const void *a, unsigned n) { return dm_sk_bind(s, a, n); } -SKF("nnsocketConnect", h_nsk_Connect, int s, const void *a, unsigned n) { return dm_sk_connect(s, a, n); } -SKF("nnsocketClose", h_nsk_Close, int s) { return dm_sk_close(s); } -SKF("nnsocketGetPeerName", h_nsk_GetPeerName, int s, void *a, unsigned *n) { return dm_sk_name(s, a, n, 1); } -SKF("nnsocketGetSockName", h_nsk_GetSockName, int s, void *a, unsigned *n) { return dm_sk_name(s, a, n, 0); } -SKF("nnsocketGetSockOpt", h_nsk_GetSockOpt, int s, int l, int o, void *v, unsigned *n) { return dm_sk_getopt(s, l, o, v, n); } -SKF("nnsocketSetSockOpt", h_nsk_SetSockOpt, int s, int l, int o, const void *v, unsigned n) { return dm_sk_setopt(s, l, o, v, n); } -SKF("nnsocketFcntl", h_nsk_Fcntl, int s, int c, int v) { return dm_sk_fcntl(s, c, v); } -SKF("nnsocketPoll", h_nsk_Poll, void *f, unsigned long n, int t) { return dm_sk_poll(f, n, t); } -SKF("nnsocketResolverGetOption", h_nsk_ResGet, void *o, int k) { (void)o; (void)k; return sk_fail(); } -SKF("nnsocketResolverSetOption", h_nsk_ResSet, const void *o) { (void)o; return sk_fail(); } -HLE_FORCE("nnsocketRecv", "local UDP (offline BSD service)", long, h_nsk_Recv, int s, void *b, unsigned long n, int f) { return dm_sk_recvfrom(s, b, n, f, NULL, NULL); } -HLE_FORCE("nnsocketSend", "local UDP (offline BSD service)", long, h_nsk_Send, int s, const void *b, unsigned long n, int f) { return dm_sk_sendto(s, b, n, f, NULL, 0); } -HLE_FORCE("nnsocketSendTo", "local UDP (offline BSD service)", long, h_nsk_SendTo, int s, const void *b, unsigned long n, int f, const void *a, unsigned al) { return dm_sk_sendto(s, b, n, f, a, al); } -HLE_FORCE("nnsocketRecvFrom", "local UDP (offline BSD service)", long, h_nsk_RecvFrom, int s, void *b, unsigned long n, int f, void *a, unsigned *al) { return dm_sk_recvfrom(s, b, n, f, a, al); } -HLE_FORCE("nnsocketRead", "local UDP/EventFd (offline BSD service)", long, h_nsk_Read, int s, void *b, unsigned long n) { return dm_sk_read(s, b, n); } -HLE_FORCE("nnsocketWrite", "local UDP/EventFd (offline BSD service)", long, h_nsk_Write, int s, const void *b, unsigned long n) { return dm_sk_write(s, b, n); } -HLE_FORCE("nnsocketGetHostByNameWithOptions", "name resolution (cut): NULL", void *, h_nsk_GetHost, const char *n, const void *o, unsigned long c) { (void)n; (void)o; (void)c; t_skerr = SK_ENETDOWN; return NULL; } -HLE_FORCE("nnsocketGetLastErrno", "socket error code kept by the host", int, h_nsk_GetErrno, void) { return t_skerr; } -HLE_FORCE("nnsocketSetLastErrno", "socket error code kept by the host", void, h_nsk_SetErrno, int e) { t_skerr = e; } - -// ---------- ssl: offline, Initialize and a context's Create / Destroy succeed, everything else that contacts the service fails ---------- -// A context is a session of the local ssl service, so on Horizon Create works with no network and only a connection needs one; DRAGON QUEST BUILDERS 2 ends its startup when Create fails (main+0x861260). -// Not cut: Context / Connection construction and destruction, Context::GetContextId (only read and write game objects). -#define SSF(m, cname, ...) HLE_FORCE(m, "ssl service (cut): fails", Result, cname, __VA_ARGS__) -HLE_FORCE("_ZN2nn3ssl10InitializeEv", "same as nnsslInitialize: succeeds, creates no session (cut)", Result, h_ssl_InitCpp, void) { return RES_OK; } -HLE_FORCE("_ZN2nn3ssl8FinalizeEv", "pairs with Initialize (cut)", Result, h_ssl_FinCpp, void) { return RES_OK; } -HLE_FORCE("_ZN2nn3ssl7Context6CreateENS1_10SslVersionE", "a session of the local ssl service: succeeds offline, connects to nothing (cut)", Result, h_ssl_CtxCreate, void *self, int v) { (void)self; (void)v; return RES_OK; } -HLE_FORCE("_ZN2nn3ssl7Context7DestroyEv", "pairs with Create (cut)", Result, h_ssl_CtxDestroy, void *self) { (void)self; return RES_OK; } -SSF("_ZN2nn3ssl7Context19RegisterInternalPkiEPmNS1_11InternalPkiE", h_ssl_CtxRegPki, void *self, uint64_t *id, int p) { (void)self; (void)id; (void)p; return RES_FAIL; } -SSF("_ZN2nn3ssl7Context9RemovePkiEm", h_ssl_CtxRemovePki, void *self, uint64_t id) { (void)self; (void)id; return RES_FAIL; } -SSF("_ZN2nn3ssl14BuiltInManager28GetBuiltInCertificateBufSizeEPjPNS0_15CaCertificateIdEj", h_ssl_BiBufSize, uint32_t *o, void *ids, unsigned n) { (void)ids; (void)n; if (o) *o = 0; return RES_FAIL; } -SSF("_ZN2nn3ssl14BuiltInManager22GetBuiltInCertificatesEPPNS1_22BuiltInCertificateInfoEPhjPNS0_15CaCertificateIdEj", h_ssl_BiCerts, void **o, uint8_t *b, unsigned bs, void *ids, unsigned n) { (void)o; (void)b; (void)bs; (void)ids; (void)n; return RES_FAIL; } -SSF("_ZN2nn3ssl10Connection6CreateEPNS0_7ContextE", h_ssl_CnCreate, void *self, void *ctx) { (void)self; (void)ctx; return RES_FAIL; } -SSF("_ZN2nn3ssl10Connection7DestroyEv", h_ssl_CnDestroy, void *self) { (void)self; return RES_FAIL; } -SSF("_ZN2nn3ssl10Connection11DoHandshakeEv", h_ssl_CnHandshake, void *self) { (void)self; return RES_FAIL; } -SSF("_ZN2nn3ssl10Connection11SetHostNameEPKcj", h_ssl_CnHost, void *self, const char *h, unsigned n) { (void)self; (void)h; (void)n; return RES_FAIL; } -SSF("_ZN2nn3ssl10Connection9SetIoModeENS1_6IoModeE", h_ssl_CnIoMode, void *self, int m) { (void)self; (void)m; return RES_FAIL; } -SSF("_ZN2nn3ssl10Connection19SetSessionCacheModeENS1_16SessionCacheModeE", h_ssl_CnCache, void *self, int m) { (void)self; (void)m; return RES_FAIL; } -SSF("_ZN2nn3ssl10Connection19SetSocketDescriptorEi", h_ssl_CnSock, void *self, int s) { (void)self; (void)s; return RES_FAIL; } -SSF("_ZN2nn3ssl10Connection12GetLastErrorEPNS_6ResultE", h_ssl_CnLastErr, void *self, uint32_t *r) { (void)self; if (r) *r = RES_FAIL; return RES_FAIL; } -SSF("_ZN2nn3ssl10Connection18GetVerifyCertErrorEPNS_6ResultE", h_ssl_CnVerifyErr, void *self, uint32_t *r) { (void)self; if (r) *r = RES_FAIL; return RES_FAIL; } -SSF("_ZN2nn3ssl10Connection4PeekEPcPij", h_ssl_CnPeek, void *self, char *b, int *o, unsigned n) { (void)self; (void)b; (void)n; if (o) *o = 0; return RES_FAIL; } -SSF("_ZN2nn3ssl10Connection4PollEPNS1_9PollEventES3_j", h_ssl_CnPoll, void *self, void *o, void *i, unsigned t) { (void)self; (void)o; (void)i; (void)t; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ssl10Connection4ReadEPcj", "ssl service (cut): read returns -1", int, h_ssl_CnRead, void *self, char *b, unsigned n) { (void)self; (void)b; (void)n; return -1; } -HLE_FORCE("_ZN2nn3ssl10Connection5WriteEPKcj", "ssl service (cut): write returns -1", int, h_ssl_CnWrite, void *self, const char *b, unsigned n) { (void)self; (void)b; (void)n; return -1; } -// C interface: all return nnResult -#define SSC(m, cname) HLE_FORCE(m, "ssl service (cut): fails", Result, cname, void) { return RES_FAIL; } -SSC("nnsslConnectionCreate", h_nssl_Create) SSC("nnsslConnectionDestroy", h_nssl_Destroy) -SSC("nnsslConnectionDoHandshakeWithCertBuffer", h_nssl_Handshake) SSC("nnsslConnectionGetConnectionId", h_nssl_GetId) -SSC("nnsslConnectionGetNextAlpnProto", h_nssl_GetAlpn) SSC("nnsslConnectionGetVerifyCertError", h_nssl_VerifyErr) -SSC("nnsslConnectionPeek", h_nssl_Peek) SSC("nnsslConnectionPending", h_nssl_Pending) SSC("nnsslConnectionRead", h_nssl_Read) -SSC("nnsslConnectionSetHostName", h_nssl_SetHost) SSC("nnsslConnectionSetIoMode", h_nssl_SetIo) -SSC("nnsslConnectionSetNextAlpnProto", h_nssl_SetAlpn) SSC("nnsslConnectionSetOption", h_nssl_SetOpt) -SSC("nnsslConnectionSetSessionCacheMode", h_nssl_SetCache) SSC("nnsslConnectionSetSocketDescriptor", h_nssl_SetSock) -SSC("nnsslConnectionSetVerifyOption", h_nssl_SetVerify) SSC("nnsslConnectionWrite", h_nssl_Write) -SSC("nnsslContextDestroy", h_nssl_CtxDestroy) SSC("nnsslContextGetContextId", h_nssl_CtxGetId) +SKF("nnsocketSocket", h_nsk_Socket, int a, int b, int c) { return SKD(dm_net_socket(a, b, c), dm_sk_socket(a, b, c)); } +SKF("nnsocketBind", h_nsk_Bind, int s, const void *a, unsigned n) { return SKD(dm_net_bind(s, a, n), dm_sk_bind(s, a, n)); } +SKW("nnsocketConnect", h_nsk_Connect, int s, const void *a, unsigned n) { return SKD(dm_net_connect(s, a, n), dm_sk_connect(s, a, n)); } +SKW("nnsocketClose", h_nsk_Close, int s) { return SKD(dm_net_close(s), dm_sk_close(s)); } +SKF("nnsocketGetPeerName", h_nsk_GetPeerName, int s, void *a, unsigned *n) { return SKD(dm_net_name(s, a, n, 1), dm_sk_name(s, a, n, 1)); } +SKF("nnsocketGetSockName", h_nsk_GetSockName, int s, void *a, unsigned *n) { return SKD(dm_net_name(s, a, n, 0), dm_sk_name(s, a, n, 0)); } +SKF("nnsocketGetSockOpt", h_nsk_GetSockOpt, int s, int l, int o, void *v, unsigned *n) { return SKD(dm_net_sockopt(s, l, o, v, n, 0), dm_sk_getopt(s, l, o, v, n)); } +SKF("nnsocketSetSockOpt", h_nsk_SetSockOpt, int s, int l, int o, const void *v, unsigned n) { return SKD(dm_net_sockopt(s, l, o, (void *)v, &n, 1), dm_sk_setopt(s, l, o, v, n)); } +SKF("nnsocketFcntl", h_nsk_Fcntl, int s, int c, int v) { return SKD(dm_net_fcntl(s, c, v), dm_sk_fcntl(s, c, v)); } +SKW("nnsocketPoll", h_nsk_Poll, void *f, unsigned long n, int t) { return dm_net_guest_errno(dm_sk_poll(f, n, t)); } +HLE_FORCE_WAIT("nnsocketGetHostByNameCancel", "real IPv4 resolution with an independent cancellation ID", void *, h_nsk_GetHostCancel, const char *name, uint32_t id) { return dm_net_gethostbyname_cancel(name, id); } +HLE_FORCE_WAIT("_ZN2nn6socket13GetHostByNameEPKci", "real IPv4 resolution with an independent cancellation ID", void *, h_sk_GetHostCancel, const char *name, uint32_t id) { return dm_net_gethostbyname_cancel(name, id); } +HLE_FORCE("nnsocketRequestCancelHandle", "allocate a nonzero resolver cancellation identity, not a socket", uint32_t, h_nsk_RequestCancel, void) { return dm_net_request_cancel_handle(); } +HLE_FORCE("_ZN2nn6socket19RequestCancelHandleEv", "allocate a nonzero resolver cancellation identity, not a socket", uint32_t, h_sk_RequestCancel, void) { return dm_net_request_cancel_handle(); } +SKW("nnsocketCancel", h_nsk_Cancel, uint32_t id) { return dm_net_guest_errno(dm_net_cancel(id)); } +SKW("_ZN2nn6socket6CancelEi", h_sk_Cancel, uint32_t id) { return dm_net_guest_errno(dm_net_cancel(id)); } +SKF("nnsocketResolverGetOption", h_nsk_ResGet, void *o, int k) { (void)o; return sk_res_option(NULL, k, 0); } +SKF("nnsocketResolverSetOption", h_nsk_ResSet, const void *o) { return sk_res_option(o, 0, 1); } +HLE_FORCE_WAIT("nnsocketRecv", "socket receive: local UDP offline, the transport in a network mode", long, h_nsk_Recv, int s, void *b, unsigned long n, int f) { return SKD(dm_net_recv(s, b, n, f, NULL, NULL), dm_sk_recvfrom(s, b, n, f, NULL, NULL)); } +HLE_FORCE_WAIT("nnsocketSend", "socket send: local UDP offline, the transport in a network mode", long, h_nsk_Send, int s, const void *b, unsigned long n, int f) { return SKD(dm_net_send(s, b, n, f, NULL, 0), dm_sk_sendto(s, b, n, f, NULL, 0)); } +HLE_FORCE_WAIT("nnsocketSendTo", "socket send: local UDP offline, the transport in a network mode", long, h_nsk_SendTo, int s, const void *b, unsigned long n, int f, const void *a, unsigned al) { return SKD(dm_net_send(s, b, n, f, a, al), dm_sk_sendto(s, b, n, f, a, al)); } +HLE_FORCE_WAIT("nnsocketRecvFrom", "socket receive: local UDP offline, the transport in a network mode", long, h_nsk_RecvFrom, int s, void *b, unsigned long n, int f, void *a, unsigned *al) { return SKD(dm_net_recv(s, b, n, f, a, al), dm_sk_recvfrom(s, b, n, f, a, al)); } +HLE_FORCE_WAIT("nnsocketRead", "socket read: local UDP/EventFd offline, the transport in a network mode", long, h_nsk_Read, int s, void *b, unsigned long n) { return SKD(dm_net_recv(s, b, n, 0, NULL, NULL), dm_sk_read(s, b, n)); } +HLE_FORCE_WAIT("nnsocketWrite", "socket write: local UDP/EventFd offline, the transport in a network mode", long, h_nsk_Write, int s, const void *b, unsigned long n) { return SKD(dm_net_send(s, b, n, 0, NULL, 0), dm_sk_write(s, b, n)); } +HLE_FORCE_WAIT("nnsocketGetHostByNameWithOptions", "name resolution, offline by default", void *, h_nsk_GetHost, const char *n, const void *o, unsigned long c) { (void)o; (void)c; return dm_net_gethostbyname(n); } +HLE_FORCE("nnsocketGetLastErrno", "the game's errno, as nn::socket::GetLastErrno reads it", int, h_nsk_GetErrno, void) { return dm_net_guest_errno_get(); } +HLE_FORCE("nnsocketSetLastErrno", "sets the host's copy and the game's errno", void, h_nsk_SetErrno, int e) { dm_net_set_errno(e); dm_net_guest_errno(-1); } +// ---------- ssl: hle_ssl.c (the client TLS service, offline and online) ---------- diff --git a/dm/host/hle_net.h b/dm/host/hle_net.h index 2a29d3980d..34ac838729 100644 --- a/dm/host/hle_net.h +++ b/dm/host/hle_net.h @@ -17,3 +17,4 @@ long dm_sk_write(int fd, const void *data, unsigned long size); int dm_sk_poll(void *fds, uint64_t count, int milliseconds); int dm_sk_select(int nfds, uint64_t *read, uint64_t *write, uint64_t *except, const int64_t *timeout); int dm_sk_errno(void); +int dm_sk_unavailable(void); // remote networking offline: -1 with ENETDOWN (an explicit network mode answers through the transport instead) diff --git a/dm/host/hle_net_backend.c b/dm/host/hle_net_backend.c new file mode 100644 index 0000000000..4776e88959 --- /dev/null +++ b/dm/host/hle_net_backend.c @@ -0,0 +1,1138 @@ +// Opt-in Apple IPv4 transport. The default offline hooks retain their previous answers. +// ABI references: Atmosphere-NX socket_types.hpp / socket_errno.hpp; switchbrew/libnx socket.c. +// Horizon uses BSD sockaddr (length + u8 family), Linux errno numbers, O_NONBLOCK=0x800, +// Modern nn::socket::AddrInfo has addr before canonname; SDK 4's plain addrinfo has +// the opposite order (verified in MK8 3.0.5's DNSSerializer at sdk+0xafa94). Never cast guest structs to Darwin structs. +#include "net_socket.h" +#include "nsd.h" +#include "discovery_protocol.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if TARGET_OS_OSX +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void dm_guest_write_prepare(void *addr, size_t len); +void dm_guest_host_wait_begin(void); +void dm_guest_host_wait_end(void); + +enum { NET_MAX = 1024, NX_NONBLOCK = 0x800, NET_SLICE_MS = 100 }; +typedef struct { uint8_t len, family; uint16_t port; uint32_t address; uint8_t zero[8]; } nx_addr; +typedef struct { int64_t sec, usec; } nx_timeval; +_Static_assert(sizeof(nx_addr) == 16, "Horizon sockaddr_in"); +_Static_assert(sizeof(dm_net_addrinfo) == 48 && offsetof(dm_net_addrinfo, addr) == 24, "Horizon addrinfo"); +_Static_assert(sizeof(dm_net_addrinfo_legacy) == 48 && offsetof(dm_net_addrinfo_legacy, addr) == 32, "SDK 4 addrinfo"); +_Static_assert(sizeof(dm_net_pollfd) == 8, "Horizon pollfd"); +// type is the socket's (1 stream, 2 datagram) or NET_EVENT for an event descriptor (dm_net_eventfd below): native is then the read end of a local socket pair, peer its +// write end, and count / efd_flags the counter and its Horizon flags +enum { NET_EVENT = 0x10 }; +typedef struct { int native, used, nonblock, type; uint64_t generation; int64_t send_ms, recv_ms; int peer; uint64_t count; int efd_flags; } net_slot; +typedef struct { int fd, guest, nonblock, type; uint64_t generation; int64_t send_ms, recv_ms; } net_ref; +static net_slot g_sockets[NET_MAX]; +static _Atomic(dm_net_dns_provider) g_dns_provider; +void dm_net_set_dns_provider(dm_net_dns_provider provider) { atomic_store(&g_dns_provider, provider); } +static pthread_mutex_t g_net_lock = PTHREAD_MUTEX_INITIALIZER; +static _Atomic int g_net_multicast_allowed = TARGET_OS_OSX; +static _Atomic uint32_t g_net_broadcast; +static _Atomic int g_net_broadcast_known; +typedef struct { uint32_t address, mask, gateway; unsigned index, flags; int local_link; } net_interface; +static int net_interface_get(net_interface *out); +#ifdef DM_NET_TEST +static net_interface g_test_interface; +static int g_test_interface_set; +void dm_net_test_set_interface(const dm_net_test_interface *p) { + g_test_interface_set = p != NULL; + if (p) g_test_interface = (net_interface){p->address, p->mask, 0, p->index, p->flags, p->local_link}; + atomic_store(&g_net_broadcast_known, 0); +} +#endif +static void net_resolver_finalize(void); +static __thread int t_net_errno = 100; // Horizon's BSD service and nn::socket expose Linux errno numbers (not Darwin's). + +dm_net_mode_t dm_net_mode(void) { +#if TARGET_OS_OSX || TARGET_OS_IOS + const char *s = getenv("DM_NETWORK"); + if (s && !strcmp(s, "lan")) return DM_NET_LAN; + if (s && !strcmp(s, "ldn")) return DM_NET_LDN; + if (s && !strcmp(s, "nextendo")) return DM_NET_NEXTENDO; + if (s && !strcmp(s, "auto")) return DM_NET_AUTO; + return DM_NET_OFFLINE; +#else + return DM_NET_OFFLINE; +#endif +} +int dm_net_enabled(void) { return dm_net_mode() != DM_NET_OFFLINE; } +void dm_net_set_multicast_allowed(int allowed) { atomic_store(&g_net_multicast_allowed, !!allowed); } +int dm_net_multicast_allowed(void) { return atomic_load(&g_net_multicast_allowed); } +static int net_discovery_unicast_plan(dm_net_discovery_plan *p) { + net_interface adapter; + if (net_interface_get(&adapter) || !adapter.index || !(adapter.flags & IFF_UP) || + !(adapter.flags & IFF_BROADCAST) || (adapter.flags & (IFF_LOOPBACK | IFF_POINTOPOINT))) { + dm_net_set_errno(99); return -1; + } +#if TARGET_OS_IOS + if (!adapter.local_link) { dm_net_set_errno(99); return -1; } +#endif + if (dm_net_discovery_subnet(p, adapter.address, adapter.mask)) { dm_net_set_errno(95); return -1; } + return 0; +} +int dm_net_discovery_prepare(uint32_t destination, dm_net_discovery_plan *p) { + if (!p) { dm_net_set_errno(14); return -1; } + memset(p, 0, sizeof *p); + const char *peer = getenv("DM_NET_DISCOVERY_PEER"); + if (peer && *peer) { + struct in_addr address; + if (inet_pton(AF_INET, peer, &address) != 1 || !address.s_addr || + (ntohl(address.s_addr) & 0xf0000000u) == 0xe0000000u || + ntohl(address.s_addr) >= 0xf0000000u) { dm_net_set_errno(22); return -1; } + p->target = address.s_addr; p->count = 1; return 0; + } + if (dm_net_multicast_allowed()) { p->target = destination; p->count = 1; return 0; } + return net_discovery_unicast_plan(p); +} +int dm_net_discovery_target(uint32_t destination, uint32_t *target) { + if (!target) { dm_net_set_errno(14); return -1; } + dm_net_discovery_plan p; + if (dm_net_discovery_prepare(destination, &p)) return -1; + // A connected UDP endpoint cannot represent multiple peers. SendTo and LDN + // use the full plan; never silently connect to the first scanned address. + if (p.automatic) { dm_net_set_errno(95); return -1; } + *target = p.target; return 0; +} +// Only discovery destinations may be redirected. Ordinary peer traffic keeps its +// original address, including after a lobby supplies the actual peer endpoint. +static int net_is_discovery(uint32_t address, int type) { + if (type != 2) return 0; + uint32_t host = ntohl(address); + int discovery = host == UINT32_MAX || (host & 0xf0000000u) == 0xe0000000u; + if (!discovery) { + if (!atomic_load(&g_net_broadcast_known)) { + dm_net_ipconfig(NULL, NULL, NULL, NULL, NULL); + atomic_store(&g_net_broadcast_known, 1); + } + uint32_t broadcast = atomic_load(&g_net_broadcast); + discovery = broadcast && address == broadcast; + } + return discovery; +} +int dm_net_discovery_supplement(uint32_t destination,dm_net_discovery_plan *plan) { + if(!plan)return 0;memset(plan,0,sizeof *plan); + const char *peer=getenv("DM_NET_DISCOVERY_PEER");dm_net_mode_t mode=dm_net_mode(); + if(!dm_net_multicast_allowed()||(peer&&*peer)||(mode!=DM_NET_LAN&&mode!=DM_NET_LDN&&mode!=DM_NET_AUTO)||!net_is_discovery(destination,2))return 0; + int saved=t_net_errno,result=!net_discovery_unicast_plan(plan);t_net_errno=saved;return result; +} +int dm_net_errno(void) { return t_net_errno; } +void dm_net_set_errno(int e) { t_net_errno = e; } +static int net_error(int e) { t_net_errno = e; return -1; } +static int net_gate(void) { return dm_net_enabled() ? 1 : (net_error(100), 0); } +static int net_errno(int e) { + switch (e) { + case 0: return 0; + case EPERM: return 1; case ENOENT: return 2; case EINTR: return 4; case EIO: return 5; + case EBADF: return 9; case EAGAIN: return 11; case ENOMEM: return 12; case EACCES: return 13; + case EFAULT: return 14; case EBUSY: return 16; case EEXIST: return 17; case ENODEV: return 19; + case EINVAL: return 22; case ENFILE: return 23; case EMFILE: return 24; case EPIPE: return 32; + case ENAMETOOLONG: return 36; case ENOSYS: return 38; case EOVERFLOW: return 75; + case ENOTSOCK: return 88; case EDESTADDRREQ: return 89; case EMSGSIZE: return 90; + case EPROTOTYPE: return 91; case ENOPROTOOPT: return 92; case EPROTONOSUPPORT: return 93; + case ESOCKTNOSUPPORT: return 94; case EOPNOTSUPP: return 95; case EPFNOSUPPORT: return 96; + case EAFNOSUPPORT: return 97; case EADDRINUSE: return 98; case EADDRNOTAVAIL: return 99; + case ENETDOWN: return 100; case ENETUNREACH: return 101; case ENETRESET: return 102; + case ECONNABORTED: return 103; case ECONNRESET: return 104; case ENOBUFS: return 105; + case EISCONN: return 106; case ENOTCONN: return 107; case ESHUTDOWN: return 108; + case ETIMEDOUT: return 110; case ECONNREFUSED: return 111; case EHOSTDOWN: return 112; + case EHOSTUNREACH: return 113; case EALREADY: return 114; case EINPROGRESS: return 115; + case ECANCELED: return 125; default: return 5; + } +} +static int net_host_result(int result, int err) { return result < 0 ? net_error(net_errno(err)) : result; } +static uint64_t net_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000; } +static void net_trace(const char *op, int fd, long result) { + const char *s = getenv("DM_NET_TRACE"); + if (s && atoi(s)) fprintf(stderr, "net: %s guest_fd=%d result=%ld errno=%d\n", op, fd, result, result < 0 ? t_net_errno : 0); +} +// The UDP watch. A game's own peer-to-peer traffic (Mario Kart 8 Deluxe's races, through Pia) ends without any host error when datagrams stop +// coming: the game times its peers out and shows its communication error, and the log said nothing. Each UDP socket counts what it sends and +// receives; one that has received and then gets nothing for NET_UDP_QUIET_MS is logged once, with its counts, and again when datagrams come back, +// so a log shows which side went quiet. A send or receive error is logged the first time each errno appears. No addresses: the peers are other players +enum { NET_UDP_QUIET_MS = 2000 }; +typedef struct { uint64_t generation, in, out, last_in_ms, quiet_since_ms; int quiet; } net_udp_watch; +static net_udp_watch g_udp_watch[NET_MAX]; +static pthread_mutex_t g_udp_watch_lock = PTHREAD_MUTEX_INITIALIZER; +static _Atomic uint64_t g_udp_errors_told[2]; // bit n: errno n already logged (receive, send) +static net_udp_watch *net_udp_entry(const net_ref *r) { // with g_udp_watch_lock held; a reused slot starts again + net_udp_watch *w = &g_udp_watch[r->guest]; + if (w->generation != r->generation) { memset(w, 0, sizeof *w); w->generation = r->generation; } + return w; +} +static void net_udp_note(const net_ref *r, int received, int sent) { + if (r->type != 2 || r->guest < 0 || r->guest >= NET_MAX) return; + uint64_t now = net_ms(); char line[160]; line[0] = 0; + pthread_mutex_lock(&g_udp_watch_lock); + net_udp_watch *w = net_udp_entry(r); + w->in += (uint64_t)received; w->out += (uint64_t)sent; + if (received) { + if (w->quiet) snprintf(line, sizeof line, "net: UDP socket %d: datagrams again after %.1f s without (in %llu, out %llu)", r->guest, + (now - w->quiet_since_ms) / 1000.0, (unsigned long long)w->in, (unsigned long long)w->out); + w->quiet = 0; w->last_in_ms = now; + } else if (w->in && !w->quiet && now - w->last_in_ms >= NET_UDP_QUIET_MS) { + w->quiet = 1; w->quiet_since_ms = w->last_in_ms; + snprintf(line, sizeof line, "[RED] net: UDP socket %d: no datagram for %d s after %llu in (%llu sent so far)", r->guest, + NET_UDP_QUIET_MS / 1000, (unsigned long long)w->in, (unsigned long long)w->out); + } + pthread_mutex_unlock(&g_udp_watch_lock); + if (line[0]) fprintf(stderr, "%s\n", line); +} +static void net_udp_error(const net_ref *r, int sending, int err) { + if (r->type != 2 || err <= 0 || err >= 64) return; + uint64_t bit = 1ull << err; + if (!(atomic_fetch_or(&g_udp_errors_told[sending], bit) & bit)) + fprintf(stderr, "[RED] net: UDP %s failed on the host: %s (errno %d; logged once)\n", sending ? "send" : "receive", strerror(err), err); +} +// Each operation borrows a duplicate while under the lock. Close removes the guest slot first; +// a generation check in every bounded wait prevents an old waiter touching a subsequently reused slot. +// Poll and Select take any descriptor (net_borrow_any); every socket operation takes only a socket, and an event descriptor fails it with ENOTSOCK (net_borrow) +static int net_borrow_kind(int guest, net_ref *r, int any) { + if (!net_gate()) return -1; + pthread_mutex_lock(&g_net_lock); + if (guest < 0 || guest >= NET_MAX || !g_sockets[guest].used) { pthread_mutex_unlock(&g_net_lock); return net_error(9); } + if (!any && g_sockets[guest].type == NET_EVENT) { pthread_mutex_unlock(&g_net_lock); return net_error(88); } + net_slot s = g_sockets[guest]; + int fd = fcntl(s.native, F_DUPFD_CLOEXEC, 0), err = errno; + pthread_mutex_unlock(&g_net_lock); + if (fd < 0) return net_error(net_errno(err)); + *r = (net_ref){fd, guest, s.nonblock, s.type, s.generation, s.send_ms, s.recv_ms}; return 0; +} +static int net_borrow(int guest, net_ref *r) { return net_borrow_kind(guest, r, 0); } +static int net_borrow_any(int guest, net_ref *r) { return net_borrow_kind(guest, r, 1); } +int dm_net_dup_native(int guest) { + return dm_net_dup_native_generation(guest, NULL); +} +int dm_net_dup_native_generation(int guest, uint64_t *generation) { + net_ref r; + if (net_borrow(guest, &r)) return -1; + if (generation) *generation = r.generation; + return r.fd; +} +static int net_live(const net_ref *r) { + pthread_mutex_lock(&g_net_lock); + int live = g_sockets[r->guest].used && g_sockets[r->guest].generation == r->generation; + pthread_mutex_unlock(&g_net_lock); return live; +} +#include "net_discovery_queue.inc" +static int net_register(int fd, int type, int nonblock) { + if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0 || fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { int e = errno; close(fd); return net_error(net_errno(e)); } + int one = 1; + if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof one) < 0) { int e = errno; close(fd); return net_error(net_errno(e)); } + pthread_mutex_lock(&g_net_lock); + int i; for (i = 0; i < NET_MAX && g_sockets[i].used; i++) {} + if (i < NET_MAX) { uint64_t gen = g_sockets[i].generation + 1; g_sockets[i] = (net_slot){.native = fd, .used = 1, .nonblock = nonblock, .type = type, .generation = gen, .send_ms = -1, .recv_ms = -1, .peer = -1}; } + pthread_mutex_unlock(&g_net_lock); + if (i == NET_MAX) { close(fd); return net_error(24); } + return i; +} +static int net_addr_in(const void *p, unsigned n, struct sockaddr_in *out) { + if (!p) return net_error(14); + if (n < sizeof(nx_addr)) return net_error(22); + nx_addr a; memcpy(&a, p, sizeof a); + if (a.family != 2) return net_error(97); + if (a.len && a.len != sizeof a) return net_error(22); + memset(out, 0, sizeof *out); out->sin_len = sizeof *out; out->sin_family = AF_INET; + out->sin_port = a.port; out->sin_addr.s_addr = a.address; return 0; +} +static int net_addr_output_ok(void *p, unsigned *n) { return p && !n ? net_error(14) : 0; } +static void net_addr_out(void *p, unsigned *n, const struct sockaddr_in *in) { + if (!p || !n) return; + nx_addr a = {.len = sizeof a, .family = 2, .port = in->sin_port, .address = in->sin_addr.s_addr}; + unsigned count = *n < sizeof a ? *n : sizeof a; memcpy(p, &a, count); *n = sizeof a; +} +static int net_wait(net_ref *r, short events, int64_t timeout, uint64_t start) { + for (;;) { + if (!net_live(r)) return net_error(9); + int slice = NET_SLICE_MS; + if (timeout >= 0) { uint64_t elapsed = net_ms() - start; if (elapsed >= (uint64_t)timeout) return net_error(11); if ((uint64_t)slice > (uint64_t)timeout - elapsed) slice = (int)((uint64_t)timeout - elapsed); } + struct pollfd p = {.fd = r->fd, .events = events}; + dm_guest_host_wait_begin(); int count = poll(&p, 1, slice), err = errno; dm_guest_host_wait_end(); + if (count < 0 && err == EINTR) continue; + if (count < 0) return net_error(net_errno(err)); + if (!net_live(r)) return net_error(9); + if (count) return 0; + } +} +int dm_net_socket(int family, int type, int protocol) { + if (!net_gate()) return -1; + if (family != 2) return net_error(97); + unsigned flags = (unsigned)type & ~0xfu; int base = type & 0xf; + if (flags & ~0x20000000u) return net_error(22); + if (base != 1 && base != 2) return net_error(94); + if (protocol && protocol != (base == 1 ? 6 : 17)) return net_error(93); + int fd = socket(AF_INET, base == 1 ? SOCK_STREAM : SOCK_DGRAM, protocol), err = errno; + int result = fd < 0 ? net_error(net_errno(err)) : net_register(fd, base, !!flags); + net_trace("socket", result, result); return result; +} +// In Nextendo mode a closed UDP port stays open for a moment. A peer-to-peer library that closes a bound UDP socket and binds the same port +// again (Mush8 handles this for Mario Kart 8 Deluxe's Pia; not yet seen in a log here) would otherwise have datagrams that arrive in between +// answered with ICMP port unreachable, where Horizon drops them. So closing a bound, unconnected UDP socket keeps its host socket for +// NET_PARK_MS. A bind to that port within that time closes it first, so the game's new socket, with the options the game set on it, gets the +// port; what arrived in between is dropped, as on Horizon. +enum { NET_PARK_MAX = 8, NET_PARK_MS = 5000 }; +static struct { int fd; uint16_t port; uint64_t until; } g_parked[NET_PARK_MAX]; // fd 0 = free; under g_net_lock +static void net_park_expire(uint64_t now) { // with g_net_lock held + for (int i = 0; i < NET_PARK_MAX; i++) if (g_parked[i].fd > 0 && (!now || g_parked[i].until <= now)) { close(g_parked[i].fd); g_parked[i].fd = 0; } +} +static uint16_t net_unconnected_udp_port(int fd) { + int type = 0; socklen_t size = sizeof type; struct sockaddr_in a; socklen_t n = sizeof a; + if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &size) || type != SOCK_DGRAM) return 0; + if (!getpeername(fd, (struct sockaddr *)&a, &n)) return 0; + n = sizeof a; + if (getsockname(fd, (struct sockaddr *)&a, &n) || a.sin_family != AF_INET) return 0; + return ntohs(a.sin_port); +} +static int net_park(int fd) { // 1 when the table took fd (the caller then does not close it) + uint16_t port = dm_net_nextendo_enabled() ? net_unconnected_udp_port(fd) : 0; + if (!port) return 0; + pthread_mutex_lock(&g_net_lock); + net_park_expire(net_ms()); + int slot = -1; + for (int i = 0; i < NET_PARK_MAX; i++) { + if (g_parked[i].fd > 0 && g_parked[i].port == port) { close(g_parked[i].fd); g_parked[i].fd = 0; } + if (g_parked[i].fd <= 0 && slot < 0) slot = i; + } + if (slot >= 0) g_parked[slot] = (__typeof__(g_parked[0])){fd, port, net_ms() + NET_PARK_MS}; + pthread_mutex_unlock(&g_net_lock); + return slot >= 0; +} +// A bind to a parked port: the parked socket is closed, so the bind that follows finds the port free +static void net_unpark(uint16_t port) { + if (!port || !dm_net_nextendo_enabled()) return; + pthread_mutex_lock(&g_net_lock); + net_park_expire(net_ms()); + for (int i = 0; i < NET_PARK_MAX; i++) if (g_parked[i].fd > 0 && g_parked[i].port == port) { close(g_parked[i].fd); g_parked[i].fd = 0; } + pthread_mutex_unlock(&g_net_lock); +} +static int net_close_owned(int guest, int check_generation, uint64_t generation) { + pthread_mutex_lock(&g_net_lock); + if (guest < 0 || guest >= NET_MAX || !g_sockets[guest].used || + (check_generation && g_sockets[guest].generation != generation)) { + pthread_mutex_unlock(&g_net_lock); return net_error(9); + } + int fd = g_sockets[guest].native, peer = g_sockets[guest].peer; uint64_t old_generation = g_sockets[guest].generation; g_sockets[guest].used = 0; + pthread_mutex_unlock(&g_net_lock); + net_discovery_cancel(guest, old_generation); + if (peer >= 0) close(peer); // an event descriptor's write end + if (net_park(fd)) return 0; + shutdown(fd, SHUT_RDWR); int result = close(fd), err = errno; + return net_host_result(result, err); +} +int dm_net_close(int guest) { return net_gate() ? net_close_owned(guest, 0, 0) : -1; } +int dm_net_socket_type(int guest) { + pthread_mutex_lock(&g_net_lock); int type = guest >= 0 && guest < NET_MAX && g_sockets[guest].used ? g_sockets[guest].type : 0; pthread_mutex_unlock(&g_net_lock); + return type; +} +int dm_net_close_generation(int guest, uint64_t generation) { return net_close_owned(guest, 1, generation); } +// An event descriptor in a network mode (nn::socket::EventFd; gRPC wakes its pollers with one while they poll its sockets, nn::npln). It takes a slot of the socket table, so the +// sockets and the event descriptors share one numbering, lowest free first, and Poll, Select, Close and the generation checks treat it as any descriptor. Its host descriptor is +// the read end of a local socket pair that holds one byte while the counter is above zero, so a poll sees it readable exactly then; it is always writable. The flags are Horizon's: +// bit 0 reads one at a time (a semaphore), bits 1 and 2 never block. The counter's lock is the table's. +static int net_event(int guest, uint64_t generation, net_slot **out) { // with g_net_lock held + if (guest < 0 || guest >= NET_MAX || !g_sockets[guest].used || (generation && g_sockets[guest].generation != generation)) return net_error(9); + if (g_sockets[guest].type != NET_EVENT) return net_error(22); + *out = &g_sockets[guest]; return 0; +} +int dm_net_eventfd(uint64_t initial, int flags) { + if (!net_gate()) return -1; + int pair[2]; if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) < 0) return net_error(net_errno(errno)); + if (fcntl(pair[1], F_SETFL, O_NONBLOCK) < 0 || fcntl(pair[1], F_SETFD, FD_CLOEXEC) < 0) { int e = errno; close(pair[0]); close(pair[1]); return net_error(net_errno(e)); } + int guest = net_register(pair[0], NET_EVENT, !!(flags & 6)); // closes pair[0] if it fails + if (guest < 0) { close(pair[1]); return -1; } + pthread_mutex_lock(&g_net_lock); + g_sockets[guest].peer = pair[1]; g_sockets[guest].count = initial; g_sockets[guest].efd_flags = flags; + if (initial) (void)send(pair[1], "", 1, 0); + pthread_mutex_unlock(&g_net_lock); + net_trace("eventfd", guest, guest); return guest; +} +int dm_net_eventfd_read(int guest, uint64_t *value) { + if (!net_gate()) return -1; + uint64_t generation = 0; + for (;;) { + pthread_mutex_lock(&g_net_lock); + net_slot *e; if (net_event(guest, generation, &e)) { pthread_mutex_unlock(&g_net_lock); return -1; } + generation = e->generation; + if (e->count) { + uint64_t take = e->efd_flags & 1 ? 1 : e->count; e->count -= take; + // NOLINTNEXTLINE(clang-analyzer-unix.BlockInCriticalSection): both ends are non-blocking (net_register, dm_net_eventfd), and the drain must stay atomic with the count + if (!e->count) { char byte; (void)recv(e->native, &byte, 1, 0); } + pthread_mutex_unlock(&g_net_lock); + if (value) *value = take; return 0; + } + int nonblock = e->nonblock; pthread_mutex_unlock(&g_net_lock); + if (nonblock) return net_error(11); + net_ref r; if (net_borrow_any(guest, &r)) return -1; + if (r.generation != generation) { close(r.fd); return net_error(9); } + int waited = net_wait(&r, POLLIN, -1, net_ms()); close(r.fd); + if (waited) return -1; // closed while waiting: EBADF + } +} +int dm_net_eventfd_write(int guest, uint64_t value) { + if (!net_gate()) return -1; + if (value == UINT64_MAX) return net_error(22); + uint64_t generation = 0; + for (;;) { + pthread_mutex_lock(&g_net_lock); + net_slot *e; if (net_event(guest, generation, &e)) { pthread_mutex_unlock(&g_net_lock); return -1; } + generation = e->generation; + if (value <= UINT64_MAX - 1 - e->count) { // the counter's largest value is UINT64_MAX - 1 + if (!e->count && value) (void)send(e->peer, "", 1, 0); + e->count += value; pthread_mutex_unlock(&g_net_lock); return 0; + } + int nonblock = e->nonblock; pthread_mutex_unlock(&g_net_lock); + if (nonblock) return net_error(11); + dm_guest_host_wait_begin(); (void)poll(NULL, 0, NET_SLICE_MS); dm_guest_host_wait_end(); // a full counter waits for a read + } +} +void dm_net_finalize(void) { net_resolver_finalize(); for (int i = 0; i < NET_MAX; i++) { pthread_mutex_lock(&g_net_lock); int used = g_sockets[i].used; pthread_mutex_unlock(&g_net_lock); if (used) net_close_owned(i, 0, 0); } pthread_mutex_lock(&g_net_lock); net_park_expire(0); pthread_mutex_unlock(&g_net_lock); } +int dm_net_bind(int guest, const void *addr, unsigned len) { + if (!net_gate()) return -1; + struct sockaddr_in a; if (net_addr_in(addr, len, &a)) return -1; + net_ref r; if (net_borrow(guest, &r)) return -1; + if (r.type == 2) net_unpark(ntohs(a.sin_port)); + int result = bind(r.fd, (struct sockaddr *)&a, sizeof a), err = errno; close(r.fd); + result = net_host_result(result, err); net_trace("bind", guest, result); return result; +} +int dm_net_connect(int guest, const void *addr, unsigned len) { + if (!net_gate()) return -1; + struct sockaddr_in a; if (net_addr_in(addr, len, &a)) return -1; + net_ref r; if (net_borrow(guest, &r)) return -1; + if (net_is_discovery(a.sin_addr.s_addr, r.type) && dm_net_discovery_target(a.sin_addr.s_addr, &a.sin_addr.s_addr)) { close(r.fd); return -1; } + uint64_t start = net_ms(); int result = connect(r.fd, (struct sockaddr *)&a, sizeof a), err = errno; + if (result < 0 && err == EINPROGRESS && !r.nonblock) { + result = net_wait(&r, POLLOUT, r.send_ms, start); + if (!result) { socklen_t n = sizeof err; if (getsockopt(r.fd, SOL_SOCKET, SO_ERROR, &err, &n) < 0) err = errno; result = err ? -1 : 0; if (result) net_error(net_errno(err)); } + } else result = net_host_result(result, err); + close(r.fd); net_trace("connect", guest, result); return result; +} +int dm_net_listen(int guest, int backlog) { net_ref r; if (net_borrow(guest, &r)) return -1; int result = listen(r.fd, backlog), err = errno; close(r.fd); return net_host_result(result, err); } +int dm_net_accept(int guest, void *addr, unsigned *len) { + if (!net_gate() || net_addr_output_ok(addr, len)) return -1; + net_ref r; if (net_borrow(guest, &r)) return -1; + uint64_t start = net_ms(); int fd; + struct sockaddr_in a; + for (;;) { + socklen_t n = sizeof a; fd = accept(r.fd, (struct sockaddr *)&a, &n); int err = errno; + if (fd >= 0) break; + if (err != EAGAIN || r.nonblock) { net_error(net_errno(err)); break; } + if (net_wait(&r, POLLIN, r.recv_ms, start)) break; + } + close(r.fd); + if (fd < 0) return -1; + int result = net_register(fd, 1, r.nonblock); + if (result >= 0) net_addr_out(addr, len, &a); + return result; +} +static int net_name_impl(int guest, void *addr, unsigned *len, int peer) { + if (!net_gate()) return -1; + if (!addr || !len) return net_error(14); + net_ref r; if (net_borrow(guest, &r)) return -1; + struct sockaddr_in a; socklen_t n = sizeof a; + int result = peer ? getpeername(r.fd, (struct sockaddr *)&a, &n) : getsockname(r.fd, (struct sockaddr *)&a, &n), err = errno; close(r.fd); + if (result >= 0) net_addr_out(addr, len, &a); + return net_host_result(result, err); +} +int dm_net_shutdown(int guest, int how) { + if (!net_gate()) return -1; + if (how < 0 || how > 2) return net_error(22); + net_ref r; if (net_borrow(guest, &r)) return -1; + int methods[] = {SHUT_RD, SHUT_WR, SHUT_RDWR}; int result = shutdown(r.fd, methods[how]), err = errno; close(r.fd); return net_host_result(result, err); +} +static int net_fcntl_impl(int guest, int cmd, int flags) { + net_ref r; if (net_borrow(guest, &r)) return -1; + close(r.fd); + if (cmd == 3) return r.nonblock ? NX_NONBLOCK : 0; + if (cmd != 4) return net_error(95); + // F_SETFL does not change the descriptor's access mode. NEX supplies + // O_RDWR | O_NONBLOCK (0x802); reject unsupported status flags, not the + // read/write bits carried from a caller's file-status flags. + if ((unsigned)flags & ~(NX_NONBLOCK | 3u)) return net_error(22); + pthread_mutex_lock(&g_net_lock); + int live = g_sockets[guest].used && g_sockets[guest].generation == r.generation; + if (live) g_sockets[guest].nonblock = !!(flags & NX_NONBLOCK); + pthread_mutex_unlock(&g_net_lock); return live ? 0 : net_error(9); +} +static int net_message_flags(int flags, int sending) { + if ((unsigned)flags & ~(1u | 2u | 4u | 0x40u | 0x80u)) return net_error(95); + if (sending && (flags & (2 | 0x40))) return net_error(95); + int out = 0; + if (flags & 1) out |= MSG_OOB; if (flags & 2) out |= MSG_PEEK; if (flags & 4) out |= MSG_DONTROUTE; + // Native sockets always remain nonblocking. Guest blocking and WAITALL are implemented around readiness waits. + return out; +} +long dm_net_recv(int guest, void *buf, unsigned long len, int flags, void *addr, unsigned *addrlen) { + if (!net_gate()) return -1; + if ((!buf && len) || net_addr_output_ok(addr, addrlen)) return net_error(14); + if (len > SSIZE_MAX) return net_error(22); + int hostflags = net_message_flags(flags, 0); if (hostflags < 0) return -1; + net_ref r; if (net_borrow(guest, &r)) return -1; + if ((flags & 0x40) && (flags & 2)) { close(r.fd); return net_error(95); } // PEEK+WAITALL would need a separate buffered transport. + uint64_t start = net_ms(); long result = -1; size_t total = 0; + struct sockaddr_in a; + for (;;) { + // Kernel copyout cannot fault into the dirty-page signal hook. A wait or + // partial stream read may allow the renderer to protect this span again. + dm_guest_write_prepare(buf ? (char *)buf + total : NULL, len - total); + socklen_t n = sizeof a; ssize_t got = recvfrom(r.fd, buf ? (char *)buf + total : NULL, len - total, hostflags, addr ? (struct sockaddr *)&a : NULL, addr ? &n : NULL); int err = errno; + if (got >= 0) { + total += (size_t)got; result = (long)total; net_udp_note(&r, 1, 0); + if (addr) net_addr_out(addr, addrlen, &a); + if (!got || r.type != 1 || !(flags & 0x40) || r.nonblock || (flags & 0x80) || total == len) break; + continue; + } + // A host report of ICMP unreachable for an earlier send, delivered on the next receive of a UDP socket. In Nextendo mode it counts as + // no datagram yet, so a peer that is not listening yet does not end a session (Mush8 does the same for Mario Kart 8 Deluxe) + if (r.type == 2 && (err == ECONNREFUSED || err == ECONNRESET || err == ENETRESET) && dm_net_nextendo_enabled()) err = EAGAIN; + if (err == EAGAIN) net_udp_note(&r, 0, 0); else net_udp_error(&r, 0, err); + if (err != EAGAIN || r.nonblock || (flags & 0x80)) { if (!total) result = net_error(net_errno(err)); break; } + if (net_wait(&r, POLLIN, r.recv_ms, start)) { if (!total) result = -1; break; } + } + close(r.fd); net_trace("recv", guest, result); return result; +} +long dm_net_send(int guest, const void *buf, unsigned long len, int flags, const void *addr, unsigned addrlen) { + if (!net_gate()) return -1; + if (!buf && len) return net_error(14); + if (len > SSIZE_MAX) return net_error(22); + struct sockaddr_in a; if (addr && net_addr_in(addr, addrlen, &a)) return -1; + int hostflags = net_message_flags(flags, 1); if (hostflags < 0) return -1; + net_ref r; if (net_borrow(guest, &r)) return -1; + int discovery=addr&&net_is_discovery(a.sin_addr.s_addr,r.type); + if (discovery) { + dm_net_discovery_plan plan; + if (dm_net_discovery_prepare(a.sin_addr.s_addr, &plan)) { close(r.fd); return -1; } + if (plan.automatic) { + long result = net_discovery_enqueue(&r, plan, a, buf, len, hostflags); + close(r.fd); net_trace("send-discovery", guest, result); return result; + } + a.sin_addr.s_addr = plan.target; + } + uint64_t start = net_ms(); long result; int reported = 0; + for (;;) { + result = addr ? net_discovery_packet(r.fd,buf,len,hostflags,&a) : sendto(r.fd,buf,len,hostflags,NULL,0); int err = errno; + if (result >= 0) { net_udp_note(&r, 0, 1); break; } + if (err != EAGAIN) net_udp_error(&r, 1, err); + // As on a receive (dm_net_recv): the host hands an earlier datagram's ICMP report to the next call on a UDP socket, a send too, and then + // does not send this datagram (the report is cleared). In Nextendo mode it is sent again once + if (r.type == 2 && !reported && (err == ECONNREFUSED || err == ECONNRESET || err == ENETRESET) && dm_net_nextendo_enabled()) { reported = 1; continue; } + if (err != EAGAIN || r.nonblock || (flags & 0x80)) { result = net_error(net_errno(err)); break; } + if (net_wait(&r, POLLOUT, r.send_ms, start)) { result = -1; break; } + } + if(result>=0&&discovery&&dm_discovery_query_protocol(ntohs(a.sin_port),buf,len)) { + dm_net_discovery_plan extra;int saved=t_net_errno; + if(dm_net_discovery_supplement(a.sin_addr.s_addr,&extra)) { + long queued=net_discovery_enqueue(&r,extra,a,buf,len,hostflags); + net_trace("send-discovery-extra",guest,queued); + } + // The original native send owns the result. Queue pressure or an + // unavailable bounded subnet must not turn its success into failure. + t_net_errno=saved; + } + close(r.fd); net_trace("send", guest, result); return result; +} + +static int net_option(int level, int option, int *hostlevel, int *hostoption, unsigned *size) { + *size = sizeof(int); + if (level == 0xffff) { + *hostlevel = SOL_SOCKET; + switch (option) { + case 1: *hostoption = SO_DEBUG; break; case 2: *hostoption = SO_ACCEPTCONN; break; + case 4: *hostoption = SO_REUSEADDR; break; case 8: *hostoption = SO_KEEPALIVE; break; + case 16: *hostoption = SO_DONTROUTE; break; case 32: *hostoption = SO_BROADCAST; break; + case 128: *hostoption = SO_LINGER; *size = sizeof(struct linger); break; + case 256: *hostoption = SO_OOBINLINE; break; case 512: *hostoption = SO_REUSEPORT; break; + case 0x800: *hostoption = SO_NOSIGPIPE; break; + case 0x1001: *hostoption = SO_SNDBUF; break; case 0x1002: *hostoption = SO_RCVBUF; break; + case 0x1003: *hostoption = SO_SNDLOWAT; break; case 0x1004: *hostoption = SO_RCVLOWAT; break; + case 0x1007: *hostoption = SO_ERROR; break; case 0x1008: *hostoption = SO_TYPE; break; + default: return net_error(92); + } + } else if (level == 6) { + *hostlevel = IPPROTO_TCP; + if (option == 1) *hostoption = TCP_NODELAY; + else if (option == 2) *hostoption = TCP_MAXSEG; + else return net_error(92); + } else if (level == 0) { + *hostlevel = IPPROTO_IP; + switch (option) { + case 3: *hostoption = IP_TOS; break; case 4: *hostoption = IP_TTL; break; + case 9: *hostoption = IP_MULTICAST_IF; *size = 4; break; + case 10: *hostoption = IP_MULTICAST_TTL; *size = 1; break; + case 11: *hostoption = IP_MULTICAST_LOOP; *size = 1; break; + case 12: *hostoption = IP_ADD_MEMBERSHIP; *size = 8; break; + case 13: *hostoption = IP_DROP_MEMBERSHIP; *size = 8; break; + default: return net_error(92); + } + } else return net_error(92); + return 0; +} +static int net_sockopt_impl(int guest, int level, int option, void *value, unsigned *len, int set) { + if (!net_gate()) return -1; + if (!value || !len) return net_error(14); + if (set && level == 0 && option == 12 && !dm_net_multicast_allowed()) return net_error(13); + net_ref r; if (net_borrow(guest, &r)) return -1; + if (level == 0xffff && (option == 0x1005 || option == 0x1006)) { + // Horizon's service uses a u32 millisecond value. Also accept the SDK's 64-bit TimeVal form, translating rather than passing it to Darwin. + int64_t ms; + if (set) { + if (*len == 4) { uint32_t v; memcpy(&v, value, 4); ms = v ? (int64_t)v : -1; } + else if (*len == sizeof(nx_timeval)) { nx_timeval v; memcpy(&v, value, sizeof v); if (v.sec < 0 || v.usec < 0 || v.usec >= 1000000 || v.sec > INT_MAX / 1000) { close(r.fd); return net_error(22); } ms = v.sec * 1000 + (v.usec + 999) / 1000; if (!ms) ms = -1; } + else { close(r.fd); return net_error(22); } + pthread_mutex_lock(&g_net_lock); + int live = g_sockets[guest].used && g_sockets[guest].generation == r.generation; + if (live) { if (option == 0x1005) g_sockets[guest].send_ms = ms; else g_sockets[guest].recv_ms = ms; } + pthread_mutex_unlock(&g_net_lock); close(r.fd); return live ? 0 : net_error(9); + } + ms = option == 0x1005 ? r.send_ms : r.recv_ms; if (ms < 0) ms = 0; + if (*len == sizeof(nx_timeval)) { nx_timeval v = {ms / 1000, ms % 1000 * 1000}; memcpy(value, &v, sizeof v); } + else if (*len >= 4) { uint32_t v = (uint32_t)ms; memcpy(value, &v, 4); *len = 4; } + else { close(r.fd); return net_error(22); } + close(r.fd); return 0; + } + int hl, ho; unsigned size; + if (net_option(level, option, &hl, &ho, &size)) { close(r.fd); return -1; } + if (set && level == 0xffff && (option == 2 || option == 0x1007 || option == 0x1008)) { close(r.fd); return net_error(92); } + // SO_NOSIGPIPE is required internally to preserve the guest's EPIPE convention. Guest setting it to zero cannot re-enable a process-killing host signal. + int one = 1; void *hostvalue = level == 0xffff && option == 0x800 ? &one : value; + if (*len < size || (set && *len != size)) { close(r.fd); return net_error(22); } + if (set && level == 0xffff && option == 128) { + int v[2]; memcpy(v, value, sizeof v); + if ((v[0] != 0 && v[0] != 1) || v[1] < 0) { close(r.fd); return net_error(22); } + } + socklen_t n = size; + // Kernel copyout does not invoke the tracked guest-page write-fault hook. + if (!set) dm_guest_write_prepare(value, n); + int result = set ? setsockopt(r.fd, hl, ho, hostvalue, n) : getsockopt(r.fd, hl, ho, value, &n), err = errno; + if (!set && result >= 0) { + *len = n; + if (level == 0xffff && option == 0x1007 && n == 4) { int e; memcpy(&e, value, 4); e = net_errno(e); memcpy(value, &e, 4); } + } + close(r.fd); return net_host_result(result, err); +} +static short net_poll_events(uint16_t events) { + short host = 0; + if (events & 1) host |= POLLIN; if (events & 2) host |= POLLPRI; if (events & 4) host |= POLLOUT; + if (events & 64) host |= POLLRDNORM; if (events & 128) host |= POLLRDBAND; if (events & 256) host |= POLLWRBAND; + return host; +} +static int16_t net_poll_revents(short events) { + int16_t out = 0; + if (events & POLLIN) out |= 1; if (events & POLLPRI) out |= 2; if (events & POLLOUT) out |= 4; + if (events & POLLERR) out |= 8; if (events & POLLHUP) out |= 16; if (events & POLLNVAL) out |= 32; + if (events & POLLRDNORM) out |= 64; if (events & POLLRDBAND) out |= 128; if (events & POLLWRBAND) out |= 256; + return out; +} +int dm_net_idle(void) { + for (;;) { + dm_guest_host_wait_begin(); int result = poll(NULL, 0, -1), err = errno; dm_guest_host_wait_end(); + if (result < 0 && err == EINTR) continue; // Host pause/lifecycle signals are not guest-visible interrupts. + return net_host_result(result, err); + } +} +int dm_net_poll(void *fds, uint64_t count, int timeout_ms) { + if (!net_gate()) return -1; + if (count > NET_MAX) return net_error(22); + if (count && !fds) return net_error(14); + struct pollfd *host = calloc(count ? (size_t)count : 1, sizeof *host); + net_ref *refs = calloc(count ? (size_t)count : 1, sizeof *refs); + dm_net_pollfd *guest = fds; + if (!host || !refs) { free(host); free(refs); return net_error(12); } + int result = -1, invalid = 0; + for (uint64_t i = 0; i < count; i++) refs[i].fd = -1; + for (uint64_t i = 0; i < count; i++) { + refs[i].fd = host[i].fd = -1; guest[i].revents = 0; + if (guest[i].fd < 0) continue; + if ((uint16_t)guest[i].events & (uint16_t)~0x1ffu) { net_error(22); goto done; } + if (net_borrow_any(guest[i].fd, &refs[i])) { if (t_net_errno != 9) goto done; guest[i].revents = 32; invalid = 1; } + else { host[i].fd = refs[i].fd; host[i].events = net_poll_events((uint16_t)guest[i].events); } + } + uint64_t start = net_ms(); + for (;;) { + int wait = invalid ? 0 : NET_SLICE_MS; + if (timeout_ms >= 0) { uint64_t elapsed = net_ms() - start; uint64_t left = elapsed < (uint64_t)timeout_ms ? (uint64_t)timeout_ms - elapsed : 0; if ((uint64_t)wait > left) wait = (int)left; } + dm_guest_host_wait_begin(); int ready = poll(host, (nfds_t)count, wait), err = errno; dm_guest_host_wait_end(); + if (ready < 0 && err == EINTR) continue; + if (ready < 0) { net_error(net_errno(err)); break; } + result = 0; + for (uint64_t i = 0; i < count; i++) { + if (refs[i].fd >= 0) guest[i].revents = net_live(&refs[i]) ? net_poll_revents(host[i].revents) : 32; + if (guest[i].revents) result++; + } + if (result || (timeout_ms >= 0 && net_ms() - start >= (uint64_t)timeout_ms)) break; + } +done: + for (uint64_t i = 0; i < count; i++) if (refs[i].fd >= 0) close(refs[i].fd); + free(host); free(refs); return result; +} +int dm_net_select(int nfds, void *read, void *write, void *except, const int64_t *timeout) { + if (!net_gate()) return -1; + if (nfds < 0 || nfds > NET_MAX) return net_error(22); + int ms = -1; + if (timeout) { + int64_t sec = timeout[0], us = timeout[1]; + if (sec < 0 || us < 0 || us >= 1000000 || sec > INT_MAX / 1000) return net_error(22); + int64_t total = sec * 1000 + (us + 999) / 1000; if (total > INT_MAX) return net_error(22); ms = (int)total; + } + dm_net_pollfd *fds = calloc(nfds ? (size_t)nfds : 1, sizeof *fds); + if (!fds) return net_error(12); + uint64_t *sets[] = {read, write, except}; + int count = 0; + for (int i = 0; i < nfds; i++) { + uint16_t ev = 0; + for (int k = 0; k < 3; k++) if (sets[k] && ((sets[k][i >> 6] >> (i & 63)) & 1)) ev |= (uint16_t[]){1, 4, 2}[k]; + if (ev) fds[count++] = (dm_net_pollfd){i, (int16_t)ev, 0}; + } + int result = dm_net_poll(fds, (uint64_t)count, ms); + if (result >= 0) for (int i = 0; i < count; i++) if (fds[i].revents & 32) { result = net_error(9); break; } + if (result >= 0) { + for (int k = 0; k < 3; k++) if (sets[k]) memset(sets[k], 0, NET_MAX / 8); + result = 0; + for (int i = 0; i < count; i++) for (int k = 0; k < 3; k++) if (sets[k] && (fds[i].events & (int[]){1, 4, 2}[k]) && (fds[i].revents & (int[]){1 | 8 | 16, 4 | 8 | 16, 2}[k])) { sets[k][fds[i].fd >> 6] |= 1ull << (fds[i].fd & 63); result++; } + } + free(fds); return result; +} + +typedef struct net_ai_allocation { struct net_ai_allocation *next; dm_net_addrinfo *root; void **owned; size_t count; } net_ai_allocation; +static net_ai_allocation *g_ai; +static int net_gai_error(int e) { + switch (e) { + case 0: return 0; case EAI_AGAIN: return 2; case EAI_BADFLAGS: return 3; case EAI_FAIL: return 4; + case EAI_FAMILY: return 5; case EAI_MEMORY: return 6; case EAI_NODATA: return 7; case EAI_NONAME: return 8; + case EAI_SERVICE: return 9; case EAI_SOCKTYPE: return 10; case EAI_SYSTEM: return 11; case EAI_OVERFLOW: return 14; + default: return 4; + } +} +static void net_ai_destroy(net_ai_allocation *p) { if (p) { for (size_t i = 0; i < p->count; i++) free(p->owned[i]); free(p->owned); free(p); } } +// Shared admission: both resolver ABIs must expand NSD before consulting the +// same scoped provider. Service policy does not alter ordinary LAN or offline resolution. +static int net_resolver_name(const char *host, int flags, char expanded[DM_NSD_FQDN_CAPACITY], + char redirected[INET_ADDRSTRLEN], const char **lookup) { + *lookup = host; + if (dm_net_nextendo_enabled() && host) { + struct in_addr literal; int numeric = inet_pton(AF_INET, host, &literal) == 1; + if (!numeric && (flags & 4)) return 8; + if (!numeric && strchr(host, '%')) { + if (dm_nsd_resolve(expanded, host)) return 8; + *lookup = expanded; + } + dm_net_dns_provider provider = atomic_load(&g_dns_provider); + int policy = provider ? provider(*lookup, redirected, INET_ADDRSTRLEN) : numeric ? 0 : -1; + if (policy < 0 || policy > 1 || (policy > 0 && (!memchr(redirected, 0, INET_ADDRSTRLEN) || inet_pton(AF_INET, redirected, &literal) != 1))) return 8; + if (policy > 0) *lookup = redirected; + } + return 0; +} +static int net_getaddrinfo(const char *host, const char *service, const void *hints, void **result, int legacy) { + if (!result) { net_error(14); return 11; } + *result = NULL; + if (!net_gate()) return 4; + struct addrinfo h = {.ai_family = AF_INET}, *native = NULL; + dm_net_addrinfo input = {0}; if (hints) memcpy(&input, hints, sizeof input); + if (input.family != 0 && input.family != 2) return 5; + if (input.type && input.type != 1 && input.type != 2) return 10; + if (input.protocol && input.protocol != 6 && input.protocol != 17) return 13; + if ((unsigned)input.flags & ~(1u | 2u | 4u | 8u | 1024u)) return 3; + h.ai_socktype = input.type == 1 ? SOCK_STREAM : input.type == 2 ? SOCK_DGRAM : 0; h.ai_protocol = input.protocol; + if (input.flags & 1) h.ai_flags |= AI_PASSIVE; if (input.flags & 2) h.ai_flags |= AI_CANONNAME; + if (input.flags & 4) h.ai_flags |= AI_NUMERICHOST; if (input.flags & 8) h.ai_flags |= AI_NUMERICSERV; + if (input.flags & 1024) h.ai_flags |= AI_ADDRCONFIG; + char redirected[INET_ADDRSTRLEN] = {0}, expanded[DM_NSD_FQDN_CAPACITY]; const char *lookup = host; + int admission = net_resolver_name(host, input.flags, expanded, redirected, &lookup); + if (admission) return admission; + dm_guest_host_wait_begin(); int code = getaddrinfo(lookup, service, &h, &native), err = errno; dm_guest_host_wait_end(); + if (code) { if (code == EAI_SYSTEM) net_error(net_errno(err)); return net_gai_error(code); } + net_ai_allocation *allocation = calloc(1, sizeof *allocation); + if (!allocation) { freeaddrinfo(native); return 6; } + size_t capacity = 0; + for (struct addrinfo *p = native; p; p = p->ai_next) if (++capacity > NET_MAX) { net_ai_destroy(allocation); freeaddrinfo(native); return 6; } + allocation->owned = calloc(capacity ? capacity : 1, sizeof(void *)); + if (!allocation->owned) { net_ai_destroy(allocation); freeaddrinfo(native); return 6; } + dm_net_addrinfo *first = NULL, **tail = &first; + for (struct addrinfo *p = native; p; p = p->ai_next) { + if (p->ai_family != AF_INET || p->ai_addrlen < sizeof(struct sockaddr_in)) continue; + const char *canonical = lookup != host && (input.flags & 2) ? host : p->ai_canonname; + size_t name_size = canonical ? strlen(canonical) + 1 : 0; + dm_net_addrinfo *node = calloc(1, sizeof *node + sizeof(nx_addr) + name_size); + if (!node) { net_ai_destroy(allocation); freeaddrinfo(native); return 6; } + allocation->owned[allocation->count++] = node; + nx_addr *address = (nx_addr *)(node + 1); + node->flags = input.flags; node->family = 2; node->type = p->ai_socktype == SOCK_STREAM ? 1 : 2; node->protocol = p->ai_protocol; + node->addrlen = sizeof *address; node->addr = address; + struct sockaddr_in *a = (struct sockaddr_in *)p->ai_addr; unsigned n = sizeof *address; net_addr_out(address, &n, a); + if (name_size) { node->canonname = (char *)(address + 1); memcpy(node->canonname, canonical, name_size); } + if (legacy) { void *swap = node->addr; node->addr = node->canonname; node->canonname = swap; } + *tail = node; tail = (dm_net_addrinfo **)&node->next; + } + freeaddrinfo(native); + if (!first) { net_ai_destroy(allocation); return 7; } + allocation->root = first; pthread_mutex_lock(&g_net_lock); allocation->next = g_ai; g_ai = allocation; pthread_mutex_unlock(&g_net_lock); + *result = first; return 0; +} +// Every lookup in a network mode is logged with its name and result (a failed one in red; the name is a server's, never an account's), so a game that stops before its +// first socket shows which name it could not resolve +static int net_getaddrinfo_logged(const char *host, const char *service, const void *hints, void **result, int legacy) { + int code = net_getaddrinfo(host, service, hints, result, legacy); + if (dm_net_enabled()) { + const dm_net_addrinfo *h = hints; char name[96]; snprintf(name, sizeof name, "%s", host ? host : "(none)"); + fprintf(stderr, "%snet: name lookup %s port %s (family %d, flags %#x, %s layout) -> %d\n", code ? "[RED] " : "", name, service ? service : "-", + h ? h->family : 0, h ? (unsigned)h->flags : 0u, legacy ? "addrinfo" : "AddrInfo", code); + } + return code; +} +int dm_net_getaddrinfo(const char *host, const char *service, const void *hints, void **result) { return net_getaddrinfo_logged(host, service, hints, result, 0); } +int dm_net_getaddrinfo_legacy(const char *host, const char *service, const void *hints, void **result) { return net_getaddrinfo_logged(host, service, hints, result, 1); } +void dm_net_freeaddrinfo(void *result) { + if (!result) return; + pthread_mutex_lock(&g_net_lock); net_ai_allocation **link = &g_ai; while (*link && (*link)->root != result) link = &(*link)->next; + net_ai_allocation *found = *link; if (found) *link = found->next; pthread_mutex_unlock(&g_net_lock); + if (found) net_ai_destroy(found); else if (dm_net_enabled()) net_error(22); +} +static void *net_hostent(const char *name, const uint32_t *addresses, size_t count) { + typedef struct { char *name; char **aliases; int32_t family, length; char **addresses; } nx_hostent; + static __thread struct { nx_hostent entry; char name[NI_MAXHOST]; char *aliases[1], *addresses[65]; uint32_t data[64]; } data; + _Static_assert(sizeof(nx_hostent) == 32 && offsetof(nx_hostent, addresses) == 24, "Horizon hostent"); + memset(&data, 0, sizeof data); snprintf(data.name, sizeof data.name, "%s", name); + for (size_t i = 0; i < count; ++i) { data.data[i] = addresses[i]; data.addresses[i] = (char *)&data.data[i]; } + data.entry = (nx_hostent){data.name, data.aliases, 2, 4, data.addresses}; return &data.entry; +} +void *dm_net_gethostbyname(const char *name) { + if (!name) { net_error(14); return NULL; } + void *out = NULL; dm_net_addrinfo hints = {.family = 2, .type = 1}; + if (dm_net_getaddrinfo(name, NULL, &hints, &out)) return NULL; + uint32_t addresses[64]; size_t n = 0; + for (dm_net_addrinfo *p = out; p && n < 64; p = p->next) addresses[n++] = ((nx_addr *)p->addr)->address; + void *entry = net_hostent(name, addresses, n); dm_net_freeaddrinfo(out); return entry; +} + +// A cancel ID is not a socket and is not reused in this process. Only active +// native queries occupy the bounded registry; requesting an unused ID leaks no +// slot. Each DNSServiceRef is created, used and destroyed on one serial queue. +enum { NET_RESOLVER_MAX = 64, NET_RESOLVER_NO_ADDRESS = -1 }; +typedef struct net_resolver_job { + pthread_mutex_t lock; + pthread_cond_t changed; + _Atomic unsigned references; + uint32_t id, addresses[64]; + size_t count; + int done, error, finished; + DNSServiceRef service; + char name[NI_MAXHOST]; +} net_resolver_job; +static pthread_mutex_t g_resolver_lock = PTHREAD_MUTEX_INITIALIZER; +static net_resolver_job *g_resolver_jobs[NET_RESOLVER_MAX]; +static unsigned g_resolver_finalizing; +static _Atomic uint64_t g_resolver_next_id = 1; +static pthread_once_t g_resolver_once = PTHREAD_ONCE_INIT; +static dispatch_queue_t g_resolver_queue; +static void net_resolver_init(void) { g_resolver_queue = dispatch_queue_create("org.nxnative.resolver", DISPATCH_QUEUE_SERIAL); } +static dispatch_queue_t net_resolver_queue(void) { + dm_guest_host_wait_begin(); pthread_once(&g_resolver_once, net_resolver_init); dm_guest_host_wait_end(); + return g_resolver_queue; +} +static void net_resolver_lock(pthread_mutex_t *lock) { + if (!pthread_mutex_trylock(lock)) return; + dm_guest_host_wait_begin(); pthread_mutex_lock(lock); dm_guest_host_wait_end(); +} +static void net_resolver_retain(net_resolver_job *job) { atomic_fetch_add(&job->references, 1); } +static void net_resolver_release(net_resolver_job *job) { + if (atomic_fetch_sub(&job->references, 1) == 1) { + pthread_cond_destroy(&job->changed); pthread_mutex_destroy(&job->lock); free(job); + } +} +static void net_resolver_finish(net_resolver_job *job, int error) { + // Queue-owned lifetime lasts through deallocation; a waiting caller and any + // already queued cancellation each hold a separate reference. + if (job->finished) return; + job->finished = 1; + if (job->service) { DNSServiceRefDeallocate(job->service); job->service = NULL; } + pthread_mutex_lock(&g_resolver_lock); + for (unsigned i = 0; i < NET_RESOLVER_MAX; ++i) if (g_resolver_jobs[i] == job) { + g_resolver_jobs[i] = NULL; net_resolver_release(job); break; + } + pthread_mutex_unlock(&g_resolver_lock); + pthread_mutex_lock(&job->lock); job->error = error; job->done = 1; + pthread_cond_broadcast(&job->changed); pthread_mutex_unlock(&job->lock); + net_resolver_release(job); +} +static int net_resolver_error(DNSServiceErrorType error) { + switch (error) { + // A negative DNS answer is not a POSIX system errno. As in the + // existing GetAddrInfo path, fail without replacing retained errno. + case kDNSServiceErr_NoSuchRecord: case kDNSServiceErr_NoSuchName: return NET_RESOLVER_NO_ADDRESS; + case kDNSServiceErr_NoMemory: return 12; + case kDNSServiceErr_BadParam: case kDNSServiceErr_BadFlags: return 22; + case kDNSServiceErr_Unsupported: return 95; + case kDNSServiceErr_ServiceNotRunning: return 100; + case kDNSServiceErr_Timeout: return 110; + case kDNSServiceErr_PolicyDenied: case kDNSServiceErr_NotPermitted: return 13; + default: return 5; + } +} +static void net_resolver_reply(DNSServiceRef service, DNSServiceFlags flags, uint32_t interface, + DNSServiceErrorType error, const char *name, + const struct sockaddr *address, uint32_t ttl, void *context) { + (void)service; (void)interface; (void)name; (void)ttl; + net_resolver_job *job = context; + if (job->finished) return; + if (error) { net_resolver_finish(job, net_resolver_error(error)); return; } + if (!address || address->sa_family != AF_INET || address->sa_len < sizeof(struct sockaddr_in)) { + net_resolver_finish(job, 22); return; + } + uint32_t value = ((const struct sockaddr_in *)address)->sin_addr.s_addr; + size_t i = 0; while (i < job->count && job->addresses[i] != value) ++i; + if (flags & kDNSServiceFlagsAdd) { + if (i == job->count) { + if (job->count == 64) { net_resolver_finish(job, 75); return; } + job->addresses[job->count++] = value; + } + } else if (i < job->count) job->addresses[i] = job->addresses[--job->count]; + if (!(flags & kDNSServiceFlagsMoreComing)) net_resolver_finish(job, job->count ? 0 : NET_RESOLVER_NO_ADDRESS); +} +static void net_resolver_start(void *context) { + net_resolver_job *job = context; + // Use the system's own finite DNS deadline, not an application retry/sleep + // or an unbounded tracking query. A timeout is delivered as a real error. + DNSServiceErrorType error = DNSServiceGetAddrInfo(&job->service, kDNSServiceFlagsTimeout, 0, kDNSServiceProtocol_IPv4, + job->name, net_resolver_reply, job); + // The output reference is owned only on success, never on an API error. + if (error) { job->service = NULL; net_resolver_finish(job, net_resolver_error(error)); return; } + if (!job->service) { net_resolver_finish(job, 22); return; } + error = DNSServiceSetDispatchQueue(job->service, g_resolver_queue); + if (error) net_resolver_finish(job, net_resolver_error(error)); +} +uint32_t dm_net_request_cancel_handle(void) { + uint64_t id = atomic_load(&g_resolver_next_id); + while (id <= UINT32_MAX) { + if (atomic_compare_exchange_weak(&g_resolver_next_id, &id, id + 1)) return (uint32_t)id; + } + net_error(11); return 0; +} +static void net_resolver_cancel_job(void *context) { + net_resolver_job *job = context; + if (!job->finished) net_resolver_finish(job, 125); // Darwin ECANCELED -> Horizon ECANCELED. + net_resolver_release(job); +} +int dm_net_cancel(uint32_t id) { + if (!id) { net_error(22); return 0; } // Verified SDK Cancel(0) convention. + dispatch_queue_t queue = net_resolver_queue(); + if (!queue) return net_error(11); + net_resolver_lock(&g_resolver_lock); + for (unsigned i = 0; !g_resolver_finalizing && i < NET_RESOLVER_MAX; ++i) { + net_resolver_job *job = g_resolver_jobs[i]; + if (job && job->id == id) { net_resolver_retain(job); dispatch_async_f(queue, job, net_resolver_cancel_job); } + } + pthread_mutex_unlock(&g_resolver_lock); + return 0; +} +void *dm_net_gethostbyname_cancel(const char *name, uint32_t id) { + if (!net_gate()) return NULL; + if (!name) { net_error(22); return NULL; } // SDK resolver's null-name EINVAL. + if (strnlen(name, NI_MAXHOST) == NI_MAXHOST) { net_error(22); return NULL; } + char expanded[DM_NSD_FQDN_CAPACITY], redirected[INET_ADDRSTRLEN] = {0}; const char *lookup = name; + if (net_resolver_name(name, 0, expanded, redirected, &lookup)) return NULL; + struct in_addr literal; + if (inet_pton(AF_INET, lookup, &literal) == 1) return net_hostent(name, &literal.s_addr, 1); + dispatch_queue_t queue = net_resolver_queue(); + if (!queue) { net_error(12); return NULL; } + net_resolver_job *job = calloc(1, sizeof *job); + if (!job) { net_error(12); return NULL; } + if (pthread_mutex_init(&job->lock, NULL)) { free(job); net_error(12); return NULL; } + if (pthread_cond_init(&job->changed, NULL)) { pthread_mutex_destroy(&job->lock); free(job); net_error(12); return NULL; } + atomic_init(&job->references, 1); job->id = id; snprintf(job->name, sizeof job->name, "%s", lookup); + net_resolver_lock(&g_resolver_lock); unsigned slot = 0; + while (slot < NET_RESOLVER_MAX && g_resolver_jobs[slot]) ++slot; + if (g_resolver_finalizing) slot = NET_RESOLVER_MAX; + if (slot < NET_RESOLVER_MAX) { + g_resolver_jobs[slot] = job; net_resolver_retain(job); net_resolver_retain(job); + dispatch_async_f(queue, job, net_resolver_start); + } + pthread_mutex_unlock(&g_resolver_lock); + if (slot == NET_RESOLVER_MAX) { net_resolver_release(job); net_error(11); return NULL; } + net_resolver_lock(&job->lock); + while (!job->done) { dm_guest_host_wait_begin(); pthread_cond_wait(&job->changed, &job->lock); dm_guest_host_wait_end(); } + int error = job->error; void *result = error ? NULL : net_hostent(name, job->addresses, job->count); + pthread_mutex_unlock(&job->lock); net_resolver_release(job); + if (error > 0) net_error(error); + return result; +} +static void net_resolver_stop_all(void *unused) { + (void)unused; + for (unsigned i = 0; i < NET_RESOLVER_MAX; ++i) { + pthread_mutex_lock(&g_resolver_lock); net_resolver_job *job = g_resolver_jobs[i]; + if (job) net_resolver_retain(job); + pthread_mutex_unlock(&g_resolver_lock); + if (job) net_resolver_cancel_job(job); + } +} +static void net_resolver_finalize(void) { + dispatch_queue_t queue = net_resolver_queue(); + if (queue) { + net_resolver_lock(&g_resolver_lock); ++g_resolver_finalizing; pthread_mutex_unlock(&g_resolver_lock); + dm_guest_host_wait_begin(); dispatch_sync_f(queue, NULL, net_resolver_stop_all); dm_guest_host_wait_end(); + net_resolver_lock(&g_resolver_lock); --g_resolver_finalizing; pthread_mutex_unlock(&g_resolver_lock); + } +} + +// Query the actual IPv4 default route, then find that interface's address. DM_NETWORK_INTERFACE +// can choose another up IPv4 interface (including lo0 for deterministic transport tests). +static unsigned net_route(unsigned wanted, uint32_t *gateway) { +#if TARGET_OS_OSX + int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_DUMP, 0}; size_t size = 0; + if (sysctl(mib, 6, NULL, &size, NULL, 0) || !size) return 0; + char *buf = malloc(size); if (!buf) return 0; + if (sysctl(mib, 6, buf, &size, NULL, 0)) { free(buf); return 0; } + unsigned found = 0; + for (size_t pos = 0; pos + sizeof(struct rt_msghdr) <= size;) { + struct rt_msghdr *r = (struct rt_msghdr *)(buf + pos); size_t end = pos + r->rtm_msglen; + if (r->rtm_msglen < sizeof *r || end > size) break; + if ((r->rtm_flags & (RTF_UP | RTF_GATEWAY)) == (RTF_UP | RTF_GATEWAY) && !(r->rtm_flags & RTF_IFSCOPE) && (!wanted || wanted == r->rtm_index)) { + struct sockaddr *a[RTAX_MAX] = {0}; size_t next = pos + sizeof *r; + for (int i = 0; i < RTAX_MAX; i++) if (r->rtm_addrs & (1 << i)) { + if (next + 2 > end) break; struct sockaddr *s = (struct sockaddr *)(buf + next); + size_t n = s->sa_len ? (s->sa_len + sizeof(long) - 1) & ~(sizeof(long) - 1) : sizeof(long); + if (n > end - next) break; a[i] = s; next += n; + } + if (a[RTAX_DST] && a[RTAX_DST]->sa_family == AF_INET && a[RTAX_DST]->sa_len >= sizeof(struct sockaddr_in) && + ((struct sockaddr_in *)a[RTAX_DST])->sin_addr.s_addr == 0 && a[RTAX_GATEWAY] && a[RTAX_GATEWAY]->sa_family == AF_INET && a[RTAX_GATEWAY]->sa_len >= sizeof(struct sockaddr_in)) { + found = r->rtm_index; *gateway = ((struct sockaddr_in *)a[RTAX_GATEWAY])->sin_addr.s_addr; break; + } + } + pos = end; + } + free(buf); return found; +#else + (void)wanted; (void)gateway; return 0; +#endif +} +#if TARGET_OS_IOS +// The IPv4 address the system sends from to the internet: a UDP socket connected to an address beyond the local networks (192.0.2.1, a documentation +// address, takes the default route; connect sends nothing) has the route's source as its own address. 0 when there is no IPv4 route +static uint32_t net_route_source(void) { + int s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) return 0; + struct sockaddr_in to = {.sin_len = sizeof to, .sin_family = AF_INET, .sin_port = htons(9)}, me = {0}; socklen_t n = sizeof me; uint32_t a = 0; + to.sin_addr.s_addr = htonl(0xc0000201); + if (!connect(s, (struct sockaddr *)&to, sizeof to) && !getsockname(s, (struct sockaddr *)&me, &n) && me.sin_family == AF_INET) a = me.sin_addr.s_addr; + close(s); return a; +} +#endif +static int net_interface_get(net_interface *out) { + memset(out, 0, sizeof *out); +#ifdef DM_NET_TEST + if (g_test_interface_set) { *out = g_test_interface; return out->address ? 0 : -1; } +#endif + const char *name = getenv("DM_NETWORK_INTERFACE"); unsigned wanted = name && *name ? if_nametoindex(name) : 0; + if (name && *name && !wanted) return -1; + unsigned primary = net_route(wanted, &out->gateway); if (wanted) primary = wanted; + struct ifaddrs *list = NULL; if (getifaddrs(&list)) return -1; + int control = socket(AF_INET, SOCK_DGRAM, 0); +#if TARGET_OS_IOS + // getifaddrs ordering is not the preferred route on iOS. Automatic mode + // must not select a cellular/VPN entry before an available LAN adapter, + // then reject that same entry when preparing local discovery. Preserve a + // non-local fallback for online use when no eligible LAN is available. + dm_net_mode_t mode = dm_net_mode(); + // Online, iOS has no routing table to read (net_route), and getifaddrs lists cellular before Wi-Fi: the first adapter would tell the game its + // cellular address while it plays over Wi-Fi, and Pia offers that address to the other players for a direct link. So the first pass takes + // only the adapter the system sends from to the internet (net_route_source); the second, if none matched, any as before + uint32_t source = mode == DM_NET_NEXTENDO && !wanted ? net_route_source() : 0; + for (int pass = 0; pass < (mode == DM_NET_AUTO || source ? 2 : 1) && !out->address; pass++) { +#endif + for (struct ifaddrs *p = list; p; p = p->ifa_next) { + if (!p->ifa_addr || p->ifa_addr->sa_family != AF_INET || !(p->ifa_flags & IFF_UP) || (!wanted && (p->ifa_flags & IFF_LOOPBACK))) continue; + unsigned index = if_nametoindex(p->ifa_name); + if (!index || (primary && index != primary)) continue; + struct ifreq request = {0}; strlcpy(request.ifr_name, p->ifa_name, sizeof request.ifr_name); + unsigned type = control >= 0 && !ioctl(control, SIOCGIFFUNCTIONALTYPE, &request) ? + request.ifr_ifru.ifru_functional_type : IFRTYPE_FUNCTIONAL_UNKNOWN; + int local_link = type == IFRTYPE_FUNCTIONAL_WIFI_INFRA || type == IFRTYPE_FUNCTIONAL_WIRED; +#if TARGET_OS_IOS + // TN3179: BSD names such as en0 are not API. Ask the functional type. + if ((mode == DM_NET_LAN || mode == DM_NET_LDN || (mode == DM_NET_AUTO && pass == 0)) && + (!local_link || !(p->ifa_flags & IFF_BROADCAST) || (p->ifa_flags & IFF_POINTOPOINT))) continue; + if (source && pass == 0 && ((struct sockaddr_in *)p->ifa_addr)->sin_addr.s_addr != source) continue; +#endif + out->address = ((struct sockaddr_in *)p->ifa_addr)->sin_addr.s_addr; + if (p->ifa_netmask && p->ifa_netmask->sa_family == AF_INET) + out->mask = ((struct sockaddr_in *)p->ifa_netmask)->sin_addr.s_addr; + out->index = index; out->flags = p->ifa_flags; out->local_link = local_link; +#if TARGET_OS_IOS + static _Atomic unsigned told; // the adapter the game is told about, logged when it changes (which one, not its address) + if (mode == DM_NET_NEXTENDO && atomic_exchange(&told, index) != index) + fprintf(stderr, "[dm] net: online adapter %s (%s)%s\n", p->ifa_name, local_link ? "Wi-Fi or wired" : "cellular or other", + !source ? ", no route to the internet found" : pass ? ", none had the internet route's address" : ", the internet route's"); +#endif + break; + } +#if TARGET_OS_IOS + } +#endif + if (control >= 0) close(control); + freeifaddrs(list); + return out->address ? 0 : -1; +} +int dm_net_ipconfig(uint32_t *address, uint32_t *mask, uint32_t *gateway, uint32_t *dns1, uint32_t *dns2) { + uint32_t values[5] = {0}; uint32_t *outputs[] = {address, mask, gateway, dns1, dns2}; + for (int i = 0; i < 5; i++) if (outputs[i]) *outputs[i] = 0; + if (!dm_net_enabled()) return -1; + net_interface adapter; + if (net_interface_get(&adapter)) return -1; + values[0] = adapter.address; values[1] = adapter.mask; values[2] = adapter.gateway; + atomic_store(&g_net_broadcast, adapter.mask && (adapter.flags & IFF_BROADCAST) ? adapter.address | ~adapter.mask : 0); + atomic_store(&g_net_broadcast_known, 1); + if (!values[0]) return -1; + // DNS is advisory for LAN and never invented. macOS publishes the default resolver here; + // getaddrinfo itself continues to use the system resolver (including scoped DNS). + FILE *f = fopen("/etc/resolv.conf", "r"); + if (f) { char line[512], ip[64]; int n = 3; while (n < 5 && fgets(line, sizeof line, f)) if (sscanf(line, "nameserver %63s", ip) == 1 && inet_pton(AF_INET, ip, &values[n]) == 1) n++; fclose(f); } + for (int i = 0; i < 5; i++) if (outputs[i]) *outputs[i] = values[i]; return 0; +} + +// Error-only diagnostics for control operations. Record numeric ABI metadata, +// never option contents, socket addresses or application data. +static void net_control_trace(const char *operation, int guest, int result, int a, int b) { + int saved = errno; const char *flag = getenv("DM_NET_TRACE"); + if (result < 0 && flag && atoi(flag)) + fprintf(stderr,"net: %s guest_fd=%d result=%d errno=%d arg0=%d arg1=%d\n", operation, guest, result, t_net_errno, a, b); + errno = saved; +} +int dm_net_name(int guest, void *addr, unsigned *len, int peer) { + int result = net_name_impl(guest, addr, len, peer); + net_control_trace(peer ? "getpeername" : "getsockname", guest, result, 0, 0); + return result; +} +int dm_net_fcntl(int guest, int command, int flags) { + int result = net_fcntl_impl(guest, command, flags); + net_control_trace("fcntl", guest, result, command, flags); + return result; +} +int dm_net_sockopt(int guest, int level, int option, void *value, unsigned *len, int set) { + int result = net_sockopt_impl(guest, level, option, value, len, set); + net_control_trace(set ? "setsockopt" : "getsockopt", guest, result, level, option); + return result; +} diff --git a/dm/host/hle_network_clock.c b/dm/host/hle_network_clock.c new file mode 100644 index 0000000000..c3d2df6de0 --- /dev/null +++ b/dm/host/hle_network_clock.c @@ -0,0 +1,142 @@ +// The kernel's NTP discipline is a read-only source for whether the network +// clock is synchronized (IsAccuracySufficient, the availability task). A +// user/fixed clock is not evidence of synchronization. The clock's time itself +// is the host's (hle_time.c GetCurrentTime and now(), main's PR #2359): a Switch +// keeps its network clock from its last sync and reads it unsynchronized too. +// No daemon, system clock setting, entitlement or trust configuration is changed here. +#include "hle.h" +#include +#include +#include + +// Contended service locks release the caller's guest core, including during +// SDK callbacks below. HLE_FORCE_WAIT cannot be used around those callbacks. +void dm_host_lock(pthread_mutex_t *mutex); + +// PosixTime has whole-second resolution. Require both kernel error estimates +// to fit within one second; reject unsynchronized/leap/error states as well. +// XNU grows maxerror as its synchronization ages, so stale precision fails too. +#define NETWORK_CLOCK_ERROR_US 1000000L +static Result network_clock_read(int64_t *out) { + if (!out) return RES_FAIL; + struct ntptimeval value = {0}; + int saved_errno = errno; + int status = ntp_gettime(&value); + errno = saved_errno; + if (status != TIME_OK || value.time_state != TIME_OK || value.time.tv_sec <= 0 || + value.time.tv_nsec < 0 || value.time.tv_nsec >= 1000000000L || + value.maxerror < 0 || value.esterror < 0 || + value.maxerror > NETWORK_CLOCK_ERROR_US || value.esterror > NETWORK_CLOCK_ERROR_US) return RES_FAIL; + *out = (int64_t)value.time.tv_sec; + return RES_OK; +} +HLE_FORCE("_ZN2nn4time26StandardNetworkSystemClock20IsAccuracySufficientEv", "accuracy follows the kernel NTP state and its error bounds", unsigned, h_time_NetAccurate, void) { + int64_t value; + return network_clock_read(&value) == RES_OK; +} + +// SDK task sizes differ, so the guest object is an opaque registry key. Each +// task owns a separate SDK-created SystemEvent. All task operations serialize; +// the kernel query completes inline, without a made-up delay or network request. +typedef struct network_clock_task { + const void *object; + struct network_clock_task *next; + _Alignas(16) uint8_t event[0x100]; + uint64_t binding; + Result result; + int initialized, started, mode; +} network_clock_task; +static pthread_mutex_t clock_tasks_lock = PTHREAD_MUTEX_INITIALIZER; +static network_clock_task *clock_tasks; +static unsigned clock_task_count; +#define NETWORK_CLOCK_MAX_TASKS 256 + +static network_clock_task *clock_task_find(const void *object) { + for (network_clock_task *task = clock_tasks; task; task = task->next) if (task->object == object) return task; + return NULL; +} +static network_clock_task *clock_task_remove(const void *object) { + network_clock_task **link = &clock_tasks; + while (*link && (*link)->object != object) link = &(*link)->next; + network_clock_task *task = *link; + if (task) { *link = task->next; clock_task_count--; } + return task; +} +static void clock_task_release(network_clock_task *task) { + if (!task) return; + if (task->initialized) { + // Match the SDK that created the event; DestroySystemEvent closes its + // handles and removes the host binding before storage can be reused. + void (*destroy)(void *) = guest_sym("_ZN2nn2os18DestroySystemEventEPNS0_15SystemEventTypeE"); + destroy(task->event); + } + free(task); +} +static void clock_task_construct(void *object) { + if (!object) return; + dm_host_lock(&clock_tasks_lock); + network_clock_task *old = clock_task_remove(object); + if (clock_task_count < NETWORK_CLOCK_MAX_TASKS) { + network_clock_task *task = calloc(1, sizeof *task); + if (task) { task->object = object; task->result = RES_FAIL; task->next = clock_tasks; clock_tasks = task; clock_task_count++; } + } + pthread_mutex_unlock(&clock_tasks_lock); + clock_task_release(old); +} +HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTaskC1Ev", "owned network clock task and completion event", void, h_time_NcCtor, void *self) { clock_task_construct(self); } +HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTaskC2Ev", "owned network clock task and completion event, base constructor", void, h_time_NcCtor2, void *self) { clock_task_construct(self); } +static void clock_task_destroy(void *object) { + dm_host_lock(&clock_tasks_lock); + network_clock_task *task = clock_task_remove(object); + pthread_mutex_unlock(&clock_tasks_lock); + clock_task_release(task); +} +HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTaskD1Ev", "destroy only this task's SDK event and registry lifetime", void, h_time_NcDtor, void *self) { clock_task_destroy(self); } +HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTaskD2Ev", "destroy only this task's SDK event, base destructor", void, h_time_NcDtor2, void *self) { clock_task_destroy(self); } +HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTask10InitializeENS_2os14EventClearModeE", "initialize an unsignaled per-task SDK event with the requested clear mode", Result, h_time_NcInit, void *self, int mode) { + if (mode != 0 && mode != 1) return RES_FAIL; + dm_host_lock(&clock_tasks_lock); + network_clock_task *task = clock_task_find(self); + Result result = RES_FAIL; + if (task) { + if (!task->initialized) { + hle_bind_system_event(task->event, mode); + task->binding = hle_system_event_binding(task->event); + task->initialized = task->binding != 0; + task->mode = mode; + } + if (task->initialized && task->mode == mode) result = RES_OK; + } + pthread_mutex_unlock(&clock_tasks_lock); + return result; +} +HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTask9StartTaskEv", "complete after an actual kernel synchronization/precision query, retaining its real result", Result, h_time_NcStart, void *self) { + dm_host_lock(&clock_tasks_lock); + network_clock_task *task = clock_task_find(self); + Result result = RES_FAIL; + if (task && task->initialized) { + hle_clear_system_event(task->event); + int64_t value; + task->result = network_clock_read(&value); + task->started = 1; + // The captured binding identifies this event lifetime, not its address. + if (hle_signal_system_event_binding(task->binding)) result = RES_OK; + else task->result = RES_FAIL; + } + pthread_mutex_unlock(&clock_tasks_lock); + return result; +} +HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTask14GetFinishEventEv", "return this task's event without changing its completion state", void *, h_time_NcEvent, void *self) { + dm_host_lock(&clock_tasks_lock); + network_clock_task *task = clock_task_find(self); + void *event = task && task->initialized ? task->event : NULL; + pthread_mutex_unlock(&clock_tasks_lock); + return event; +} +HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTask9GetResultEv", "actual completed kernel query result; failure before starting or after destruction", Result, h_time_NcResult, void *self) { + dm_host_lock(&clock_tasks_lock); + network_clock_task *task = clock_task_find(self); + Result result = task && task->initialized && task->started ? task->result : RES_FAIL; + pthread_mutex_unlock(&clock_tasks_lock); + return result; +} diff --git a/dm/host/hle_nextendo_api_apple.m b/dm/host/hle_nextendo_api_apple.m new file mode 100644 index 0000000000..3ba84e2877 --- /dev/null +++ b/dm/host/hle_nextendo_api_apple.m @@ -0,0 +1,227 @@ +// Original bounded canonical-provider HTTPS transport for social/account data. +// This uses normal system TLS, with no cookies, redirects or alternate origins. +#import "nextendo_api_apple.h" +#include "nextendo_account.h" +#include +#include +#include +#include +#include +#include +#include + +void dm_guest_host_wait_begin(void); +void dm_guest_host_wait_end(void); +enum { API_MAX = 1024 * 1024 }; // an answer's size cap + +bool dm_nextendo_api_baas_namespace(const char *kind) { @autoreleasepool { + if (!kind || (strcmp(kind,"account") && strcmp(kind,"friends"))) return false; + const char *routes = getenv("DM_NEXTENDO_ROUTES"); + if (!routes || routes[0]!='/' || strnlen(routes,PATH_MAX)>=PATH_MAX) return false; + NSString *path = [[[NSString stringWithUTF8String:routes] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"manifest.json"]; + int fd=open(path.fileSystemRepresentation,O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK); if(fd<0)return false; + struct stat info; if (fstat(fd,&info) || !S_ISREG(info.st_mode) || + (info.st_uid!=geteuid() && info.st_uid!=0) || (info.st_mode&022) || info.st_size<=0 || info.st_size>65536) { close(fd); return false; } + NSMutableData *bytes=[NSMutableData dataWithLength:(NSUInteger)info.st_size]; size_t done=0; + while(done 40) return false; + for (NSUInteger i = 0; i < [key length]; i++) { unichar c = [key characterAtIndex:i]; if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_')) return false; } + return true; +} +static void me_fields(id document) { + if (![document isKindOfClass:NSDictionary.class]) return; + static dispatch_once_t once; dispatch_once(&once, ^{ + NSMutableArray *names = [NSMutableArray new]; + for (id key in [document allKeys]) { if (!plain_name(key)) continue; id value = document[key]; + if ([value isKindOfClass:NSDictionary.class]) { for (id inner in [value allKeys]) if (plain_name(inner)) [names addObject:[NSString stringWithFormat:@"%@.%@", key, inner]]; } + else [names addObject:key]; } + [names sortUsingSelector:@selector(compare:)]; NSString *line = [names componentsJoinedByString:@" "]; if (line.length > 800) line = [line substringToIndex:800]; + fprintf(stderr, "nextendo: account fields: %s\n", line.UTF8String); + }); +} +// /api/me, fetched once per signed-in account and shared by the readers below (BaaS ID, country, birthday). A failed fetch is remembered for +// 60 s, so a game that asks again while Nextendo does not answer does not wait on every call. With no identity to key it on, nothing is kept. nil while it fails +static NSDictionary *me_document(void) { + NSData *identity = dm_nextendo_api_identity(); + static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static NSData *cached_identity; static NSDictionary *cached; static double failed_at; + double now = NSDate.date.timeIntervalSince1970; + pthread_mutex_lock(&mutex); + bool same = identity && [cached_identity isEqual:identity]; NSDictionary *known = same ? cached : nil; bool resting = same && !known && now - failed_at < 60; + pthread_mutex_unlock(&mutex); + if (known || resting) return known; + uint8_t *buffer=malloc(API_MAX); if (!buffer) return nil; size_t size=0; + uint32_t result=dm_nextendo_api_request("me",NULL,0,buffer,API_MAX,&size); + NSData *bytes=result?nil:[NSData dataWithBytes:buffer length:size]; free(buffer); + id document=bytes?[NSJSONSerialization JSONObjectWithData:bytes options:0 error:nil]:nil; + if (![document isKindOfClass:NSDictionary.class]) document=nil; else me_fields(document); + if (identity && [identity isEqual:dm_nextendo_api_identity()]) { pthread_mutex_lock(&mutex); cached_identity=identity; cached=document; failed_at=document?0:now; pthread_mutex_unlock(&mutex); } + return document; +} + +uint32_t dm_nextendo_api_baas_id(uint64_t *output) { @autoreleasepool { + if (!output) return DM_ACCOUNT_FAIL; *output = 0; + NSData *identity = dm_nextendo_api_identity(); if (!identity) return DM_ACCOUNT_FAIL; + static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static NSData *cached_identity; static uint64_t cached_id; + pthread_mutex_lock(&mutex); uint64_t existing = [cached_identity isEqual:identity] ? cached_id : 0; pthread_mutex_unlock(&mutex); + if (existing) { *output=existing; return 0; } + NSDictionary *document=me_document(); + id field=document[@"nsa"]; + if (![field isKindOfClass:NSString.class] || ![field length] || [field length]>16 || ![identity isEqual:dm_nextendo_api_identity()]) return DM_ACCOUNT_FAIL; + uint64_t value=0; + for (NSUInteger i=0;i<[field length];i++) { unichar c=[field characterAtIndex:i]; unsigned digit; + if (c>='0' && c<='9') digit=c-'0'; else if(c>='a' && c<='f') digit=c-'a'+10; else if(c>='A' && c<='F') digit=c-'A'+10; else return DM_ACCOUNT_FAIL; + value=(value<<4)|digit; + } + if (!value) return DM_ACCOUNT_FAIL; + pthread_mutex_lock(&mutex); cached_identity=identity; cached_id=value; pthread_mutex_unlock(&mutex); + *output=value; return 0; +} } + +// The Nextendo account's country, two capital letters from /api/me's account.country (the player picks it at sign-up), else "": never a guessed one. +// Ryujinx-Nextendo (NextendoCountry.cs) answers CachedNintendoAccountInfo::GetCountry from the same field (me_document) +uint32_t dm_nextendo_account_country(char output[3]) { @autoreleasepool { + if (!output) return DM_ACCOUNT_FAIL; output[0]=0; + NSDictionary *document=me_document(); if (!document) return DM_ACCOUNT_FAIL; + id account=document[@"account"]; + id field=[account isKindOfClass:NSDictionary.class]?account[@"country"]:nil; + NSString *country=[field isKindOfClass:NSString.class]?[field stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet].uppercaseString:@""; + char code[3]={0}; + if (country.length==2) { unichar a=[country characterAtIndex:0], b=[country characterAtIndex:1]; if (a>='A' && a<='Z' && b>='A' && b<='Z') { code[0]=(char)a; code[1]=(char)b; } } + memcpy(output,code,3); return 0; +} } + +// The Nextendo account's birthday as YYYY-MM-DD, else "". Which /api/me field carries it is not confirmed yet (the account fields line above will show it): the +// usual names are tried, in account and at the top level, and only a value that starts with a plain date is taken (a time after it is dropped). From me_document +uint32_t dm_nextendo_account_birthday(char output[11]) { @autoreleasepool { + if (!output) return DM_ACCOUNT_FAIL; output[0]=0; + NSDictionary *document=me_document(); if (!document) return DM_ACCOUNT_FAIL; + id account=document[@"account"]; + char date[11]={0}; + for (id place in @[account ?: NSNull.null, document ?: NSNull.null]) { + if (![place isKindOfClass:NSDictionary.class] || date[0]) continue; + for (NSString *name in @[@"birthday", @"birth_date", @"birthdate", @"date_of_birth"]) { + id field=place[name]; if (![field isKindOfClass:NSString.class] || [field length]<10) continue; + const char *text=[[field substringToIndex:10] UTF8String]; bool plain=text && strlen(text)==10 && text[4]=='-' && text[7]=='-'; + for (int i=0;plain && i<10;i++) if (i!=4 && i!=7 && (text[i]<'0' || text[i]>'9')) plain=false; + if (plain && ([field length]==10 || [field characterAtIndex:10]=='T' || [field characterAtIndex:10]==' ')) { memcpy(date,text,11); break; } + } + } + memcpy(output,date,11); return 0; +} } + +@interface DmNextendoApiTransfer : NSObject +@property(nonatomic) NSLock *lock; +@property(nonatomic) NSMutableData *data; +@property(nonatomic) dispatch_semaphore_t completed; +@property(nonatomic) BOOL failed; +@property(nonatomic) NSInteger status; +@property(nonatomic) NSUInteger limit; // the answer's size cap; 0 keeps only the status and drops the answer +@end +@implementation DmNextendoApiTransfer +- (instancetype)init { + if ((self = [super init])) { _lock = [NSLock new]; _data = [NSMutableData new]; _completed = dispatch_semaphore_create(0); } + return self; +} +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completion { + (void)session; (void)task; (void)response; (void)request; + [self.lock lock]; self.failed = YES; [self.lock unlock]; completion(nil); +} +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition))completion { + (void)session; (void)task; + [self.lock lock]; + self.failed = self.failed || ![response isKindOfClass:NSHTTPURLResponse.class] || (self.limit && response.expectedContentLength > (long long)self.limit); + self.status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0; + BOOL failed = self.failed; [self.lock unlock]; completion(failed ? NSURLSessionResponseCancel : NSURLSessionResponseAllow); +} +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data { + (void)session; [self.lock lock]; + if (self.limit && data.length > self.limit - self.data.length) self.failed = YES; + else if (self.limit && !self.failed) [self.data appendData:data]; + BOOL failed = self.failed; [self.lock unlock]; if (failed) [task cancel]; +} +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { + (void)session; (void)task; [self.lock lock]; self.failed = self.failed || error != nil; [self.lock unlock]; + dispatch_semaphore_signal(self.completed); +} +@end + +// One session for every request, so the TLS connection to nextendo.network stays open between them (a session per request made each one a new +// handshake). Each task has its own delegate (NSURLSessionTask.delegate, iOS 15 / macOS 12), which keeps that answer and its size cap. +// Ephemeral, with no cookies, credentials or cache: every answer comes from the server +static NSURLSession *api_session(void) { + static NSURLSession *session; static dispatch_once_t once; + dispatch_once(&once, ^{ + NSURLSessionConfiguration *configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration; + configuration.HTTPCookieStorage = nil; configuration.HTTPShouldSetCookies = NO; configuration.URLCredentialStorage = nil; + configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData; configuration.timeoutIntervalForResource = 15; + session = [NSURLSession sessionWithConfiguration:configuration]; + }); + return session; +} + +#ifdef DM_NEXTENDO_API_TEST +static dm_nextendo_api_transport test_transport; +void dm_nextendo_api_test_transport(dm_nextendo_api_transport transport) { test_transport = transport; } +#endif + +uint32_t dm_nextendo_api_request(const char *resource, const uint8_t *body, size_t body_size, + uint8_t *output, size_t capacity, size_t *output_size) { @autoreleasepool { + if (output_size) *output_size = 0; + if (!resource || !output_size || body_size > 4096 || (body_size && !body)) return DM_ACCOUNT_FAIL; + // presence is posted; friends, me and profile are only read + BOOL presence = !strcmp(resource,"presence"); + if (!presence && strcmp(resource,"friends") && strcmp(resource,"me") && strcmp(resource,"profile")) return DM_ACCOUNT_FAIL; + if ((presence && !body_size) || (!presence && body_size)) return DM_ACCOUNT_FAIL; + if (!output || !capacity || capacity > API_MAX) return DM_ACCOUNT_FAIL; + NSString *proof = dm_nextendo_api_bearer(resource); if (!proof.length) return DM_ACCOUNT_FAIL; + NSString *authorization = [@"Bearer " stringByAppendingString:proof]; + NSString *resourceName = [NSString stringWithUTF8String:resource]; if (!resourceName) return DM_ACCOUNT_FAIL; + NSString *url = [@"https://nextendo.network/api/" stringByAppendingString:resourceName]; + NSString *method = presence ? @"POST" : @"GET"; +#ifdef DM_NEXTENDO_API_TEST + if (test_transport) { + size_t size = 0; unsigned status = 0; + if (!test_transport(url.UTF8String,method.UTF8String,authorization.UTF8String,body,body_size,output,capacity,&size,&status) || + status < 200 || status >= 300 || size > capacity) return DM_ACCOUNT_FAIL; + *output_size = size; return 0; + } +#endif + NSURL *endpoint = [NSURL URLWithString:url]; if (!endpoint) return DM_ACCOUNT_FAIL; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:endpoint]; + request.HTTPMethod = method; request.timeoutInterval = 12; + [request setValue:authorization forHTTPHeaderField:@"Authorization"]; + [request setValue:@"nxnative" forHTTPHeaderField:@"User-Agent"]; + [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; + if (body_size) { request.HTTPBody = [NSData dataWithBytes:body length:body_size]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; } + DmNextendoApiTransfer *transfer = [DmNextendoApiTransfer new]; transfer.limit = capacity; + NSURLSessionDataTask *task = [api_session() dataTaskWithRequest:request]; task.delegate = transfer; [task resume]; + dm_guest_host_wait_begin(); long timed_out = dispatch_semaphore_wait(transfer.completed,dispatch_time(DISPATCH_TIME_NOW,15 * NSEC_PER_SEC)); dm_guest_host_wait_end(); + if (timed_out) { [task cancel]; return DM_ACCOUNT_FAIL; } + [transfer.lock lock]; + BOOL valid = !transfer.failed && transfer.status >= 200 && transfer.status < 300 && transfer.data.length <= capacity; + if (valid) { memcpy(output,transfer.data.bytes,transfer.data.length); *output_size = transfer.data.length; } + NSInteger status = transfer.status; + [transfer.lock unlock]; + // A refused request is logged once per resource and status (no body, no token), so a device log shows whether Nextendo takes this + // bearer for the resource: 401 or 403 here would mean it wants another kind of token + if (!valid) { + static pthread_mutex_t seen_lock = PTHREAD_MUTEX_INITIALIZER; static NSMutableSet *seen; + NSString *key = [NSString stringWithFormat:@"%@ %ld", resourceName, (long)status]; + pthread_mutex_lock(&seen_lock); if (!seen) seen = [NSMutableSet new]; BOOL first = ![seen containsObject:key]; [seen addObject:key]; pthread_mutex_unlock(&seen_lock); + NSString *what = status ? [NSString stringWithFormat:@"HTTP %ld", (long)status] : @"nothing (no connection, or an oversized answer)"; + if (first) fprintf(stderr, "[dm] [RED] nextendo: /api/%s answered %s\n", resource, what.UTF8String); + } + return valid ? 0 : DM_ACCOUNT_FAIL; +} } diff --git a/dm/host/hle_nextendo_apple.m b/dm/host/hle_nextendo_apple.m new file mode 100644 index 0000000000..0694418d75 --- /dev/null +++ b/dm/host/hle_nextendo_apple.m @@ -0,0 +1,249 @@ +// Native Nextendo credentials and account requests. This bridge never mints an nx2 +// proof: its HMAC is checked by Nextendo, while the host checks identity and expiry. +#import +#import +#include +#include "nextendo_account.h" +#import "nextendo_api_apple.h" +#include "net_socket.h" +#include +#include +#include +#include + +void dm_guest_host_wait_begin(void); +void dm_guest_host_wait_end(void); +int hle_signal_system_event_binding(uint64_t binding); + +static _Atomic(dm_nextendo_credential_provider) credentialProvider; +static pthread_mutex_t accountLock = PTHREAD_MUTEX_INITIALIZER; +static NSString *explicitVersion; +static NSData *cachedFingerprint; +static NSString *cachedVersion; +static NSData *cachedToken; +static NSTimeInterval cachedExpiry; +static SecKeyRef signingKey; +static NSData *publicSigningKey; +static pthread_once_t signingOnce = PTHREAD_ONCE_INIT; +static BOOL enabled(void) { return dm_net_nextendo_enabled(); } +@interface DmNextendoCredential : NSObject +@property(nonatomic) uint64_t pid; +@property(nonatomic) NSString *username; +@property(nonatomic) NSString *token; +@property(nonatomic) NSTimeInterval expiry; +@end +@implementation DmNextendoCredential +@end + +static NSString *base64url(NSData *data) { + NSString *value = [[data base64EncodedStringWithOptions:0] stringByReplacingOccurrencesOfString:@"+" withString:@"-"]; + return [[value stringByReplacingOccurrencesOfString:@"/" withString:@"_"] stringByReplacingOccurrencesOfString:@"=" withString:@""]; +} +static NSData *decode_base64url(NSString *value) { + if (![value isKindOfClass:NSString.class] || !value.length) return nil; + for (NSUInteger i = 0; i < value.length; i++) { unichar c = [value characterAtIndex:i]; if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_')) return nil; } + NSString *normal = [[value stringByReplacingOccurrencesOfString:@"-" withString:@"+"] stringByReplacingOccurrencesOfString:@"_" withString:@"/"]; + normal = [normal stringByPaddingToLength:(normal.length + 3) & ~(NSUInteger)3 withString:@"=" startingAtIndex:0]; + NSData *data = [[NSData alloc] initWithBase64EncodedString:normal options:0]; return data && [base64url(data) isEqualToString:value] ? data : nil; +} +static BOOL unsigned_decimal(NSString *text, uint64_t *out) { + if (![text isKindOfClass:NSString.class] || !text.length || text.length > 20) return NO; + uint64_t value = 0; + for (NSUInteger i = 0; i < text.length; i++) { unichar c = [text characterAtIndex:i]; if (c < '0' || c > '9' || value > (UINT64_MAX - (c - '0')) / 10) return NO; value = value * 10 + c - '0'; } + if (!value) return NO; *out = value; return YES; +} +static BOOL number(id value) { return [value isKindOfClass:NSNumber.class] && CFGetTypeID((__bridge CFTypeRef)value) != CFBooleanGetTypeID(); } +// The embedding host owns local storage/authorization. No fallback reads occur. +static NSData *read_credentials(void) { + dm_nextendo_credential_provider provider = atomic_load(&credentialProvider); + if (!provider) return nil; + NSMutableData *data = [NSMutableData dataWithLength:65536]; size_t size = 0; + if (!data || !provider(data.mutableBytes, data.length, &size) || !size || size > data.length) return nil; + data.length = size; return data; +} +// Nextendo's clock less this device's; hle_nextendo_login_apple.m has the strong definition, a host without it judges by its own clock +__attribute__((weak)) double dm_nextendo_clock_offset(void) { return 0; } +static DmNextendoCredential *decode_credential(NSData *data) { + if (!data.length || data.length > 65536) return nil; + id decoded = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; if (![decoded isKindOfClass:NSDictionary.class]) return nil; NSDictionary *json = decoded; + if (!number(json[@"schema_version"]) || [json[@"schema_version"] doubleValue] != 1 || ![json[@"token_kind"] isEqual:@"nex"]) return nil; + NSString *token = json[@"token"]; if (![token isKindOfClass:NSString.class] || !token.length || [token lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 16384) return nil; + for (NSUInteger i = 0; i < token.length; i++) { unichar c = [token characterAtIndex:i]; if (c <= 32 || c >= 127) return nil; } + NSArray *parts = [token componentsSeparatedByString:@"."]; if (parts.count != 3 || ![parts[0] isEqual:@"nx2"]) return nil; + NSData *payload = decode_base64url(parts[1]), *signature = decode_base64url(parts[2]); if (!payload || signature.length != 32) return nil; + NSString *text = [[NSString alloc] initWithData:payload encoding:NSUTF8StringEncoding]; NSArray *claims = [text componentsSeparatedByString:@"."]; if (claims.count < 3) return nil; + uint64_t pid, expiry; if (!unsigned_decimal(claims.firstObject, &pid) || !unsigned_decimal(claims.lastObject, &expiry) || expiry > INT64_MAX) return nil; + NSString *username = [[claims subarrayWithRange:NSMakeRange(1, claims.count - 2)] componentsJoinedByString:@"."]; if (!username.length || username.length > 128) return nil; + id identity = json[@"identity"]; if (![identity isKindOfClass:NSDictionary.class] || !number(identity[@"pid"])) return nil; + uint64_t storedPid; if (!unsigned_decimal([identity[@"pid"] stringValue], &storedPid) || storedPid != pid || ![identity[@"username"] isEqual:username]) return nil; + NSTimeInterval now = NSDate.date.timeIntervalSince1970 + dm_nextendo_clock_offset(); // Nextendo's time: the record's are + if (!number(json[@"created_at"]) || !number(json[@"expires_at"])) return nil; + double created = [json[@"created_at"] doubleValue], until = [json[@"expires_at"] doubleValue]; + if (!isfinite(created) || !isfinite(until) || created <= 0 || created > now + 60 || until <= now || until <= created || until > (double)expiry) return nil; + id scopes = json[@"scopes"]; if (![scopes isKindOfClass:NSArray.class] || [scopes count] > 128) return nil; for (id scope in scopes) if (![scope isKindOfClass:NSString.class] || [scope length] > 256) return nil; + DmNextendoCredential *c = [DmNextendoCredential new]; c.pid = pid; c.username = username; c.token = token; c.expiry = until; return c; +} +static DmNextendoCredential *credential(void) { + return enabled() ? decode_credential(read_credentials()) : nil; +} +void dm_nextendo_set_credential_provider(dm_nextendo_credential_provider provider) { + atomic_store(&credentialProvider, provider); + pthread_mutex_lock(&accountLock); cachedFingerprint = nil; cachedToken = nil; cachedVersion = nil; cachedExpiry = 0; pthread_mutex_unlock(&accountLock); +} +void dm_nextendo_set_game_version(const char *version) { + NSString *value = version ? [NSString stringWithUTF8String:version] : nil; + pthread_mutex_lock(&accountLock); explicitVersion = value; cachedToken = nil; cachedVersion = nil; pthread_mutex_unlock(&accountLock); +} +uint32_t dm_nextendo_account_available(uint8_t *out) { @autoreleasepool { + if (!out) return DM_ACCOUNT_FAIL; *out = 0; + if (enabled()) *out = credential() != nil; + return 0; +} } +uint32_t dm_nextendo_account_id(uint64_t *out) { @autoreleasepool { + if (!out) return DM_ACCOUNT_FAIL; *out = 0; DmNextendoCredential *c = credential(); if (!c) return DM_ACCOUNT_FAIL; + if (dm_nextendo_api_baas_namespace("account")) return dm_nextendo_api_baas_id(out); + *out = c.pid; return 0; +} } +uint32_t dm_nextendo_account_ensure(void) { @autoreleasepool { return credential() ? 0 : DM_ACCOUNT_FAIL; } } +uint32_t dm_nextendo_account_username(char out[33]) { @autoreleasepool { + if (!out) return DM_ACCOUNT_FAIL; memset(out, 0, 33); DmNextendoCredential *c = credential(); if (!c) return DM_ACCOUNT_FAIL; + const char *name = c.username.UTF8String; size_t n = name ? strlen(name) : 0; + if (n > 32) { n = 32; while (n && ((unsigned char)name[n] & 0xc0) == 0x80) n--; } // whole UTF-8 characters only + if (!n) return DM_ACCOUNT_FAIL; memcpy(out, name, n); return 0; +} } +// Host-only API authorization. Never serialized into a game bundle or HLE output. Nextendo's routes differ in the token they take, as +// nextendo.network answered on 2026-11-15 (each route asked with both tokens): the sign-in's OAuth access token for me, friends and presence; +// the nx2 game token for online-status. /api/profile took neither: it needs the profil scope, which the sign-in asks for since 2026-11-15 (a sign-in from before then has to be redone). A history write is +// refused to both (only Nextendo's own emulator may write play time), so the host sends none. The access token goes first where it is taken, the nx2 token +// without one. hle_nextendo_login_apple.m has the strong dm_nextendo_login_access; a host without it has no access token +__attribute__((weak)) NSString *dm_nextendo_login_access(void) { return nil; } +NSString *dm_nextendo_api_bearer(const char *resource) { + DmNextendoCredential *c = credential(); if (!c) return nil; + bool takes_game = resource && !strcmp(resource, "online-status"); + NSString *access = takes_game ? nil : dm_nextendo_login_access(); return access.length ? access : c.token; +} +NSData *dm_nextendo_api_identity(void) { + DmNextendoCredential *c = credential(); if (!c) return nil; + NSData *bytes = [c.token dataUsingEncoding:NSUTF8StringEncoding]; uint8_t digest[CC_SHA256_DIGEST_LENGTH]; + CC_SHA256(bytes.bytes, (CC_LONG)bytes.length, digest); return [NSData dataWithBytes:digest length:sizeof digest]; +} + +// Token construction is deliberately separate from credential validation. The nx2 +// proof is never substituted with a local signature or an OAuth access token. +static void initialize_signing_key(void) { + NSDictionary *attributes = @{(__bridge id)kSecAttrKeyType:(__bridge id)kSecAttrKeyTypeRSA, + (__bridge id)kSecAttrKeySizeInBits:@2048, (__bridge id)kSecPrivateKeyAttrs:@{(__bridge id)kSecAttrIsPermanent:@NO}}; + CFErrorRef error = NULL; dm_guest_host_wait_begin(); signingKey = SecKeyCreateRandomKey((__bridge CFDictionaryRef)attributes, &error); dm_guest_host_wait_end(); if (error) CFRelease(error); + if (!signingKey) return; SecKeyRef publicKey = SecKeyCopyPublicKey(signingKey); + if (publicKey) { publicSigningKey = CFBridgingRelease(SecKeyCopyExternalRepresentation(publicKey, NULL)); CFRelease(publicKey); } +} +uint32_t dm_nextendo_copy_public_signing_key(void *buffer, uint64_t capacity, uint64_t *size) { @autoreleasepool { + if (!size) return DM_ACCOUNT_FAIL; *size = 0; pthread_once(&signingOnce, initialize_signing_key); + if (!publicSigningKey) return DM_ACCOUNT_FAIL; *size = publicSigningKey.length; if (!buffer || capacity < publicSigningKey.length) return DM_ACCOUNT_FAIL; + memcpy(buffer, publicSigningKey.bytes, publicSigningKey.length); return 0; +} } +static NSString *tokenSub, *tokenDevice, *tokenDeviceAccount; // under accountLock +static NSString *random_hex(size_t count) { + uint8_t bytes[32]; if (count > sizeof bytes || SecRandomCopyBytes(kSecRandomDefault, count, bytes) != errSecSuccess) return nil; + NSMutableString *hex = [NSMutableString stringWithCapacity:count * 2]; for (size_t i = 0; i < count; i++) [hex appendFormat:@"%02x", bytes[i]]; return hex; +} +static NSData *id_token(DmNextendoCredential *c) { + NSTimeInterval now = NSDate.date.timeIntervalSince1970 + dm_nextendo_clock_offset(); NSData *proof = [c.token dataUsingEncoding:NSASCIIStringEncoding]; unsigned char hash[CC_SHA256_DIGEST_LENGTH]; CC_SHA256(proof.bytes, (CC_LONG)proof.length, hash); + NSData *fingerprint = [NSData dataWithBytes:hash length:sizeof hash]; pthread_mutex_lock(&accountLock); + NSString *version = explicitVersion ?: [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; + if (![version isKindOfClass:NSString.class] || !version.length || version.length > 64 || ![version canBeConvertedToEncoding:NSASCIIStringEncoding]) { pthread_mutex_unlock(&accountLock); return nil; } + if (cachedToken && [cachedFingerprint isEqual:fingerprint] && [cachedVersion isEqual:version] && cachedExpiry > now && cachedExpiry <= c.expiry) { NSData *token = cachedToken; pthread_mutex_unlock(&accountLock); return token; } + pthread_once(&signingOnce, initialize_signing_key); if (!signingKey || !publicSigningKey) { pthread_mutex_unlock(&accountLock); return nil; } + uint64_t expiry = (uint64_t)floor(MIN(c.expiry, now + 3 * 3600)); if ((double)expiry <= now) { pthread_mutex_unlock(&accountLock); return nil; } + // The BaaS id_token shape Nextendo's own clients send (Ryujinx-Nextendo ManagerServer.GenerateIdToken, Mush8 nextendo.rs id_token): the + // header's kid and typ, Nintendo BaaS's issuer, audience and certificate URL, random user / device / device-account IDs (fixed for the + // process) and "hm", the online-membership claim (Ryujinx-Nextendo: Splatoon 2 reads it locally before it goes online). The server authenticates the nnex proof, not + // this signature (Mush8 sends random bytes there); Wonder's token has no app_id (Ryujinx sends one only for the NSO Classics, Scarlet and MH Rise JP/HK) + if (!tokenSub) { tokenSub = random_hex(16); tokenDevice = random_hex(16); tokenDeviceAccount = random_hex(16); } + if (!tokenSub || !tokenDevice || !tokenDeviceAccount) { tokenSub = nil; pthread_mutex_unlock(&accountLock); return nil; } + NSString *baas = @"https://e0d67c509fb203858ebcb2fe3f88c2aa.baas.nintendo.com"; NSNumber *issued = @((uint64_t)floor(now)); + NSDictionary *header = @{@"alg":@"RS256", @"typ":@"id_token", @"kid":@"nextendo-baas-key-1"}; + NSDictionary *claims = @{@"sub":tokenSub, @"aud":@"ed9e2f05d286f7b8", @"iss":baas, @"iat":issued, @"nbf":issued, @"exp":@(expiry), + @"jku":[baas stringByAppendingString:@"/1.0.0/certificates"], @"jti":NSUUID.UUID.UUIDString.lowercaseString, @"di":tokenDevice, @"sn":@"XAW10000000000", + @"bs:did":tokenDeviceAccount, @"hm":@YES, @"nnex":c.token, @"tv":version}; + NSJSONWritingOptions json = NSJSONWritingSortedKeys | NSJSONWritingWithoutEscapingSlashes; + NSData *headerData = [NSJSONSerialization dataWithJSONObject:header options:json error:nil], *claimData = [NSJSONSerialization dataWithJSONObject:claims options:json error:nil]; + if (!headerData || !claimData) { pthread_mutex_unlock(&accountLock); return nil; } + NSString *message = [NSString stringWithFormat:@"%@.%@", base64url(headerData), base64url(claimData)]; NSData *bytes = [message dataUsingEncoding:NSASCIIStringEncoding]; + CFErrorRef error = NULL; dm_guest_host_wait_begin(); NSData *signature = CFBridgingRelease(SecKeyCreateSignature(signingKey, kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA256, (__bridge CFDataRef)bytes, &error)); dm_guest_host_wait_end(); if (error) CFRelease(error); + if (!signature) { pthread_mutex_unlock(&accountLock); return nil; } + NSData *token = [[NSString stringWithFormat:@"%@.%@", message, base64url(signature)] dataUsingEncoding:NSASCIIStringEncoding]; + cachedFingerprint = fingerprint; cachedVersion = version; cachedToken = token; cachedExpiry = (NSTimeInterval)expiry; pthread_mutex_unlock(&accountLock); return token; +} +uint32_t dm_nextendo_account_load_token(uint64_t *size, char *buffer, uint64_t capacity) { @autoreleasepool { + if (!size) return DM_ACCOUNT_FAIL; *size = 0; if (!buffer && capacity) return DM_ACCOUNT_FAIL; + DmNextendoCredential *c = credential(); if (!c) return DM_ACCOUNT_FAIL; NSData *token = id_token(c); if (!token) return DM_ACCOUNT_FAIL; + *size = token.length; if (!buffer || capacity <= token.length) return DM_ACCOUNT_FAIL; memcpy(buffer, token.bytes, token.length); buffer[token.length] = 0; return 0; +} } + +@interface DmNextendoAsync : NSObject +@property(nonatomic) NSLock *lock; +@property(nonatomic) uint64_t lifetime, generation; +@property(nonatomic) BOOL started, done, destroyed; +@property(nonatomic) uint32_t result; +@property(nonatomic) NSMutableArray *events; +@end +@implementation DmNextendoAsync +@end +static NSMutableDictionary *requests; +static pthread_once_t requestsOnce = PTHREAD_ONCE_INIT; +static pthread_mutex_t requestsLock = PTHREAD_MUTEX_INITIALIZER; +static uint64_t nextLifetime; +static void requests_init(void) { requests = [NSMutableDictionary new]; } +static NSValue *request_key(void *object) { return [NSValue valueWithPointer:object]; } +static DmNextendoAsync *request(void *object) { pthread_once(&requestsOnce, requests_init); pthread_mutex_lock(&requestsLock); DmNextendoAsync *state = requests[request_key(object)]; pthread_mutex_unlock(&requestsLock); return state; } +static DmNextendoAsync *new_request(void) { DmNextendoAsync *state = [DmNextendoAsync new]; state.lock = [NSLock new]; state.events = [NSMutableArray new]; state.result = DM_ACCOUNT_FAIL; return state; } +static void finish_events(NSArray *events) { for (NSNumber *binding in events) hle_signal_system_event_binding(binding.unsignedLongLongValue); } +static void destroy_request(DmNextendoAsync *state) { if (!state) return; [state.lock lock]; state.destroyed = YES; state.generation++; state.done = YES; state.result = DM_ACCOUNT_FAIL; NSArray *events = state.events.copy; [state.lock unlock]; finish_events(events); } +void dm_nextendo_async_construct(void *object) { @autoreleasepool { + if (!object) return; DmNextendoAsync *state = new_request(); if (!state) return; pthread_once(&requestsOnce, requests_init); pthread_mutex_lock(&requestsLock); + DmNextendoAsync *old = requests[request_key(object)]; if (requests.count < 512 || old) { state.lifetime = ++nextLifetime; requests[request_key(object)] = state; } pthread_mutex_unlock(&requestsLock); destroy_request(old); +} } +void dm_nextendo_async_destroy(void *object) { @autoreleasepool { if (!object) return; pthread_once(&requestsOnce, requests_init); pthread_mutex_lock(&requestsLock); DmNextendoAsync *state = requests[request_key(object)]; [requests removeObjectForKey:request_key(object)]; pthread_mutex_unlock(&requestsLock); destroy_request(state); } } +void *dm_nextendo_async_move(void *object, void *source) { @autoreleasepool { + if (!object || !source || object == source) return object; pthread_once(&requestsOnce, requests_init); pthread_mutex_lock(&requestsLock); + DmNextendoAsync *old = requests[request_key(object)], *state = requests[request_key(source)]; [requests removeObjectForKey:request_key(source)]; requests[request_key(object)] = state; pthread_mutex_unlock(&requestsLock); destroy_request(old); return object; +} } +void dm_nextendo_async_swap(void *object, void *other) { @autoreleasepool { + if (!object || !other || object == other) return; pthread_once(&requestsOnce, requests_init); pthread_mutex_lock(&requestsLock); DmNextendoAsync *first = requests[request_key(object)], *second = requests[request_key(other)]; requests[request_key(object)] = second; requests[request_key(other)] = first; pthread_mutex_unlock(&requestsLock); +} } +bool dm_nextendo_async_valid(void *object) { @autoreleasepool { DmNextendoAsync *state = request(object); if (!state) return false; [state.lock lock]; bool valid = state.started && !state.destroyed; [state.lock unlock]; return valid; } } +uint64_t dm_nextendo_async_lifetime(void *object) { @autoreleasepool { DmNextendoAsync *state = request(object); if (!state) return 0; [state.lock lock]; uint64_t id = state.started && !state.destroyed ? state.lifetime : 0; [state.lock unlock]; return id; } } +uint32_t dm_nextendo_async_attach(void *object, uint64_t lifetime, uint64_t binding) { @autoreleasepool { + if (!object || !lifetime || !binding) return DM_ACCOUNT_FAIL; DmNextendoAsync *state = request(object); if (!state) return DM_ACCOUNT_FAIL; [state.lock lock]; + if (state.lifetime != lifetime || state.destroyed || !state.started || state.events.count >= 64) { [state.lock unlock]; return DM_ACCOUNT_FAIL; } + if (![state.events containsObject:@(binding)]) [state.events addObject:@(binding)]; BOOL done = state.done; [state.lock unlock]; if (done) hle_signal_system_event_binding(binding); return 0; +} } +uint32_t dm_nextendo_async_execute(void *object, dm_nextendo_async_operation operation, const void *context) { @autoreleasepool { + if (!object || !operation || !enabled()) return DM_ACCOUNT_FAIL; + DmNextendoAsync *state = request(object); if (!state) { dm_nextendo_async_construct(object); state = request(object); } if (!state) return DM_ACCOUNT_FAIL; + [state.lock lock]; BOOL replacing = state.started && state.done && !state.destroyed; [state.lock unlock]; + if (replacing) { + DmNextendoAsync *fresh = new_request(); if (!fresh) return DM_ACCOUNT_FAIL; + pthread_mutex_lock(&requestsLock); if (requests[request_key(object)] != state) { pthread_mutex_unlock(&requestsLock); return DM_ACCOUNT_FAIL; } + fresh.lifetime = ++nextLifetime; requests[request_key(object)] = fresh; pthread_mutex_unlock(&requestsLock); destroy_request(state); state = fresh; + } + [state.lock lock]; if (state.started || state.destroyed) { [state.lock unlock]; return DM_ACCOUNT_FAIL; } state.started = YES; uint64_t generation = ++state.generation; [state.lock unlock]; + uint32_t result = operation(context); + [state.lock lock]; NSArray *events = nil; if (!state.destroyed && state.generation == generation) { state.result = result; state.done = YES; events = state.events.copy; } [state.lock unlock]; finish_events(events); + return enabled() ? 0 : DM_ACCOUNT_FAIL; +} } +static uint32_t ensure_token_operation(const void *context) { + (void)context; DmNextendoCredential *c = credential(); return c && id_token(c) ? 0 : DM_ACCOUNT_FAIL; +} +uint32_t dm_nextendo_async_ensure(void *object) { return dm_nextendo_async_execute(object, ensure_token_operation, NULL); } +uint32_t dm_nextendo_async_cancel(void *object) { @autoreleasepool { + DmNextendoAsync *state = request(object); if (!state) return DM_ACCOUNT_FAIL; [state.lock lock]; if (!state.started || state.destroyed) { [state.lock unlock]; return DM_ACCOUNT_FAIL; } + NSArray *events = nil; if (!state.done) { state.generation++; state.done = YES; state.result = DM_ACCOUNT_FAIL; events = state.events.copy; } [state.lock unlock]; finish_events(events); return 0; +} } +uint32_t dm_nextendo_async_done(void *object, uint8_t *out) { @autoreleasepool { + if (!out) return DM_ACCOUNT_FAIL; *out = 0; DmNextendoAsync *state = request(object); if (!state) return DM_ACCOUNT_FAIL; [state.lock lock]; uint32_t result = !state.started || state.destroyed ? DM_ACCOUNT_FAIL : 0; if (!result) *out = state.done; [state.lock unlock]; return result; +} } +uint32_t dm_nextendo_async_result(void *object) { @autoreleasepool { + DmNextendoAsync *state = request(object); if (!state) return DM_ACCOUNT_FAIL; [state.lock lock]; uint32_t result = state.started && state.done && !state.destroyed ? state.result : DM_ACCOUNT_FAIL; [state.lock unlock]; return result; +} } diff --git a/dm/host/hle_nextendo_friends.c b/dm/host/hle_nextendo_friends.c new file mode 100644 index 0000000000..d5eef853ef --- /dev/null +++ b/dm/host/hle_nextendo_friends.c @@ -0,0 +1,115 @@ +// Original social-data/SDK adapter. Layout is verified from SDK function semantics, +// not fixed module addresses or a guessed opaque-object size. +#include "hle.h" +#include "nextendo_social.h" +#include "account_local.h" +#include "net_socket.h" +#include "nextendo_account.h" +#include +#include +#include + +static bool getter(const char *name,uint32_t instruction) { + const uint32_t *code=guest_sym(name); uint32_t words[2]; if (!code) return false; + memcpy(words,code,sizeof words); return words[0]==instruction && words[1]==0xd65f03c0u; +} +static bool friend_layout(void) { + const uint32_t *code=guest_sym("_ZN2nn7friends6FriendC1Ev"); uint32_t words[3]; if (!code) return false; + memcpy(words,code,sizeof words); + if (words[0]!=0x52804002u && words[1]!=0x52804002u) return false; // constructor memset size 0x200 + return getter("_ZNK2nn7friends6Friend11GetNicknameEv",0x91006000u) && + getter("_ZNK2nn7friends6Friend11GetPresenceEv",0x91010000u) && + getter("_ZNK2nn7friends6Friend12GetAccountIdEv",0xf9400800u) && + getter("_ZNK2nn7friends6Friend7IsValidEv",0x3944a000u) && + getter("_ZNK2nn7friends6Friend10IsFavoriteEv",0x39448000u); +} +static bool presence_layout(void) { + const uint32_t *code=guest_sym("_ZN2nn7friends12UserPresenceC1Ev"); if(!code)return false; + uint32_t first;memcpy(&first,code,4); + if(first==0x52801c02u)return true; // constructor memset size 0xe0 + // New SDKs inline the complete fourteen-pair zero initialization. + if(first!=0xa90d7c1fu)return false; + uint32_t words[15];memcpy(words,code,sizeof words); + for(unsigned i=0;i<14;i++)if(words[i]!=(0xa9007c1fu|((26-2*i)<<15)))return false; + return words[14]==0xd65f03c0u; +} +uint32_t dm_nextendo_presence_initialize(void *object,const void *uid) { + if(!object||!presence_layout()||!dm_net_nextendo_enabled()||dm_nextendo_account_ensure())return RES_FAIL; + uint8_t local[16];if(!uid){if(!dm_account_copy_uid(local))return RES_FAIL;uid=local;} + if(!dm_account_uid_exists(uid))return RES_FAIL; + // The original SDK initializer writes only the selected local UID. Its + // constructors, Clear, SetDescription and SetAppValue keep their own format. + memcpy(object,uid,16);return 0; +} +uint32_t dm_nextendo_presence_commit(const void *object) { + if(!object||!presence_layout()||!dm_net_nextendo_enabled()||!dm_account_uid_exists(object))return RES_FAIL; + return dm_nextendo_social_publish(2,(const uint8_t*)object+0x20,DM_SOCIAL_APP_FIELD); +} +// SetDescription writes the description into the object's application field under a reserved +// key (SDK 4.4: Mario Kart 8 Deluxe's sdk+0x122a44, the same helper SetAppValue uses, which refuses +// keys starting "sys"), no service call. The host takes the symbol over for offline, so with Nextendo +// on it runs the SDK's own definition, which guest_sym still finds in the module. +uint32_t dm_nextendo_presence_describe(void *object,const char *description) { + if(!object||!description||!presence_layout()||!dm_net_nextendo_enabled())return RES_FAIL; + uint32_t (*sdk)(void *,const char *)=(uint32_t (*)(void *,const char *))guest_sym("_ZN2nn7friends12UserPresence14SetDescriptionEPKc"); + return sdk?sdk(object,description):RES_FAIL; +} +static void encode_friend(uint8_t output[0x200],const dm_social_friend *item,const void *uid,bool baas) { + memset(output,0,0x200); memcpy(output,uid,16); + uint64_t id=baas&&item->nsa?item->nsa:item->pid; + memcpy(output+0x10,&id,8); memcpy(output+0x18,item->nickname,33); + memcpy(output+0x40,uid,16); memcpy(output+0x50,&item->last_online,8); memcpy(output+0x58,&item->presence,4); + output[0x5c]=item->application==strtoull(DM_GAME_ID,NULL,16); + memcpy(output+0x60,item->app_field,DM_SOCIAL_APP_FIELD); + output[0x120]=item->favorite; output[0x128]=1; +} +uint32_t dm_nextendo_friends_ensure(const void *uid) { + if (!dm_net_nextendo_enabled() || !dm_account_uid_exists(uid)) return RES_FAIL; + dm_social_friend *friends=NULL; size_t count=0; + uint32_t result=dm_nextendo_social_friends(&friends,&count); free(friends); return result; +} +uint32_t dm_nextendo_friends_available(uint8_t *available,const void *uid) { + if (!available || !dm_account_uid_exists(uid)) return RES_FAIL; + *available=0; + if (!dm_net_nextendo_enabled()) return 0; + uint32_t result=dm_nextendo_friends_ensure(uid); if (!result) *available=1; return result; +} +uint32_t dm_nextendo_friends_list(int *count,void *output,const void *uid,int offset,int capacity,const void *filter,bool ids_only) { + if (count) *count=0; + if (!count || !filter || offset<0 || capacity<0 || capacity>DM_SOCIAL_FRIEND_MAX || (capacity&&!output) || !dm_net_nextendo_enabled()) return RES_FAIL; + uint8_t local_uid[16]; + if (!uid) { if (!dm_account_copy_uid(local_uid)) return RES_FAIL; uid=local_uid; } + if (!dm_account_uid_exists(uid) || (!ids_only && !friend_layout())) return RES_FAIL; + uint8_t options[16]; memcpy(options,filter,sizeof options); uint32_t presence; memcpy(&presence,options,4); + if (presence>3 || options[4]>1 || options[5]>1 || options[6] || options[7]) return RES_FAIL; + dm_social_friend *friends=NULL; size_t total=0; + if (dm_nextendo_social_friends(&friends,&total)) return RES_FAIL; + bool baas=dm_nextendo_api_baas_namespace("friends"); size_t matched=0,written=0; + for (size_t i=0;ipresence!=1) || (presence==2&&item->presence!=2) || + (presence==3&&!item->presence) || (options[4]&&!item->favorite) || + (options[5]&&item->application!=strtoull(DM_GAME_ID,NULL,16))) continue; + if (matched++<(size_t)offset || written>=(size_t)capacity) continue; + if (ids_only) { uint64_t id=baas&&item->nsa?item->nsa:item->pid; memcpy((uint8_t*)output+written*8,&id,8); } + else encode_friend((uint8_t*)output+written*0x200,item,uid,baas); + written++; + } + free(friends); *count=(int)written; return 0; +} +uint32_t dm_nextendo_friends_update(void *output,const void *uid,const uint64_t *ids,int count) { + if (count<0||count>DM_SOCIAL_FRIEND_MAX||(count&&(!output||!ids))||!dm_net_nextendo_enabled()||!dm_account_uid_exists(uid)||!friend_layout())return RES_FAIL; + dm_social_friend *friends=NULL;size_t total=0; + // UpdateFriendInfo is an explicit refresh, independent of list pagination's + // short-lived snapshot. A failed refresh never clears the caller's records. + if(dm_nextendo_social_friends_refresh(&friends,&total))return RES_FAIL; + size_t selected[DM_SOCIAL_FRIEND_MAX]; + for(int i=0;i +#if TARGET_OS_OSX || TARGET_OS_IOS +#import "nextendo_login_apple.inc" +#include "nextendo_account.h" +#import "nextendo_api_apple.h" +#include +#include +#include +#include +#include + +void dm_guest_host_wait_begin(void); +void dm_guest_host_wait_end(void); +void dm_nextendo_login_online_check(const char *when); +void dm_nextendo_session_start(void); // hle_nextendo_social_apple.m (loader.c has a weak empty default) + +enum { ACCESS_LIFE = 50 * 60 }; // Nextendo's access tokens live an hour; one older than this is renewed first + +static struct { + pthread_mutex_t lock; + NSData *json; // the current record, encoded + NSTimeInterval expires; // its game token's expiry + NSTimeInterval next_try; // no fetch before this after a failure + NSString *access; // the refresh's access token, and when it was issued + NSTimeInterval access_at; +} g_cache = {.lock = PTHREAD_MUTEX_INITIALIZER}; + +static void refresh_locked(NSTimeInterval now) { + NSString *why = nil, *access = nil; + NSDictionary *record = nxl_game_record_access(&why, &access); + NSData *json = record ? [NSJSONSerialization dataWithJSONObject:record options:0 error:nil] : nil; + if (!json) { // the current record, if any, serves until its own expiry (provide_credential checks it) + g_cache.next_try = now + 30; + fprintf(stderr, "[dm] [RED] nextendo: no %sgame credential: %s\n", g_cache.json && g_cache.expires > now ? "new " : "", (why ?: @"the record could not be encoded").UTF8String); + return; + } + g_cache.json = json; g_cache.expires = [record[@"expires_at"] doubleValue]; g_cache.next_try = 0; + g_cache.access = access; g_cache.access_at = now; + fprintf(stderr, "[dm] nextendo: signed in as %s\n", [record[@"identity"][@"username"] UTF8String]); +} + +static bool provide_credential(uint8_t *buffer, size_t capacity, size_t *size) { @autoreleasepool { + dm_guest_host_wait_begin(); // a refresh is network round trips, and other callers wait on the lock meanwhile: their guest cores are free + pthread_mutex_lock(&g_cache.lock); + NSTimeInterval now = nxl_now(); + bool stale = !g_cache.json || g_cache.expires - now < 120; + if (stale && now >= g_cache.next_try) refresh_locked(now); + bool usable = g_cache.json && g_cache.expires > now && g_cache.json.length <= capacity; + if (usable) { memcpy(buffer, g_cache.json.bytes, g_cache.json.length); *size = g_cache.json.length; } + pthread_mutex_unlock(&g_cache.lock); + dm_guest_host_wait_end(); + // The first game credential also asks once whether Nextendo will let this account play (on a queue: the game does not wait), and starts the + // Nextendo session (the account's Mii) if the module load did not: on the iPhone the modules can load before the launcher has set + // DM_NETWORK, and then loader.c's nextendo_main saw no Nextendo (Mario Kart 8 Deluxe, 2026-11-14). It starts once either way + static atomic_bool asked; + if (usable && !atomic_exchange(&asked, true)) { + dm_nextendo_session_start(); + dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ dm_nextendo_login_online_check("at the game's first sign-in"); }); + } + return usable; +} } + +// The access token for Nextendo's account API, renewed when older than ACCESS_LIFE; nil without a sign-in or while a refresh fails +NSString *dm_nextendo_login_access(void) { @autoreleasepool { + dm_guest_host_wait_begin(); + pthread_mutex_lock(&g_cache.lock); + NSTimeInterval now = nxl_now(); + if ((!g_cache.access || now - g_cache.access_at >= ACCESS_LIFE) && now >= g_cache.next_try) refresh_locked(now); + NSString *access = g_cache.access && now - g_cache.access_at < ACCESS_LIFE + 600 ? g_cache.access : nil; + pthread_mutex_unlock(&g_cache.lock); + dm_guest_host_wait_end(); + return access; +} } + +// Asks /api/online-status whether this account may play online now and logs the answer when it changes: "allowed", the refusal in words +// (the gates Nextendo's game servers apply at a game's login: e-mail, Discord link, another device online, a disabled account), or that it +// could not be asked. when says what prompted it ("at the start", "after the game's error 2306-0807") +void dm_nextendo_login_online_check(const char *when) { @autoreleasepool { + NSString *token = dm_nextendo_api_bearer("online-status"); + NSString *line; + if (!token) line = @"[RED] nextendo: online status not asked: no game token (no sign-in, or its refresh failed)"; + else { + NSMutableURLRequest *get = nxl_request(kNxOnlineStatusEndpoint, 8); + [get setValue:[NSString stringWithFormat:@"Bearer %@", token] forHTTPHeaderField:@"Authorization"]; + NSString *why = nil; + dm_guest_host_wait_begin(); NSDictionary *answer = nxl_send(get, &why); dm_guest_host_wait_end(); + if (!answer) line = [NSString stringWithFormat:@"[RED] nextendo: online status could not be asked: %@", why ?: @"no answer"]; + else if ([answer[@"allow"] isEqual:@YES]) line = @"nextendo: Nextendo allows online play for this account"; + else line = [@"[RED] nextendo: " stringByAppendingString:nxl_refusal_words(answer[@"reason"])]; + } + static pthread_mutex_t told_lock = PTHREAD_MUTEX_INITIALIZER; static NSString *told; + pthread_mutex_lock(&told_lock); bool fresh = ![told isEqual:line]; if (fresh) told = line; pthread_mutex_unlock(&told_lock); + if (fresh) fprintf(stderr, "[dm] %s (%s)\n", line.UTF8String, when ? when : "asked"); +} } + +// Nextendo's clock less this device's (nxl_note_server_date), for hle_nextendo_apple.m's credential checks and id token +double dm_nextendo_clock_offset(void) { return atomic_load(&nxl_clock_offset); } + +__attribute__((constructor)) static void install_provider(void) { dm_nextendo_set_credential_provider(provide_credential); } +#endif diff --git a/dm/host/hle_nextendo_routes.c b/dm/host/hle_nextendo_routes.c new file mode 100644 index 0000000000..4c3823e12a --- /dev/null +++ b/dm/host/hle_nextendo_routes.c @@ -0,0 +1,198 @@ +// Original exact-host routing policy. Endpoint facts/configuration do not import +// another client's implementation, credentials, wildcard rules or TLS bypasses. +#include "nextendo_routes.h" +#include "net_socket.h" +#include "ssl_backend.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +enum { ROUTE_MAX = 128, CONFIG_MAX = 65536, CERT_MAX = 65536, CERT_TOTAL_MAX = 1024 * 1024 }; +typedef struct { char host[254], address[INET_ADDRSTRLEN], peer[254]; unsigned match; bool pinned, address_alias; uint8_t *ca; size_t ca_size; } route; +static route *routes; +static size_t route_count; +static pthread_mutex_t policy_lock = PTHREAD_MUTEX_INITIALIZER; +static _Atomic int policy_status = DM_NEXTENDO_ROUTES_UNINITIALIZED; + +static bool hostname(const char *input, char out[254]) { + if (!input) return false; size_t length = strnlen(input, 255); if (!length || length > 254) return false; + if (input[length - 1] == '.') length--; if (!length || length > 253) return false; + size_t label = 0; + for (size_t i = 0; i < length; i++) { + unsigned char c = (unsigned char)input[i]; if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; + if (c == '.') { if (!label || input[i - 1] == '-') return false; label = 0; } + else { if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-') || (!label && c == '-') || ++label > 63) return false; } + out[i] = (char)c; + } + if (!label || input[length - 1] == '-') return false; out[length] = 0; return true; +} +static bool route_pattern(const char *kind, const char *input, route *entry) { + if (!strcmp(kind, "exact")) entry->match = 0; + else if (!strcmp(kind, "pinned-exact")) { entry->match = 0; entry->pinned = true; } + else if (!strcmp(kind, "pinned-address")) { entry->match = 0; entry->pinned = true; entry->address_alias = true; } + else if (!strcmp(kind, "suffix")) entry->match = 1; + else if (!strcmp(kind, "label")) entry->match = 2; + else return false; + if (entry->match != 2) return hostname(input, entry->host); + if (!input || strnlen(input, 254) >= 254) return false; + char check[254]; strcpy(check, input); char *star = strchr(check, '*'); + if (!star || strchr(star + 1, '*')) return false; + size_t offset = (size_t)(star - check); *star = 'x'; + if (!hostname(check, entry->host)) return false; + entry->host[offset] = '*'; return true; +} +static unsigned match_score(const route *entry, const char *host) { + size_t n = strlen(host), m = strlen(entry->host); + if (!entry->match) return !strcmp(host, entry->host) ? 100000u + (unsigned)m : 0; + if (entry->match == 1) + return (n == m && !strcmp(host, entry->host)) || + (n > m && host[n - m - 1] == '.' && !strcmp(host + n - m, entry->host)) ? (unsigned)m : 0; + const char *star = strchr(entry->host, '*'); size_t prefix = (size_t)(star - entry->host), suffix = m - prefix - 1; + if (n < prefix + suffix || strncmp(host, entry->host, prefix) || strcmp(host + n - suffix, star + 1)) return 0; + // A label wildcard cannot cross a DNS-label boundary. + if (memchr(host + prefix, '.', n - prefix - suffix)) return 0; + return 10000u + (unsigned)m; +} +static int read_regular(int fd, size_t limit, uint8_t **bytes, size_t *length) { + struct stat st; + if (fstat(fd, &st) || !S_ISREG(st.st_mode) || (st.st_uid != geteuid() && st.st_uid != 0) || (st.st_mode & 022) || st.st_size <= 0) return DM_NEXTENDO_ROUTES_IO; + if ((uint64_t)st.st_size > limit) return DM_NEXTENDO_ROUTES_LIMIT; + uint8_t *data = malloc((size_t)st.st_size + 1); if (!data) return DM_NEXTENDO_ROUTES_LIMIT; size_t done = 0; + while (done < (size_t)st.st_size) { ssize_t n = read(fd, data + done, (size_t)st.st_size - done); if (n < 0 && errno == EINTR) continue; if (n <= 0) { free(data); return DM_NEXTENDO_ROUTES_IO; } done += (size_t)n; } + data[done] = 0; *bytes = data; *length = done; return 0; +} +static int hex_digit(char c) { return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; } +static int load_ca(int directory, const char *name, const char *expected, route *entry) { + if (!strcmp(name, "-") && !strcmp(expected, "-")) return 0; + if (!name[0] || strlen(name) > NAME_MAX || strchr(name, '/') || !strcmp(name, ".") || !strcmp(name, "..") || strlen(expected) != 64) return DM_NEXTENDO_ROUTES_CERTIFICATE; + uint8_t digest[CC_SHA256_DIGEST_LENGTH]; + for (unsigned i = 0; i < sizeof digest; i++) { int a = hex_digit(expected[i * 2]), b = hex_digit(expected[i * 2 + 1]); if (a < 0 || b < 0) return DM_NEXTENDO_ROUTES_CERTIFICATE; digest[i] = (uint8_t)(a * 16 + b); } + int fd = openat(directory, name, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); if (fd < 0) return DM_NEXTENDO_ROUTES_CERTIFICATE; + int status = read_regular(fd, CERT_MAX, &entry->ca, &entry->ca_size); close(fd); if (status) return status; + uint8_t actual[CC_SHA256_DIGEST_LENGTH]; CC_SHA256(entry->ca, (CC_LONG)entry->ca_size, actual); if (memcmp(actual, digest, sizeof actual)) return DM_NEXTENDO_ROUTES_CERTIFICATE; + CFDataRef data = CFDataCreate(kCFAllocatorDefault, entry->ca, (CFIndex)entry->ca_size); + SecCertificateRef certificate = data ? SecCertificateCreateWithData(kCFAllocatorDefault, data) : NULL; if (data) CFRelease(data); + if (!certificate) return DM_NEXTENDO_ROUTES_CERTIFICATE; CFRelease(certificate); return 0; +} +static void free_routes(route *entries, size_t count) { if (!entries) return; for (size_t i = 0; i < count; i++) free(entries[i].ca); free(entries); } +static int load_policy(const char *path, route **output, size_t *count) { + if (!path || !path[0]) return DM_NEXTENDO_ROUTES_MISSING; + size_t path_size = strnlen(path, PATH_MAX); if (path[0] != '/' || path_size >= PATH_MAX) return DM_NEXTENDO_ROUTES_INVALID; + char parent[PATH_MAX]; memcpy(parent, path, path_size + 1); char *slash = strrchr(parent, '/'); if (!slash || !slash[1]) return DM_NEXTENDO_ROUTES_INVALID; + const char *file = path + (slash - parent) + 1; if (slash == parent) slash[1] = 0; else *slash = 0; + int directory = open(parent, O_RDONLY | O_CLOEXEC | O_DIRECTORY); if (directory < 0) return errno == ENOENT ? DM_NEXTENDO_ROUTES_MISSING : DM_NEXTENDO_ROUTES_IO; + int fd = openat(directory, file, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); if (fd < 0) { int status = errno == ENOENT ? DM_NEXTENDO_ROUTES_MISSING : DM_NEXTENDO_ROUTES_IO; close(directory); return status; } + uint8_t *data = NULL; size_t size = 0; int status = read_regular(fd, CONFIG_MAX, &data, &size); close(fd); + if (status) { close(directory); return status; } + if (memchr(data, 0, size)) { free(data); close(directory); return DM_NEXTENDO_ROUTES_INVALID; } + route *entries = calloc(ROUTE_MAX, sizeof *entries); if (!entries) { free(data); close(directory); return DM_NEXTENDO_ROUTES_LIMIT; } + char *cursor = (char *)data, *end = (char *)data + size; size_t used = 0, ca_total = 0; bool magic = false, version2 = false; + while (cursor < end && !status) { + char *line = cursor, *newline = memchr(cursor, '\n', (size_t)(end - cursor)); if (newline) { *newline = 0; cursor = newline + 1; } else cursor = end; + size_t length = strlen(line); if (length && line[length - 1] == '\r') line[--length] = 0; + if (!magic) { + version2 = !strcmp(line, "NXNEXTENDO_ROUTES_2"); + if (!version2 && strcmp(line, "NXNEXTENDO_ROUTES_1")) status = DM_NEXTENDO_ROUTES_INVALID; + else magic = true; continue; + } + if (!length || line[0] == '#') continue; + if (used >= ROUTE_MAX || length > 2048) { status = DM_NEXTENDO_ROUTES_LIMIT; break; } + char *fields[5], *part = line; const char *kind = version2 ? strsep(&part, "\t") : "exact"; + if (!kind || !part) { status = DM_NEXTENDO_ROUTES_INVALID; break; } + for (unsigned i = 0; i < 5; i++) { fields[i] = strsep(&part, "\t"); if (!fields[i] || !fields[i][0]) { status = DM_NEXTENDO_ROUTES_INVALID; break; } } + if (status || part) { status = DM_NEXTENDO_ROUTES_INVALID; break; } + route *entry = &entries[used]; struct in_addr ip, literal; + bool dynamic_peer = version2 && !strcmp(fields[2], "@host"); + if (!route_pattern(kind, fields[0], entry) || (inet_pton(AF_INET, entry->host, &literal) == 1) != entry->address_alias || inet_pton(AF_INET, fields[1], &ip) != 1 || (ntohl(ip.s_addr) >> 24) == 0 || (ntohl(ip.s_addr) >> 24) >= 224 || + (!strcmp(fields[2], "-") ? (strcmp(fields[3], "-") || strcmp(fields[4], "-")) : (!dynamic_peer && !hostname(fields[2], entry->peer)))) { status = DM_NEXTENDO_ROUTES_INVALID; break; } + if (dynamic_peer) strcpy(entry->peer, "@host"); + // A leaf pin enrolls one exact logical service identity. It cannot be + // inherited by wildcard hosts or used to rename the TLS service. + if (entry->pinned && !entry->address_alias && (entry->match || (!dynamic_peer && strcmp(entry->host, entry->peer)))) { status = DM_NEXTENDO_ROUTES_INVALID; break; } + if (entry->address_alias && (dynamic_peer || literal.s_addr != ip.s_addr || !entry->peer[0] || inet_pton(AF_INET, entry->peer, &literal) == 1)) { status = DM_NEXTENDO_ROUTES_INVALID; break; } + if (!inet_ntop(AF_INET, &ip, entry->address, sizeof entry->address)) { status = DM_NEXTENDO_ROUTES_INVALID; break; } + for (size_t i = 0; i < used; i++) if (entries[i].match == entry->match && !strcmp(entries[i].host, entry->host)) { status = DM_NEXTENDO_ROUTES_INVALID; break; } + if (!status) status = load_ca(directory, fields[3], fields[4], entry); + if (!status && entry->pinned && !entry->ca_size) status = DM_NEXTENDO_ROUTES_CERTIFICATE; + if (status) { free(entry->ca); entry->ca = NULL; break; } + ca_total += entry->ca_size; if (ca_total > CERT_TOTAL_MAX) { free(entry->ca); entry->ca = NULL; status = DM_NEXTENDO_ROUTES_LIMIT; break; } used++; + } + free(data); close(directory); if (!magic || !used) status = status ? status : DM_NEXTENDO_ROUTES_INVALID; + // NEX secure-server handoffs can name an IP instead of the original DNS + // service. A configured numeric alias inherits only an existing exact pin + // for the same address and certificate; it grants no independent identity. + for (size_t i = 0; !status && i < used; i++) if (entries[i].address_alias) { + const route *alias = &entries[i]; bool paired = false; + for (size_t j = 0; j < used; j++) { + const route *identity = &entries[j]; + if (identity->pinned && !identity->address_alias && !identity->match && + !strcmp(alias->peer, identity->host) && !strcmp(alias->address, identity->address) && + alias->ca_size == identity->ca_size && !memcmp(alias->ca, identity->ca, alias->ca_size)) { paired = true; break; } + } + if (!paired) status = DM_NEXTENDO_ROUTES_INVALID; + } + if (status) { free_routes(entries, used); return status; } *output = entries; *count = used; return 0; +} +static const route *find_route(const char *host) { + dm_nextendo_routes_initialize(); if (atomic_load(&policy_status) != DM_NEXTENDO_ROUTES_READY) return NULL; + char normalized[254]; if (!hostname(host, normalized)) return NULL; + const route *best = NULL; unsigned score = 0; + for (size_t i = 0; i < route_count; i++) { unsigned value = match_score(&routes[i], normalized); if (value > score) { best = &routes[i]; score = value; } } + return best; +} +static int resolve_host(const char *host, char *output, size_t capacity) { + if (!dm_net_nextendo_enabled() || !host) return 0; struct in_addr ip; if (inet_pton(AF_INET, host, &ip) == 1) return 0; + const route *entry = find_route(host); if (!entry || capacity <= strlen(entry->address)) return -1; strcpy(output, entry->address); return 1; +} +static bool admit_peer(const char *host) { if (!dm_net_nextendo_enabled()) return true; const route *entry = find_route(host); return entry && entry->peer[0]; } +static bool copy_peer_policy(const char *host, char *output, size_t capacity, const uint8_t **ca, size_t *size, bool pinned) { + if (!dm_net_nextendo_enabled()) return false; const route *entry = find_route(host); if (!entry || !entry->peer[0]) return false; + if (entry->pinned != pinned) return false; + const char *peer = entry->peer; char normalized[254]; + if (!strcmp(peer, "@host")) { if (!hostname(host, normalized)) return false; peer = normalized; } + if (capacity <= strlen(peer)) return false; + strcpy(output, peer); *ca = entry->ca; *size = entry->ca_size; return true; +} +static bool peer_policy(const char *host, char *output, size_t capacity, const uint8_t **ca, size_t *size) { return copy_peer_policy(host, output, capacity, ca, size, false); } +static bool pinned_peer_policy(const char *host, char *output, size_t capacity, const uint8_t **ca, size_t *size) { return copy_peer_policy(host, output, capacity, ca, size, true); } +// The service's CA for the SSL service's built-in certificates when the player has no firmware store (hle_ssl_apple.m): a game whose own TLS takes its roots +// from the store (Super Mario Bros. Wonder's gRPC) then needs only the sign-in. The profile's routes share the provider's one CA (dm/net/nextendo-services.json +// provider.caSHA256, checked when the table loaded); an enrolled leaf of a pinned route is not a CA and is skipped +static bool provider_ca(const uint8_t **ca, size_t *size) { + if (!dm_net_nextendo_enabled() || dm_nextendo_routes_initialize() != DM_NEXTENDO_ROUTES_READY) return false; + for (size_t i = 0; i < route_count; i++) if (routes[i].ca_size && !routes[i].pinned) { *ca = routes[i].ca; *size = routes[i].ca_size; return true; } + return false; +} +__attribute__((constructor)) static void register_policy(void) { dm_net_set_dns_provider(resolve_host); dm_ssl_set_peer_guard(admit_peer); dm_ssl_set_peer_policy(peer_policy); dm_ssl_set_peer_pin_policy(pinned_peer_policy); dm_ssl_set_builtin_fallback(provider_ca); } +int dm_nextendo_routes_initialize(void) { + pthread_mutex_lock(&policy_lock); int status = atomic_load(&policy_status); + if (status == DM_NEXTENDO_ROUTES_UNINITIALIZED) { status = load_policy(getenv("DM_NEXTENDO_ROUTES"), &routes, &route_count); atomic_store(&policy_status, status); } + pthread_mutex_unlock(&policy_lock); return status; +} +int dm_nextendo_routes_retry_unconfigured(void) { + pthread_mutex_lock(&policy_lock); int status = atomic_load(&policy_status); + // A failed load publishes no route pointers. An explicit launcher setup + // action may retry that state; a valid published table is never replaced. + if (status != DM_NEXTENDO_ROUTES_READY) atomic_store(&policy_status, DM_NEXTENDO_ROUTES_UNINITIALIZED); + pthread_mutex_unlock(&policy_lock); return status; +} +int dm_nextendo_routes_status(void) { return atomic_load(&policy_status); } +size_t dm_nextendo_routes_count(void) { return atomic_load(&policy_status) == DM_NEXTENDO_ROUTES_READY ? route_count : 0; } + +// Optional BCAT capability bridge. A valid explicit service profile is required; +// checking it performs no network/account request and does not grant game access. +int dm_bcat_online_enabled(void) { + return dm_net_nextendo_enabled() && dm_nextendo_routes_initialize() == DM_NEXTENDO_ROUTES_READY && dm_nextendo_routes_count() > 0; +} diff --git a/dm/host/hle_nextendo_social_apple.m b/dm/host/hle_nextendo_social_apple.m new file mode 100644 index 0000000000..ff5b44dc50 --- /dev/null +++ b/dm/host/hle_nextendo_social_apple.m @@ -0,0 +1,217 @@ +// Real, bounded friend snapshots. HTTP/schema failures never become empty lists. +#import "nextendo_api_apple.h" +#include "nextendo_social.h" +#include "nextendo_account.h" +#include "net_socket.h" +#include +#include +#include +#include +#include +#include +#include "game_profile.h" + +static bool number(id value) { return [value isKindOfClass:NSNumber.class] && CFGetTypeID((__bridge CFTypeRef)value)!=CFBooleanGetTypeID(); } +static NSTimeInterval monotonic_time(void) { struct timespec now; clock_gettime(CLOCK_MONOTONIC,&now); return now.tv_sec+now.tv_nsec/1e9; } +static bool unsigned_value(id value,uint64_t *output) { + if (!number(value)) return false; + NSString *text=[value stringValue]; if (!text.length || text.length>20) return false; + uint64_t result=0; + for (NSUInteger i=0;i'9'||result>(UINT64_MAX-(c-'0'))/10) return false; result=result*10+c-'0'; } + *output=result; return true; +} +static bool hexadecimal(id value,uint64_t *output) { + if (![value isKindOfClass:NSString.class] || ![value length] || [value length]>16) return false; + uint64_t result=0; + for (NSUInteger i=0;i<[value length];i++) { unichar c=[value characterAtIndex:i]; unsigned digit; + if (c>='0'&&c<='9')digit=c-'0'; else if(c>='a'&&c<='f')digit=c-'a'+10; else if(c>='A'&&c<='F')digit=c-'A'+10; else return false; + result=(result<<4)|digit; + } + *output=result; return true; +} +static bool nickname(id value,char output[33]) { + if (![value isKindOfClass:NSString.class] || ![value length] || [value length]>128 || [value rangeOfString:[NSString stringWithFormat:@"%C",(unichar)0]].location!=NSNotFound) return false; + NSMutableData *bytes=[NSMutableData new]; + [value enumerateSubstringsInRange:NSMakeRange(0,[value length]) options:NSStringEnumerationByComposedCharacterSequences + usingBlock:^(NSString *substring,NSRange range,NSRange enclosing,BOOL *stop) { + (void)range; (void)enclosing; NSData *part=[substring dataUsingEncoding:NSUTF8StringEncoding]; + if (!part || bytes.length+part.length>32) { *stop=YES; return; } [bytes appendData:part]; + }]; + if (!bytes.length) return false; memcpy(output,bytes.bytes,bytes.length); output[bytes.length]=0; return true; +} +static NSData *decode_friends(NSData *bytes,size_t *count) { + id root=[NSJSONSerialization JSONObjectWithData:bytes options:0 error:nil]; + id rows=[root isKindOfClass:NSDictionary.class]?root[@"friends"]:nil; + if (![rows isKindOfClass:NSArray.class] || [rows count]>DM_SOCIAL_FRIEND_MAX) return nil; + NSMutableData *records=[NSMutableData dataWithLength:[rows count]*sizeof(dm_social_friend)]; + dm_social_friend *output=records.mutableBytes; NSMutableSet *seen=[NSMutableSet new]; + for (NSUInteger i=0;i<[rows count];i++) { + id row=rows[i]; dm_social_friend *item=&output[i]; + if (![row isKindOfClass:NSDictionary.class] || !unsigned_value(row[@"pid"],&item->pid) || !item->pid || + [seen containsObject:@(item->pid)] || !nickname(row[@"name"],item->nickname)) return nil; + [seen addObject:@(item->pid)]; + if (row[@"nsa"] && row[@"nsa"]!=NSNull.null && ![row[@"nsa"] isEqual:@""] && !hexadecimal(row[@"nsa"],&item->nsa)) return nil; + if (row[@"favorite"]) { + if (![row[@"favorite"] isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)row[@"favorite"])!=CFBooleanGetTypeID()) return nil; + item->favorite=[row[@"favorite"] boolValue]; + } + id presence=row[@"presence"]; + if (!presence || presence==NSNull.null) continue; + if (![presence isKindOfClass:NSDictionary.class]) return nil; + uint64_t status=0; + if (presence[@"status"] && (!unsigned_value(presence[@"status"],&status) || status>2)) return nil; + item->presence=(uint32_t)status; + if (presence[@"app_id"] && presence[@"app_id"]!=NSNull.null && ![presence[@"app_id"] isEqual:@""] && !hexadecimal(presence[@"app_id"],&item->application)) return nil; + id encoded=presence[@"app_field"]; + if (encoded && encoded!=NSNull.null) { + if (![encoded isKindOfClass:NSString.class] || [encoded length]>256) return nil; + NSData *field=[[NSData alloc] initWithBase64EncodedString:encoded options:0]; + if (!field || field.length>DM_SOCIAL_APP_FIELD || ![[field base64EncodedStringWithOptions:0] isEqual:encoded]) return nil; + memcpy(item->app_field,field.bytes,field.length); + } + } + *count=[rows count]; return records; +} + +static uint32_t friends_snapshot(dm_social_friend **output,size_t *count,bool refresh) { @autoreleasepool { + if (count) *count=0; if (output) *output=NULL; if (!output || !count) return DM_ACCOUNT_FAIL; + NSData *identity=dm_nextendo_api_identity(); if (!identity) return DM_ACCOUNT_FAIL; + static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; + static NSData *cached_identity,*cached_records; static size_t cached_count; static NSTimeInterval fetched; + pthread_mutex_lock(&mutex); NSData *records=nil; size_t n=0; + if (!refresh && [identity isEqual:cached_identity] && monotonic_time()-fetched<30) { records=cached_records; n=cached_count; } + pthread_mutex_unlock(&mutex); + if (!records) { + uint8_t *buffer=malloc(1024*1024); if (!buffer) return DM_ACCOUNT_FAIL; size_t length=0; + uint32_t result=dm_nextendo_api_request("friends",NULL,0,buffer,1024*1024,&length); + NSData *data=result||!length?nil:[NSData dataWithBytes:buffer length:length]; free(buffer); + if (!data || !(records=decode_friends(data,&n)) || ![identity isEqual:dm_nextendo_api_identity()]) return DM_ACCOUNT_FAIL; + pthread_mutex_lock(&mutex); cached_identity=identity; cached_records=records; cached_count=n; fetched=monotonic_time(); pthread_mutex_unlock(&mutex); + } + if (![identity isEqual:dm_nextendo_api_identity()]) return DM_ACCOUNT_FAIL; + // Every caller owns its snapshot; sign-out/account changes cannot mutate it. + if (n) { *output=malloc(records.length); if (!*output) return DM_ACCOUNT_FAIL; memcpy(*output,records.bytes,records.length); } + *count=n; return 0; +} } +uint32_t dm_nextendo_social_friends(dm_social_friend **output,size_t *count) { return friends_snapshot(output,count,false); } +uint32_t dm_nextendo_social_friends_refresh(dm_social_friend **output,size_t *count) { return friends_snapshot(output,count,true); } + +// Nextendo shows a player online while presence keeps arriving (Mush8 sends it again every 45 seconds). The last presence a game published +// is sent again on that period until the game publishes status 0 (its online session closed) or a send fails +enum { PRESENCE_EVERY_S = 45 }; +// A publish returns once the presence is queued, as UserPresence::Commit and Declare*OnlinePlaySession do on a console: they hand it to the friends +// service, which uploads it in the background, and the game is never told how the upload went. Waiting for the request on the game's thread held a +// menu change for a round trip to nextendo.network (up to the request's 15 s timeout on a poor network). One serial queue sends and repeats, so a +// repeat never lands after a newer publish, and only the newest presence still waiting is sent: a menu that publishes several in a row sends one +static pthread_mutex_t g_presence_lock = PTHREAD_MUTEX_INITIALIZER; +static NSData *g_presence_waiting; // the newest published body not sent yet, and its status (under g_presence_lock) +static unsigned g_presence_waiting_status; +static NSData *g_presence_body; // on presence_queue(): the last body sent while its status is not 0, which the timer sends again +static dispatch_source_t g_presence_timer; +static bool g_presence_failing; // on presence_queue(): the last send failed (logged once per run of failures) +static dispatch_queue_t presence_queue(void) { + static dispatch_queue_t queue; static dispatch_once_t once; + dispatch_once(&once,^{ queue=dispatch_queue_create("nextendo.presence",dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL,QOS_CLASS_UTILITY,0)); }); + return queue; +} +static uint32_t presence_post(NSData *body,NSData *identity) { + uint8_t response[4096];size_t count=0; + uint32_t result=dm_nextendo_api_request("presence",body.bytes,body.length,response,sizeof response,&count); + return !result&&[identity isEqual:dm_nextendo_api_identity()]?0:DM_ACCOUNT_FAIL; +} +static void presence_keep(NSData *body) { // on presence_queue(); nil stops the repeats + g_presence_body=body; + if (body && !g_presence_timer) { + g_presence_timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,presence_queue()); + dispatch_source_set_timer(g_presence_timer,dispatch_time(DISPATCH_TIME_NOW,PRESENCE_EVERY_S*NSEC_PER_SEC),PRESENCE_EVERY_S*NSEC_PER_SEC,5*NSEC_PER_SEC); + dispatch_source_set_event_handler(g_presence_timer,^{ @autoreleasepool { + NSData *again=g_presence_body,*identity=again?dm_nextendo_api_identity():nil; + if (again && (!identity || presence_post(again,identity))) g_presence_body=nil; + } }); + dispatch_resume(g_presence_timer); + } +} +static void presence_send(void) { @autoreleasepool { // on presence_queue() + pthread_mutex_lock(&g_presence_lock); + NSData *body=g_presence_waiting; unsigned status=g_presence_waiting_status; g_presence_waiting=nil; + pthread_mutex_unlock(&g_presence_lock); + if (!body) return; // a send queued earlier already took this publish + NSData *identity=dm_nextendo_api_identity(); + uint32_t result=identity?presence_post(body,identity):DM_ACCOUNT_FAIL; + if (result && !g_presence_failing) fprintf(stderr,"[dm] [RED] nextendo: presence not sent (the game is not told, as on a console; the next publish tries again)\n"); + g_presence_failing=result!=0; + presence_keep(!result&&status?body:nil); +} } +#ifdef DM_NEXTENDO_API_TEST +void dm_nextendo_social_flush(void) { dispatch_sync(presence_queue(),^{}); } +#endif +static NSString *game_title(void) { return [@DM_GAME_ID lowercaseString]; } +static NSString *game_name(void) { // the app's name, the game's title ID without one + id name=[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"]; + return [name isKindOfClass:NSString.class]&&[name length]?name:game_title(); +} +// The game's own description of what the player does (UserPresence::SetDescription), which Nextendo shows beside the game's name. The SDK keeps +// it in the application field, a run of NUL-terminated strings, key and value in turn, up to an empty key (nn::friends::detail::PresenceAccessor; +// Mario Kart 8 Deluxe's SearchKey sdk+0x11c950), under the key sys_description. "" without one or for a field that does not end its strings +static NSString *presence_description(const uint8_t *field,size_t size) { + size_t at=0; + while (at=size) return @""; + const char *value=(const char *)field+at; size_t value_length=strnlen(value,size-at); if (at+value_length>=size) return @""; at+=value_length+1; + if (key_length==15 && !memcmp(key,"sys_description",15)) + return [[NSString alloc] initWithBytes:value length:value_length encoding:NSUTF8StringEncoding] ?: @""; + } + return @""; +} +uint32_t dm_nextendo_social_publish(unsigned status,const uint8_t *app_field,size_t size) { @autoreleasepool { + if(status>2||size>DM_SOCIAL_APP_FIELD||(size&&!app_field))return DM_ACCOUNT_FAIL; + NSData *identity=dm_nextendo_api_identity();if(!identity)return DM_ACCOUNT_FAIL; + NSData *field=[NSData dataWithBytes:app_field length:size]; + NSDictionary *object=@{@"status":@(status),@"app_id":game_title(),@"jeu":game_name(),@"app_field":[field base64EncodedStringWithOptions:0], + @"plateforme":@"nxnative",@"app_detail":size?presence_description(app_field,size):@""}; + NSData *body=[NSJSONSerialization dataWithJSONObject:object options:0 error:nil]; + if(!body)return DM_ACCOUNT_FAIL; + pthread_mutex_lock(&g_presence_lock); g_presence_waiting=body; g_presence_waiting_status=status; pthread_mutex_unlock(&g_presence_lock); + dispatch_async(presence_queue(),^{ presence_send(); }); + return 0; +} } + +// ---- The account's Mii, from the start of a Nextendo session (loader.c nextendo_main) ---- +void dm_guest_host_wait_begin(void); +void dm_guest_host_wait_end(void); +enum { MII_STORE_SIZE=0x44, PROFILE_WAIT_S=5 }; +static dispatch_group_t g_profile_fetch; // the account's profile, asked for once at the start +static NSData *g_account_mii; // its Mii's StoreData, written before g_profile_fetch completes + +// /api/profile's Mii: the base64 of a Switch StoreData. nil without one, or for anything else (logged) +static NSData *account_mii_fetch(void) { + size_t capacity=1024*1024,size=0; uint8_t *buffer=malloc(capacity); if(!buffer)return nil; + uint32_t result=dm_nextendo_api_request("profile",NULL,0,buffer,capacity,&size); + NSDictionary *answer=result?nil:[NSJSONSerialization JSONObjectWithData:[NSData dataWithBytesNoCopy:buffer length:size freeWhenDone:NO] options:0 error:nil]; + free(buffer); + if(result)return nil; // dm_nextendo_api_request logged the refusal + id profile=[answer isKindOfClass:NSDictionary.class]?answer[@"profile"]:nil, mii=[profile isKindOfClass:NSDictionary.class]?profile[@"mii"]:nil; + if(![mii isKindOfClass:NSString.class]||![mii length]){fprintf(stderr,"[dm] nextendo: the account has no Mii on Nextendo\n");return nil;} + NSData *store=[[NSData alloc] initWithBase64EncodedString:mii options:0]; + if(store.length!=MII_STORE_SIZE){fprintf(stderr,"[dm] [RED] nextendo: the account's Mii is not a StoreData (%lu bytes): it is not listed\n",(unsigned long)store.length);return nil;} + return store; +} +// hle_mii.c: the account's Mii for the game's Mii database, waiting a few seconds at most for the profile asked for at the start +int dm_nextendo_account_mii(uint8_t store[MII_STORE_SIZE]) { + if(!store||!g_profile_fetch||!dm_net_nextendo_enabled())return 0; + dm_guest_host_wait_begin(); long late=dispatch_group_wait(g_profile_fetch,dispatch_time(DISPATCH_TIME_NOW,PROFILE_WAIT_S*NSEC_PER_SEC)); dm_guest_host_wait_end(); + if(late){fprintf(stderr,"[dm] [RED] nextendo: the account's profile did not arrive in %d s: its Mii is not listed this run\n",PROFILE_WAIT_S);return 0;} + if(g_account_mii.length!=MII_STORE_SIZE)return 0; + memcpy(store,g_account_mii.bytes,MII_STORE_SIZE); return 1; +} + +// No play time is sent. Nextendo keeps each game's play time per account, and since 2026-11-15 only its own emulator may write it: a history +// write from a third-party app's token answers 403 ("Le jeton de jeu d'une application tierce n'ouvre pas cette route"), and its developer wiki +// says writing the history is not open to OAuth tokens +void dm_nextendo_session_start(void) { + static atomic_bool started; if(atomic_exchange(&started,true))return; + dispatch_queue_t queue=dispatch_get_global_queue(QOS_CLASS_UTILITY,0); + g_profile_fetch=dispatch_group_create(); + dispatch_group_async(g_profile_fetch,queue,^{ @autoreleasepool { g_account_mii=account_mii_fetch(); } }); +} diff --git a/dm/host/hle_nextendo_x509.c b/dm/host/hle_nextendo_x509.c new file mode 100644 index 0000000000..7ab6349001 --- /dev/null +++ b/dm/host/hle_nextendo_x509.c @@ -0,0 +1,102 @@ +// An alternative verifier for the service's explicit private CA, not public PKI. +// OpenSSL applies strict X.509 chain, purpose, SAN, strength and current-time checks. +// Apple public-PKI maximum leaf lifetimes do not define this private CA's lifetime. +#include "nextendo_x509.h" +#include +#include +#ifdef DM_OPENSSL_X509 +#include +#include +#include +#include + +static bool valid_host(const char *host) { + if (!host) return false; + size_t length = strnlen(host, 254), label = 0; + if (!length || length > 253) return false; + for (size_t i = 0; i < length; i++) { + unsigned char c = (unsigned char)host[i]; + if (c == '.') { if (!label || host[i - 1] == '-') return false; label = 0; } + else { + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '-') || (!label && c == '-') || ++label > 63) return false; + } + } + return label && host[length - 1] != '-'; +} +static X509 *certificate(const uint8_t *bytes, size_t size) { + if (!bytes || !size || size > 65536) return NULL; + const unsigned char *cursor = bytes; + X509 *value = d2i_X509(NULL, &cursor, (long)size); + if (value && cursor != bytes + size) { X509_free(value); value = NULL; } + return value; +} +bool dm_nextendo_x509_available(void) { return true; } +bool dm_nextendo_x509_verify_pin(const char *host, const uint8_t *pin, size_t pin_size, + const uint8_t *bytes, size_t size) { + if (!valid_host(host) || !pin || !bytes || !size || size > 65536 || pin_size != size || + CRYPTO_memcmp(pin, bytes, size)) return false; + X509 *leaf = certificate(bytes, size); if (!leaf) return false; + EVP_PKEY *public_key = X509_get_pubkey(leaf); + ASN1_TIME *now = ASN1_TIME_set(NULL, time(NULL)); + int before = now ? ASN1_TIME_compare(X509_get0_notBefore(leaf), now) : -2; + int after = now ? ASN1_TIME_compare(X509_get0_notAfter(leaf), now) : -2; + int signature_bits = 0; + // The enrolled route supplies identity, rather than an absent SAN. Retain + // current-time, server-purpose, strong-key and self-signature checks. TLS + // independently proves possession of this exact certificate's private key. + bool valid = public_key && EVP_PKEY_security_bits(public_key) >= 112 && + X509_NAME_cmp(X509_get_subject_name(leaf), X509_get_issuer_name(leaf)) == 0 && + before != -2 && before <= 0 && after >= 0 && + X509_check_purpose(leaf, X509_PURPOSE_SSL_SERVER, 0) == 1 && + X509_get_signature_info(leaf, NULL, NULL, &signature_bits, NULL) == 1 && signature_bits >= 112 && + X509_verify(leaf, public_key) == 1; + // Some private endpoints serve their self-signed CA-marked certificate + // directly. Exact peer-DER equality does not grant it issuer authority: + // a different leaf signed by this key still fails the comparison above. + ASN1_TIME_free(now); EVP_PKEY_free(public_key); X509_free(leaf); ERR_clear_error(); + return valid; +} +bool dm_nextendo_x509_verify(const char *host, const uint8_t *anchor, size_t anchor_size, + const uint8_t *const *chain, const size_t *sizes, size_t count) { + if (!valid_host(host) || !chain || !sizes || !count || count > 16) return false; + bool ok = false; size_t total = 0; + X509 *root = certificate(anchor, anchor_size), *leaf = NULL; + X509_STORE *store = X509_STORE_new(); + X509_STORE_CTX *context = X509_STORE_CTX_new(); + STACK_OF(X509) *untrusted = sk_X509_new_null(); + if (!root || !store || !context || !untrusted || X509_check_ca(root) <= 0 || + X509_check_issued(root, root) != X509_V_OK || X509_STORE_add_cert(store, root) != 1) goto done; + for (size_t i = 0; i < count; i++) { + if (!sizes[i] || sizes[i] > 65536 || total > 1048576 - sizes[i]) goto done; + total += sizes[i]; X509 *item = certificate(chain[i], sizes[i]); if (!item) goto done; + if (!i) leaf = item; + else if (!sk_X509_push(untrusted, item)) { X509_free(item); goto done; } + } + if (X509_STORE_CTX_init(context, store, leaf, untrusted) != 1) goto done; + X509_VERIFY_PARAM *parameters = X509_STORE_CTX_get0_param(context); + if (!parameters || X509_VERIFY_PARAM_set_purpose(parameters, X509_PURPOSE_SSL_SERVER) != 1 || + X509_VERIFY_PARAM_set_flags(parameters, X509_V_FLAG_X509_STRICT | X509_V_FLAG_CHECK_SS_SIGNATURE) != 1 || + X509_VERIFY_PARAM_set1_host(parameters, host, 0) != 1) goto done; + X509_VERIFY_PARAM_set_hostflags(parameters, X509_CHECK_FLAG_NEVER_CHECK_SUBJECT | X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + X509_VERIFY_PARAM_set_auth_level(parameters, 2); + X509_VERIFY_PARAM_set_depth(parameters, 12); + // No default paths, partial-chain trust, time suppression, custom verify + // callback or automatically adopted certificate supplied by the peer. + ok = X509_verify_cert(context) == 1; +done: + X509_STORE_CTX_free(context); X509_STORE_free(store); X509_free(root); + X509_free(leaf); sk_X509_pop_free(untrusted, X509_free); ERR_clear_error(); + return ok; +} +#else +bool dm_nextendo_x509_available(void) { return false; } +bool dm_nextendo_x509_verify_pin(const char *host, const uint8_t *pin, size_t pin_size, + const uint8_t *leaf, size_t leaf_size) { + (void)host; (void)pin; (void)pin_size; (void)leaf; (void)leaf_size; return false; +} +bool dm_nextendo_x509_verify(const char *host, const uint8_t *anchor, size_t anchor_size, + const uint8_t *const *chain, const size_t *sizes, size_t count) { + (void)host; (void)anchor; (void)anchor_size; (void)chain; (void)sizes; (void)count; return false; +} +#endif diff --git a/dm/host/hle_nsd.c b/dm/host/hle_nsd.c new file mode 100644 index 0000000000..52b49af455 --- /dev/null +++ b/dm/host/hle_nsd.c @@ -0,0 +1,6 @@ +// The NSD service boundary is separate from unrelated account/parental-control fixtures. +#include "hle.h" +#include "nsd.h" + +HLE_FORCE("_ZN2nn3nsd7ResolveEPNS0_4FqdnERKS1_", "bounded retail Fqdn expansion in explicit Nextendo mode", Result, h_nsd_Resolve, void *out, const void *in) { return dm_nsd_resolve(out,in); } +HLE_FORCE("_ZN2nn3nsd9ResolveExEPNS0_4FqdnERKS1_", "bounded retail Fqdn expansion in explicit Nextendo mode", Result, h_nsd_ResolveEx, void *out, const void *in) { return dm_nsd_resolve(out,in); } diff --git a/dm/host/hle_nsd_backend.c b/dm/host/hle_nsd_backend.c new file mode 100644 index 0000000000..7e71e0a4de --- /dev/null +++ b/dm/host/hle_nsd_backend.c @@ -0,0 +1,48 @@ +#include "nsd.h" +#include "net_socket.h" +#include + +static int valid_fqdn(const char *name, size_t length) { + if (!length || length > 253) return 0; + size_t label = 0; + for (size_t i = 0; i < length; i++) { + unsigned char c = (unsigned char)name[i]; + if (c == '.') { + if (!label || name[i - 1] == '-') return 0; + label = 0; continue; + } + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_')) return 0; + if ((!label && c == '-') || ++label > 63) return 0; + } + return label && name[length - 1] != '-'; +} + +uint32_t dm_nsd_resolve(void *output, const void *input) { + // Ordinary offline/LAN exports retain their existing service boundary. + // No DNS query, socket connection or success placeholder occurs here. + if (!output || !input || !dm_net_nextendo_enabled()) return DM_NSD_FAIL; + const char *source = input; + size_t length = strnlen(source, DM_NSD_FQDN_CAPACITY); + if (!length || length == DM_NSD_FQDN_CAPACITY) return DM_NSD_FAIL; + char expanded[DM_NSD_FQDN_CAPACITY]; size_t written = 0; + for (size_t i = 0; i < length; i++) { + unsigned char c = (unsigned char)source[i]; + size_t needed = c == '%' ? 3 : 1; + if (written + needed >= sizeof expanded) return DM_NSD_FAIL; + if (c == '%') { memcpy(expanded + written, "lp1", 3); written += 3; } + else expanded[written++] = (char)(c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c); + } + if (written && expanded[written - 1] == '.') written--; + expanded[written] = 0; + if (!valid_fqdn(expanded, written)) return DM_NSD_FAIL; + // Retail NSD account aliases are logical service names, not IP redirects. + // The subsequent socket resolver still enforces its scoped Nextendo policy. + const char *resolved = expanded; + if (!strcmp(expanded, "accounts.nintendo.com") || !strcmp(expanded, "api.accounts.nintendo.com")) + resolved = "e0d67c509fb203858ebcb2fe3f88c2aa.baas.nintendo.com"; + // Compute first so in-place and overlapping Fqdn buffers remain valid. + char result[DM_NSD_FQDN_CAPACITY] = {0}; + memcpy(result, resolved, strlen(resolved)); + memcpy(output, result, sizeof result); + return 0; +} diff --git a/dm/host/hle_offline.c b/dm/host/hle_offline.c index c3621bb9a4..92a040e248 100644 --- a/dm/host/hle_offline.c +++ b/dm/host/hle_offline.c @@ -1,10 +1,10 @@ -// Networking and peripheral system services (out of scope: online play, local wireless, friends, telemetry, SSL) as seen through newer SDKs: all made "unavailable", the game takes its offline branch. +// Local IPv4 sockets and the LDN bridge are opt-in; other peripheral/online services retain their offline fallbacks. // Only entry points that go to a service are hooked; library functions that only read and write the game's own buffers (prepo Add / Array / Struct, err ErrorResultVariant, friends getters, socket byte-order conversion) keep running in the SDK. // Return convention as in hle_friends.c: Result returns RES_FAIL ("saved / submitted" kinds return RES_OK so the game does not retry); bool returns false; events get a bound SystemEvent that never fires. #include "hle.h" #include "hle_net.h" +#include "net_socket.h" -static _Alignas(16) uint8_t g_ev_ldn[0x100]; // ---------- prepo: telemetry reports. Saving / submitting all report success; nothing is sent ---------- HLE_FORCE("_ZN2nn5prepo10PlayReport4SaveERKNS_7account3UidE", "telemetry report save (user); nothing is sent, reports success", Result, h_prepo_SaveU, void *self, const void *uid) { (void)self; (void)uid; return RES_OK; } @@ -13,7 +13,7 @@ HLE_FORCE("_ZN2nn5prepo10PlayReport4SaveEv", "telemetry report save; nothing is // own default context has: GetCompletionEvent makes a signaled event (sdk+0x5a9298), GetResult answers 0 and the destructor does nothing, so only this call is taken over. Naked because x8 is the // hidden result pointer, 8 bytes on the caller's stack, which no C return type can name __attribute__((naked)) static void h_prepo_Send(void) { __asm__("str xzr, [x8]\n ret"); } -DM_REGISTER("swforce", hle_force_ent, hle_force_h_prepo_Send, {"_ZN2nn5prepo10PlayReport4SendERKNS_7account3UidE", (void *)h_prepo_Send, "telemetry report send; nothing is sent, a default context completes at once with success"}); +DM_REGISTER("swforce", hle_force_ent, hle_force_h_prepo_Send, {"_ZN2nn5prepo10PlayReport4SendERKNS_7account3UidE", (void *)h_prepo_Send, "telemetry report send; nothing is sent, a default context completes at once with success", NULL}); HLE_FORCE("_ZN2nn5prepo10InitializeEv", "telemetry init: the original connects to the prepo service (through sm), the host has no service process; no-op (Engage calls it explicitly)", Result, h_prepo_Init, void) { return RES_OK; } // Add the session ID / connection status to a report: on hardware these first connect to the prepo service for the session (Super Mario 3D World + Bowser's Fury calls them entering the save select); the host adds nothing and reports success HLE_FORCE("_ZN2nn5prepo12AddSessionIdEPNS0_10PlayReportEPKc", "telemetry session ID: no service connection, nothing added, reports success", Result, h_prepo_AddSess, void *rep, const char *key) { (void)rep; (void)key; return RES_OK; } @@ -21,36 +21,7 @@ HLE_FORCE("_ZN2nn5prepo27AddInternetConnectionStatusEPNS0_10PlayReportEPKcS4_S4_ HLE_FORCE("_ZN2nn5prepo28RequestImmediateTransmissionEv", "telemetry immediate upload; nothing is sent, reports success", Result, h_prepo_Tx, void) { return RES_OK; } HLE_FORCE("_ZN2nn5prepo21GetTransmissionStatusEPNS0_18TransmissionStatusE", "telemetry upload status: idle (nothing is queued)", Result, h_prepo_TxStatus, uint32_t *st) { if (st) *st = 0; return RES_OK; } -// ---------- ldn: local wireless. Initialization fails, state is always "none" ---------- -HLE_FORCE("_ZN2nn3ldn10InitializeEv", "local wireless (cut): initialization fails", Result, h_ldn_Init, void) { return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn8FinalizeEv", "local wireless (cut)", void, h_ldn_Fini, void) {} -HLE_FORCE("_ZN2nn3ldn8GetStateEv", "local wireless (cut): state 0 (none)", int, h_ldn_State, void) { return 0; } -HLE_FORCE("_ZN2nn3ldn22AttachStateChangeEventEPNS_2os15SystemEventTypeE", "local wireless state event: bound, never fires", void, h_ldn_Attach, void *ev) { hle_bind_system_event(ev, 0); (void)g_ev_ldn; } -HLE_FORCE("_ZN2nn3ldn11OpenStationEv", "local wireless (cut)", Result, h_ldn_OpenSta, void) { return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn12CloseStationEv", "local wireless (cut)", Result, h_ldn_CloseSta, void) { return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn15OpenAccessPointEv", "local wireless (cut)", Result, h_ldn_OpenAp, void) { return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn16CloseAccessPointEv", "local wireless (cut)", Result, h_ldn_CloseAp, void) { return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn10DisconnectEv", "local wireless (cut)", Result, h_ldn_Disc, void) { return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn14DestroyNetworkEv", "local wireless (cut)", Result, h_ldn_Destroy, void) { return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn4ScanEPNS0_11NetworkInfoEPiiRKNS0_10ScanFilterEi", "local wireless scan (cut): 0 found", Result, h_ldn_Scan, void *out, int *n, int max, const void *f, int ch) { (void)out; (void)max; (void)f; (void)ch; if (n) *n = 0; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn11ScanPrivateEPNS0_11NetworkInfoEPiiRKNS0_10ScanFilterEi", "local wireless scan (cut): 0 found", Result, h_ldn_ScanP, void *out, int *n, int max, const void *f, int ch) { (void)out; (void)max; (void)f; (void)ch; if (n) *n = 0; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn13CreateNetworkERKNS0_13NetworkConfigERKNS0_14SecurityConfigERKNS0_10UserConfigE", "local wireless (cut)", Result, h_ldn_Create, - const void *a, const void *b, const void *c) { (void)a; (void)b; (void)c; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn20CreateNetworkPrivateERKNS0_13NetworkConfigERKNS0_14SecurityConfigERKNS0_17SecurityParameterERKNS0_10UserConfigEiPKNS0_12AddressEntryE", "local wireless (cut)", - Result, h_ldn_CreateP, const void *a, const void *b, const void *c, const void *d, int n, const void *e) { (void)a; (void)b; (void)c; (void)d; (void)n; (void)e; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn7ConnectERKNS0_11NetworkInfoERKNS0_14SecurityConfigERKNS0_10UserConfigEiNS0_13ConnectOptionE", "local wireless (cut)", Result, h_ldn_Connect, - const void *a, const void *b, const void *c, int v, int o) { (void)a; (void)b; (void)c; (void)v; (void)o; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn14ConnectPrivateERKNS0_13NetworkConfigERKNS0_14SecurityConfigERKNS0_17SecurityParameterERKNS0_10UserConfigEiNS0_13ConnectOptionE", "local wireless (cut)", - Result, h_ldn_ConnectP, const void *a, const void *b, const void *c, const void *d, int v, int o) { (void)a; (void)b; (void)c; (void)d; (void)v; (void)o; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn14GetNetworkInfoEPNS0_11NetworkInfoE", "local wireless (cut)", Result, h_ldn_NetInfo, void *o) { (void)o; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn14GetIpv4AddressEPNS0_11Ipv4AddressEPNS0_10SubnetMaskE", "local wireless (cut)", Result, h_ldn_Ip, uint32_t *a, uint32_t *m) { if (a) *a = 0; if (m) *m = 0; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn20GetSecurityParameterEPNS0_17SecurityParameterE", "local wireless (cut)", Result, h_ldn_SecPrm, void *o) { (void)o; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn16SetAdvertiseDataEPKvm", "local wireless (cut)", Result, h_ldn_Adv, const void *d, uint64_t n) { (void)d; (void)n; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn19GetDisconnectReasonEv", "local wireless (cut): 0", int, h_ldn_DiscReason, void) { return 0; } -HLE_FORCE("_ZN2nn3ldn20AddAcceptFilterEntryENS0_10MacAddressE", "local wireless (cut)", Result, h_ldn_Filter, uint64_t mac) { (void)mac; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn22SetStationAcceptPolicyENS0_12AcceptPolicyE", "local wireless (cut)", Result, h_ldn_Policy, int p) { (void)p; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn6RejectENS0_11Ipv4AddressE", "local wireless (cut)", Result, h_ldn_Reject, uint32_t a) { (void)a; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ldn16GetNetworkConfigEPNS0_13NetworkConfigE", "local wireless (cut)", Result, h_ldn_NetCfg, void *o) { (void)o; return RES_FAIL; } +// nn::ldn lives in hle_ldn.c (explicit DM_NETWORK=ldn). // ---------- bluetooth: BLE (Pokémon Violet 3.0.1 at boot, likely its Pokémon GO Plus + support). InitializeBle connects to bt and btm:u (an SDK abort without them); the host has no radio: // events never fire, scans find nothing, so the GATT calls after a connect are never reached ---------- @@ -67,32 +38,36 @@ HLE_FORCE("_ZN2nn9bluetooth16GetBleScanResultEPNS0_13BleScanResultEi", "BLE scan HLE_FORCE("_ZN2nn9bluetooth24GetBleConnectionInfoListEPNS0_17BleConnectionInfoEi", "BLE connections (cut): 0", int, h_bt_ConnList, void *out, int max) { (void)out; (void)max; return 0; } HLE_FORCE("_ZN2nn9bluetooth19ConnectToGattServerERKNS0_7AddressE", "BLE connect (cut)", Result, h_bt_Connect, const void *a) { (void)a; return RES_FAIL; } -// ---------- socket: aliases of the offline BSD service, including its process-local UDP transport ---------- -enum { SK_ENETDOWN = 50, SK_EAI_FAIL = 4 }; +// ---------- socket: aliases of hle_net.c's offline BSD service (process-local UDP); an explicit network mode uses the translated host transport ---------- +// A call with both forms: the network transport in an explicit network mode, hle_net.c's local service otherwise; a failure also sets the game's errno +#define SKD(net, local) dm_net_guest_errno(dm_net_enabled() ? (long)(net) : (long)(local)) +enum { SK_EAI_FAIL = 4 }; HLE_FORCE("_ZN2nn6socket10InitializeEPvmmi", "connects to the bsd socket service; offline, creates no session (cut)", Result, h_sk_Init4, void *mem, uint64_t sz, uint64_t alloc, int conc) { (void)mem; (void)sz; (void)alloc; (void)conc; return RES_OK; } -HLE_FORCE("_ZN2nn6socket8FinalizeEv", "pairs with Initialize (cut)", Result, h_sk_Fini, void) { return RES_OK; } -HLE_FORCE("_ZN2nn6socket12GetLastErrnoEv", "local UDP (offline BSD service)", int, h_sk_Errno, void) { return dm_sk_errno(); } -HLE_FORCE("_ZN2nn6socket6SocketEiii", "local UDP (offline BSD service)", int, h_sk_Socket3i, int a, int b, int c) { return dm_sk_socket(a, b, c); } -HLE_FORCE("_ZN2nn6socket8ShutdownEii", "local UDP (offline BSD service)", int, h_sk_Shutdown, int s, int h) { return dm_sk_shutdown(s, h); } -HLE_FORCE("_ZN2nn6socket4BindEiPK8sockaddrj", "local UDP (offline BSD service)", int, h_sk_Bind, int s, const void *a, unsigned n) { return dm_sk_bind(s, a, n); } -HLE_FORCE("_ZN2nn6socket4PollEP6pollfdmi", "waits on process-local UDP and event descriptors", int, h_sk_Poll, void *p, uint64_t n, int t) { return dm_sk_poll(p, n, t); } +HLE_FORCE_WAIT("_ZN2nn6socket8FinalizeEv", "release the host's LAN descriptors, if enabled", Result, h_sk_Fini, void) { dm_net_finalize(); return RES_OK; } +HLE_FORCE("_ZN2nn6socket12GetLastErrnoEv", "the game's errno in a network mode (as detail::GetLastErrno reads it); the local service's otherwise", int, h_sk_Errno, void) { return dm_net_enabled() ? dm_net_guest_errno_get() : dm_sk_errno(); } +HLE_FORCE("_ZN2nn6socket6SocketEiii", "socket call: the local service offline, the transport in a network mode", int, h_sk_Socket3i, int a, int b, int c) { return SKD(dm_net_socket(a, b, c), dm_sk_socket(a, b, c)); } +HLE_FORCE("_ZN2nn6socket8ShutdownEii", "socket call: the local service offline, the transport in a network mode", int, h_sk_Shutdown, int s, int h) { return SKD(dm_net_shutdown(s, h), dm_sk_shutdown(s, h)); } +HLE_FORCE("_ZN2nn6socket4BindEiPK8sockaddrj", "socket call: the local service offline, the transport in a network mode", int, h_sk_Bind, int s, const void *a, unsigned n) { return SKD(dm_net_bind(s, a, n), dm_sk_bind(s, a, n)); } +HLE_FORCE_WAIT("_ZN2nn6socket4PollEP6pollfdmi", "waits on process-local UDP and event descriptors offline, on the transport in a network mode", int, h_sk_PollPlain, void *p, uint64_t n, int t) { return dm_net_guest_errno(dm_sk_poll(p, n, t)); } // SDK 4's Select with plain fd_set / timeval (Dark Souls Remastered) -HLE_FORCE("_ZN2nn6socket6SelectEiP6fd_setS2_S2_P7timeval", "Poll over process-local UDP and event descriptor sets", int, h_sk_Select2, int n, void *r, void *w, void *e, void *t) { return dm_sk_select(n, r, w, e, t); } -HLE_FORCE("_ZN2nn6socket6SendToEiPKvmiPK8sockaddrj", "local UDP (offline BSD service)", long, h_sk_SendTo, int s, const void *b, unsigned long n, int f, const void *a, unsigned al) { return dm_sk_sendto(s, b, n, f, a, al); } -HLE_FORCE("_ZN2nn6socket6SendToEiPKvmNS0_7MsgFlagEPKNS0_8SockAddrEj", "local UDP (offline BSD service)", long, h_sk_SendTo2, int s, const void *b, unsigned long n, int f, const void *a, unsigned al) { return dm_sk_sendto(s, b, n, f, a, al); } -HLE_FORCE("_ZN2nn6socket8RecvFromEiPvmiP8sockaddrPj", "local UDP (offline BSD service)", long, h_sk_RecvFrom2, int s, void *b, unsigned long n, int f, void *a, unsigned *al) { return dm_sk_recvfrom(s, b, n, f, a, al); } -HLE_FORCE("_ZN2nn6socket11GetAddrInfoEPKcS2_PK8addrinfoPPS3_", "name resolution (cut): EAI_FAIL", int, h_sk_Gai2, const char *h, const char *s, const void *hint, void **res) { (void)h; (void)s; (void)hint; if (res) *res = NULL; return SK_EAI_FAIL; } -HLE_FORCE("_ZN2nn6socket12FreeAddrInfoEP8addrinfo", "pairs with GetAddrInfo (cut)", void, h_sk_FreeAi2, void *ai) { (void)ai; } +HLE_FORCE_WAIT("_ZN2nn6socket6SelectEiP6fd_setS2_S2_P7timeval", "Poll over its sets: process-local descriptors offline, the transport in a network mode", int, h_sk_Select2, int n, void *r, void *w, void *e, void *t) { return dm_net_guest_errno(dm_sk_select(n, r, w, e, t)); } +HLE_FORCE_WAIT("_ZN2nn6socket6SendToEiPKvmiPK8sockaddrj", "socket call: the local service offline, the transport in a network mode", long, h_sk_SendTo, int s, const void *b, unsigned long n, int f, const void *a, unsigned al) { return SKD(dm_net_send(s, b, n, f, a, al), dm_sk_sendto(s, b, n, f, a, al)); } +HLE_FORCE_WAIT("_ZN2nn6socket6SendToEiPKvmNS0_7MsgFlagEPKNS0_8SockAddrEj", "socket call: the local service offline, the transport in a network mode", long, h_sk_SendTo2, int s, const void *b, unsigned long n, int f, const void *a, unsigned al) { return SKD(dm_net_send(s, b, n, f, a, al), dm_sk_sendto(s, b, n, f, a, al)); } +HLE_FORCE_WAIT("_ZN2nn6socket8RecvFromEiPvmiP8sockaddrPj", "socket call: the local service offline, the transport in a network mode", long, h_sk_RecvFrom2, int s, void *b, unsigned long n, int f, void *a, unsigned *al) { return SKD(dm_net_recv(s, b, n, f, a, al), dm_sk_recvfrom(s, b, n, f, a, al)); } +HLE_FORCE_WAIT("_ZN2nn6socket11GetAddrInfoEPKcS2_PK8addrinfoPPS3_", "SDK 4 addrinfo layout; name resolution, offline by default", int, h_sk_Gai2, const char *h, const char *s, const void *hint, void **res) { return dm_net_getaddrinfo_legacy(h, s, hint, res); } +HLE_FORCE("_ZN2nn6socket12FreeAddrInfoEP8addrinfo", "release only resolver allocations owned by the host", void, h_sk_FreeAi2, void *ai) { dm_net_freeaddrinfo(ai); } HLE_FORCE("_ZN2nn6socket11GAIStrErrorENS0_7AiErrnoE", "resolver error text", const char *, h_sk_GaiStr, int e) { (void)e; return "network unavailable"; } // SDK 11's overloads with plain sockaddr / int arguments (Big Brain Academy: Brain vs. Brain, through Pia) -HLE_FORCE("_ZN2nn6socket7ConnectEiPK8sockaddrj", "local UDP (offline BSD service)", int, h_sk_Connect2, int s, const void *a, unsigned n) { return dm_sk_connect(s, a, n); } -HLE_FORCE("_ZN2nn6socket6AcceptEiP8sockaddrPj", "offline (cut)", int, h_sk_Accept2, int s, void *a, unsigned *n) { (void)s; (void)a; (void)n; return -1; } -HLE_FORCE("_ZN2nn6socket11GetSockNameEiP8sockaddrPj", "local UDP (offline BSD service)", int, h_sk_GetSockName2, int s, void *a, unsigned *n) { return dm_sk_name(s, a, n, 0); } -HLE_FORCE("_ZN2nn6socket10GetSockOptEiiiPvPj", "local UDP (offline BSD service)", int, h_sk_GetSockOpt2, int s, int l, int o, void *v, unsigned *n) { return dm_sk_getopt(s, l, o, v, n); } -HLE_FORCE("_ZN2nn6socket10SetSockOptEiiiPKvj", "local UDP (offline BSD service)", int, h_sk_SetSockOpt2, int s, int l, int o, const void *v, unsigned n) { return dm_sk_setopt(s, l, o, v, n); } -HLE_FORCE("_ZN2nn6socket5FcntlEiiz", "local UDP (offline BSD service)", int, h_sk_Fcntl2, int s, int c, int v) { return dm_sk_fcntl(s, c, v); } -HLE_FORCE("_ZN2nn6socket4RecvEiPvmi", "local UDP (offline BSD service)", long, h_sk_Recv2, int s, void *b, unsigned long n, int f) { return dm_sk_recvfrom(s, b, n, f, NULL, NULL); } -HLE_FORCE("_ZN2nn6socket4SendEiPKvmi", "local UDP (offline BSD service)", long, h_sk_Send2, int s, const void *b, unsigned long n, int f) { return dm_sk_sendto(s, b, n, f, NULL, 0); } +HLE_FORCE_WAIT("_ZN2nn6socket7ConnectEiPK8sockaddrj", "socket call: the local service offline, the transport in a network mode", int, h_sk_Connect2, int s, const void *a, unsigned n) { return SKD(dm_net_connect(s, a, n), dm_sk_connect(s, a, n)); } +HLE_FORCE_WAIT("_ZN2nn6socket6AcceptEiP8sockaddrPj", "socket call: the local service offline, the transport in a network mode", int, h_sk_Accept2, int s, void *a, unsigned *n) { return SKD(dm_net_accept(s, a, n), dm_sk_unavailable()); } +HLE_FORCE("_ZN2nn6socket11GetSockNameEiP8sockaddrPj", "socket call: the local service offline, the transport in a network mode", int, h_sk_GetSockName2, int s, void *a, unsigned *n) { return SKD(dm_net_name(s, a, n, 0), dm_sk_name(s, a, n, 0)); } +/* GetPeerName registered in hle_net.c to avoid duplicate forced takeover entries */ +HLE_FORCE_WAIT("_ZN2nn6socket13GetHostByNameEPKc", "SDK 4 resolver, offline by default", void *, h_sk_GetHostByName4, const char *name) { return dm_net_gethostbyname(name); } +HLE_FORCE("_ZN2nn6socket10GetSockOptEiiiPvPj", "socket call: the local service offline, the transport in a network mode", int, h_sk_GetSockOpt2, int s, int l, int o, void *v, unsigned *n) { return SKD(dm_net_sockopt(s, l, o, v, n, 0), dm_sk_getopt(s, l, o, v, n)); } +HLE_FORCE("_ZN2nn6socket10SetSockOptEiiiPKvj", "socket call: the local service offline, the transport in a network mode", int, h_sk_SetSockOpt2, int s, int l, int o, const void *v, unsigned n) { return SKD(dm_net_sockopt(s, l, o, (void *)v, &n, 1), dm_sk_setopt(s, l, o, v, n)); } +HLE_FORCE("_ZN2nn6socket5FcntlEiiz", "socket call: the local service offline, the transport in a network mode; Switch variadic argument is in x2", int, h_sk_Fcntl2, int s, int c, int flags) { return SKD(dm_net_fcntl(s, c, flags), dm_sk_fcntl(s, c, flags)); } +HLE_FORCE_WAIT("_ZN2nn6socket4RecvEiPvmi", "socket call: the local service offline, the transport in a network mode", long, h_sk_Recv2, int s, void *b, unsigned long n, int f) { return SKD(dm_net_recv(s, b, n, f, NULL, NULL), dm_sk_recvfrom(s, b, n, f, NULL, NULL)); } +HLE_FORCE_WAIT("_ZN2nn6socket4SendEiPKvmi", "socket call: the local service offline, the transport in a network mode", long, h_sk_Send2, int s, const void *b, unsigned long n, int f) { return SKD(dm_net_send(s, b, n, f, NULL, 0), dm_sk_sendto(s, b, n, f, NULL, 0)); } // ---------- irsensor: the Joy-Con IR camera (Big Brain Academy: Brain vs. Brain's input layer makes one per controller). The host has none: every camera is unconnected, // processors cannot run and report no states. The default-config getters and MakeRect only fill the game's structs and keep running in the SDK ---------- @@ -120,25 +95,20 @@ HLE_FORCE("_ZN2nn8irsensor30GetHandAnalysisSilhouetteStateEPNS0_27HandAnalysisSi HLE_FORCE("_ZN2nn8irsensor30GetImageTransferProcessorStateEPNS0_27ImageTransferProcessorStateEPvmRKNS0_14IrCameraHandleE", "IR camera (cut)", Result, h_irs_ImageState, void *s, void *b, size_t n, const void *h) { (void)s; (void)b; (void)n; (void)h; return RES_FAIL; } -// ---------- ssl: offline, creating a context fails ---------- -HLE_FORCE("_ZN2nn3ssl7Context15ImportClientPkiEPmPKcS4_jj", "SSL (cut)", Result, h_ssl_ImpCli, void *self, uint64_t *id, const char *a, const char *b, unsigned x, unsigned y) { (void)self; (void)a; (void)b; (void)x; (void)y; if (id) *id = 0; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ssl7Context15ImportServerPkiEPmPKcjNS0_17CertificateFormatE", "SSL (cut)", Result, h_ssl_ImpSrv, void *self, uint64_t *id, const char *a, unsigned n, int f) { (void)self; (void)a; (void)n; (void)f; if (id) *id = 0; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ssl7Context9ImportCrlEPmPKcj", "SSL (cut)", Result, h_ssl_ImpCrl, void *self, uint64_t *id, const char *a, unsigned n) { (void)self; (void)a; (void)n; if (id) *id = 0; return RES_FAIL; } -HLE_FORCE("_ZN2nn3ssl14BuiltInManager22GetBuiltInCertificatesEPPNS0_26BuiltInCertificateInfoBaseEPhjPNS0_15CaCertificateIdEj", "SSL (cut)", Result, h_ssl_Certs, - void **out, uint8_t *buf, unsigned bn, void *ids, unsigned n) { (void)buf; (void)bn; (void)ids; (void)n; if (out) *out = NULL; return RES_FAIL; } - -// ---------- nifm / nsd: offline ---------- -HLE_FORCE("_ZN2nn4nifm19SetLocalNetworkModeEb", "offline: the local network mode switch is ignored", void, h_nifm_LocalMode, unsigned on) { (void)on; } -HLE_FORCE("_ZN2nn4nifm27SubmitNetworkRequestAndWaitEv", "offline: the network request is not submitted (returns at once, IsNetworkAvailable is always false)", void, h_nifm_SubmitWait, void) {} -HLE_FORCE("_ZN2nn4nifm22GetCurrentIpConfigInfoEP7in_addrS2_S2_S2_S2_", "offline: no IP configuration", Result, h_nifm_IpCfg, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e) { - uint32_t *p[5] = {a, b, c, d, e}; for (int i = 0; i < 5; i++) if (p[i]) *p[i] = 0; return RES_FAIL; +// nn::ssl lives in hle_ssl.c; it remains unavailable unless networking is enabled. + +// ---------- nifm / nsd: explicit LAN uses host IP configuration; NSD retains its offline boundary ---------- +HLE_FORCE("_ZN2nn4nifm19SetLocalNetworkModeEb", "host network mode is selected explicitly at launch, not by the guest", void, h_nifm_LocalMode, unsigned on) { (void)on; } +HLE_FORCE_WAIT("_ZN2nn4nifm27SubmitNetworkRequestAndWaitEv", "offline by default; explicit LAN waits for the actual request state", void, h_nifm_SubmitWait, void) { dm_nifm_submit_wait(); } +HLE_FORCE("_ZN2nn4nifm22GetCurrentIpConfigInfoEP7in_addrS2_S2_S2_S2_", "actual host IPv4 configuration in explicit LAN mode; unavailable otherwise", Result, h_nifm_IpCfg, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e) { + return dm_net_ipconfig(a, b, c, d, e) ? RES_FAIL : RES_OK; } // SDK 10's functions of the same name take socket::InAddr / in_addr, exactly the other way round from the generation above and in hle_net.c (Super Mario 3D World + Bowser's Fury) -HLE_FORCE("_ZN2nn4nifm22GetCurrentIpConfigInfoEPNS_6socket6InAddrES3_S3_S3_S3_", "offline: no IP configuration (SDK 10 overload)", Result, h_nifm_IpCfg10, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e) { - uint32_t *p[5] = {a, b, c, d, e}; for (int i = 0; i < 5; i++) if (p[i]) *p[i] = 0; return RES_FAIL; +HLE_FORCE("_ZN2nn4nifm22GetCurrentIpConfigInfoEPNS_6socket6InAddrES3_S3_S3_S3_", "actual host IPv4 configuration in explicit LAN mode (SDK 10 overload)", Result, h_nifm_IpCfg10, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e) { + return dm_net_ipconfig(a, b, c, d, e) ? RES_FAIL : RES_OK; } -HLE_FORCE("_ZN2nn4nifm26GetCurrentPrimaryIpAddressEP7in_addr", "offline: no IP (SDK 10 overload)", Result, h_nifm_GetIp10, uint32_t *a) { if (a) *a = 0; return RES_FAIL; } -// SDK 21 (Star Fox): the IPv4 and IPv6 configurations at once, with their counts +HLE_FORCE("_ZN2nn4nifm26GetCurrentPrimaryIpAddressEP7in_addr", "actual LAN IPv4 address, offline by default", Result, h_nifm_GetIp10, uint32_t *a) { if (!a) return RES_FAIL; *a = 0; return dm_net_ipconfig(a, NULL, NULL, NULL, NULL) ? RES_FAIL : RES_OK; } +// SDK 21 (Star Fox): the IPv4 and IPv6 configurations at once, with their counts. Failing in every mode: enumerating both configurations needs the guest layout of the structs, which LAN mode does not build HLE_FORCE("_ZN2nn4nifm18GetCurrentIpConfigEPNS0_10Ipv4ConfigEPiPNS0_10Ipv6ConfigES3_ii", "offline: no IP configuration (SDK 21 overload)", Result, h_nifm_IpCfg21, void *v4, int *n4, void *v6, int *n6, int c4, int c6) { (void)v4; (void)v6; (void)c4; (void)c6; if (n4) *n4 = 0; if (n6) *n6 = 0; return RES_FAIL; } // EnvironmentIdentifier = char[8]: retail environment "lp1" @@ -150,17 +120,6 @@ HLE_FORCE("_ZN2nn3nsd35GetApplicationServerEnvironmentTypeEv", "server environme // ---------- friends: newer SDK overloads ---------- HLE_FORCE("_ZN2nn7friends12SetAllocatorEPFPvmEPFvS1_mE", "friends library allocator; no session is created, ignored", void, h_fr_SetAlloc, void *a, void *f) { (void)a; (void)f; } -HLE_FORCE("_ZN2nn7friends13GetFriendListEPiPNS0_6FriendERKNS_7account3UidEiiRKNS0_12FriendFilterE", "friend list is empty (cut)", Result, h_fr_List2, - int *count, void *out, const void *uid, int off, int n, const void *filt) { (void)out; (void)uid; (void)off; (void)n; (void)filt; if (count) *count = 0; return RES_FAIL; } -// Super Kirby Clash (SDK 7.4) requests account IDs rather than Friend objects. These -// overloads need the same offline cut: no service connection, no entries, and failure. -HLE_FORCE("_ZN2nn7friends13GetFriendListEPiPNS_7account23NetworkServiceAccountIdEiiRKNS0_12FriendFilterE", "friend ID list is empty (cut)", Result, h_fr_IdList, - int *count, void *out, int off, int n, const void *filt) { (void)out; (void)off; (void)n; (void)filt; if (count) *count = 0; return RES_FAIL; } -HLE_FORCE("_ZN2nn7friends13GetFriendListEPiPNS_7account23NetworkServiceAccountIdERKNS2_3UidEiiRKNS0_12FriendFilterE", "friend ID list is empty (cut)", Result, h_fr_IdList2, - int *count, void *out, const void *uid, int off, int n, const void *filt) { (void)out; (void)uid; (void)off; (void)n; (void)filt; if (count) *count = 0; return RES_FAIL; } -HLE_FORCE("_ZN2nn7friends27CheckFriendListAvailabilityEPbRKNS_7account3UidE", "friend list unavailable (cut)", Result, h_fr_ListAvail, uint8_t *out, const void *uid) { (void)uid; *out = 0; return RES_OK; } -HLE_FORCE("_ZN2nn7friends25EnsureFriendListAvailableEPNS0_12AsyncContextERKNS_7account3UidE", "friend list (cut): the request fails at once", Result, h_fr_ListEnsure, void *ctx, const void *uid) { (void)ctx; (void)uid; return RES_FAIL; } -HLE_FORCE("_ZN2nn7friends12AsyncContext7HasDoneEPb", "async context: always done", Result, h_fr_AcHasDone, void *self, uint8_t *done) { (void)self; *done = 1; return RES_OK; } HLE_FORCE("_ZN2nn7friends14AddPlayHistoryERKNS_7account3UidERKNS0_26PlayHistoryRegistrationKeyERKNS0_15InAppScreenNameESA_", "play history is not registered (cut)", Result, h_fr_PlayHist2, const void *uid, const void *key, const void *a, const void *b) { (void)uid; (void)key; (void)a; (void)b; return RES_FAIL; } @@ -174,8 +133,24 @@ HLE_FORCE("_ZN2nn3ngc47CheckProfanityWordsInTextForPlatformRegionChinaEPbPKc", " HLE_FORCE("_ZN2nn3ngc46MaskProfanityWordsInTextForPlatformRegionChinaEPc", "China-region profanity masking (ngct:u): nothing is masked", Result, h_ngc_MaskCn, char *text) { (void)text; return RES_OK; } // ---------- err: error display applet. Only logged, no UI is shown ---------- -HLE_FORCE("_ZN2nn3err9ShowErrorENS0_9ErrorCodeE", "error display applet; the host only logs it", void, h_err_ShowCode, uint64_t code) { DM_APPLET("error"); LOG("game asks to show an error: %04u-%04u", (unsigned)(code & 0xffffffff), (unsigned)(code >> 32)); } -HLE_FORCE("_ZN2nn3err9ShowErrorERKNS0_18ErrorResultVariantE", "error display applet; the host only logs it", void, h_err_ShowVar, const void *v) { DM_APPLET("error"); (void)v; LOG("game asks to show an error (ErrorResultVariant)"); } +// 2306-08xx is a NEX login refusal (Authentication). Nextendo's game servers refuse for account reasons the NEX reply does not carry, so the +// account server is asked which one. hle_nextendo_login_apple.m has the strong definition; hosts and tests without it only skip the question +__attribute__((weak)) void dm_nextendo_login_online_check(const char *when) { (void)when; } +static void nextendo_refusal(unsigned category, unsigned number) { + if (category != 2306 || number < 800 || number > 899 || !dm_net_nextendo_enabled()) return; + char when[48]; snprintf(when, sizeof when, "after the game's error %04u-%04u", category, number); + dm_nextendo_login_online_check(when); +} +HLE_FORCE("_ZN2nn3err9ShowErrorENS0_9ErrorCodeE", "error display applet; the host only logs it", void, h_err_ShowCode, uint64_t code) { DM_APPLET("error"); LOG("game asks to show an error: %04u-%04u", (unsigned)(code & 0xffffffff), (unsigned)(code >> 32)); + nextendo_refusal((unsigned)(code & 0xffffffff), (unsigned)(code >> 32)); } +// ErrorResultVariant: a state (1 holds a Result, 2 an ErrorCode) and then the union of the Result and the ErrorCode {category, number}, 12 bytes in all. The log gives +// the raw words with both readings, so the code the game wanted on screen is there whichever the state says +HLE_FORCE("_ZN2nn3err9ShowErrorERKNS0_18ErrorResultVariantE", "error display applet; the host only logs it", void, h_err_ShowVar, const void *v) { DM_APPLET("error"); + uint32_t w[3] = {0}; if (v) memcpy(w, v, sizeof w); + LOG("game asks to show an error (ErrorResultVariant): state %u; as a Result 0x%x (2%03u-%04u); as an error code %04u-%04u; raw %08x %08x %08x", + w[0] & 0xff, w[1], w[1] & 0x1ff, (w[1] >> 9) & 0x1fff, w[1], w[2], w[0], w[1], w[2]); + if ((w[0] & 0xff) == 2) nextendo_refusal(w[1], w[2]); +} HLE_FORCE("_ZN2nn3err40ShowUnacceptableAddOnContentVersionErrorEv", "add-on content version mismatch error applet; the host only logs it", void, h_err_AocVer, void) { DM_APPLET("error"); LOG("game asks to show an error: add-on content version mismatch"); } // A Switch 2 Edition's program asks it when its upgrade add-on is older than it needs: Super Mario Bros. Wonder's Switch 2 program 1.2.1 reads aocup:/System/AocUpgradeVersion.txt and stops // below 3 (main+0x132b9b4); the console then asks the player to update the add-on. Unhooked, the SDK's applet call crashed on a null handle (sdk StartLibraryAppletImmediately) @@ -216,19 +191,68 @@ HLE_FORCE("_ZN2nn3web13ShowLobbyPageEPNS0_20LobbyPageReturnValueERKNS0_16ShowLob HLE_FORCE("_ZN2nn3web11ShowWebPageEPNS0_18WebPageReturnValueERKNS0_14ShowWebPageArgE", "web page applet (cut)", Result, h_web_Page, void *rv, const void *arg) { (void)rv; (void)arg; LOG("web::ShowWebPage (cut)"); return RES_FAIL; } // Octopath Traveler 0 imports the offline HTML page applet too (pages shipped in the game's HTML document NCA, which the host does not extract) -// ---------- C interface (nnsocket* / nnssl*): offline as well. The arguments are all in registers and the host does not look at them ---------- -HLE_FORCE("nnsocketAccept", "offline (cut)", int, h_c_sk_Accept, void) { return -1; } -HLE_FORCE("nnsocketListen", "offline (cut)", int, h_c_sk_Listen, void) { return -1; } -HLE_FORCE("nnsocketRecvMsg", "offline (cut)", int, h_c_sk_RecvMsg, void) { return -1; } -HLE_FORCE("nnsocketSendMsg", "offline (cut)", int, h_c_sk_SendMsg, void) { return -1; } -HLE_FORCE("nnsocketShutdown", "local UDP (offline BSD service)", int, h_c_sk_Shutdown, int s, int h) { return dm_sk_shutdown(s, h); } -HLE_FORCE("nnsocketGetAddrInfoWithOptions", "name resolution with resolver options (cut): EAI_FAIL", int, h_c_sk_GaiOpt, const char *h, const char *s, const void *hint, void **res, const void *o, unsigned long n) { (void)h; (void)s; (void)hint; (void)o; (void)n; if (res) *res = NULL; return SK_EAI_FAIL; } -HLE_FORCE("nnsocketGetAddrInfo", "name resolution (cut): EAI_FAIL", int, h_c_sk_Gai, const char *h, const char *s, const void *hint, void **res) { (void)h; (void)s; (void)hint; if (res) *res = NULL; return SK_EAI_FAIL; } -HLE_FORCE("nnsocketFreeAddrInfo", "pairs with GetAddrInfo (cut)", void, h_c_sk_FreeAi, void *ai) { (void)ai; } +// ---------- C socket interface: hle_net.c's local service offline (no TCP, no messages, no lookups), the transport in a network mode ---------- +HLE_FORCE_WAIT("nnsocketAccept", "socket transport; unavailable offline", int, h_c_sk_Accept, int s, void *a, unsigned *n) { return SKD(dm_net_accept(s, a, n), dm_sk_unavailable()); } +HLE_FORCE("nnsocketListen", "socket transport; unavailable offline", int, h_c_sk_Listen, int s, int n) { return SKD(dm_net_listen(s, n), dm_sk_unavailable()); } +// RecvMsg / SendMsg (gRPC's TCP endpoint does all its reads and writes with them: nn::npln, Super Mario Bros. Wonder). Horizon's msghdr is FreeBSD's, 0x30 bytes: name +0x00, +// namelen +0x08, iov +0x10, iovlen (int) +0x18, control +0x20, controllen +0x28, flags +0x2c; SDK 16's detail::RecvMsg (Wonder 1.2.1 sdk+0x14cf70) copies those 0x30 bytes into an +// mmsghdr and calls RecvMMsg with one message. An iovec is a base and a length. The data goes through one host buffer: gathered before a send, scattered after a receive. No ancillary +// data is carried: a receive reports none (controllen 0), and a send that has some fails with EOPNOTSUPP rather than drop it. The buffer holds at most SK_MSG_MAX bytes: on a +// stream socket a longer message moves in part, as a real socket may move less than asked (the caller sends or reads the rest); no datagram is that long, so one fails with +// EMSGSIZE. A datagram longer than the iovecs is cut to them and the receive reports MSG_TRUNC (0x10), as FreeBSD's does: the host asks for one byte more to see it +typedef struct { void *name; uint32_t namelen, pad0; struct { void *base; uint64_t len; } *iov; int32_t iovlen, pad1; void *control; uint32_t controllen; int32_t flags; } sk_msghdr; +_Static_assert(sizeof(sk_msghdr) == 0x30 && offsetof(sk_msghdr, iov) == 0x10 && offsetof(sk_msghdr, controllen) == 0x28 && offsetof(sk_msghdr, flags) == 0x2c, "Horizon msghdr"); +enum { SK_MSG_IOV_MAX = 1024, SK_MSG_MAX = 16 << 20 }; +enum { SK_MSG_TRUNC = 0x10 }; +static long sk_msg_size(const sk_msghdr *m, int datagram) { + if (!m || m->iovlen < 0 || m->iovlen > SK_MSG_IOV_MAX || (m->iovlen && !m->iov)) { dm_net_set_errno(22); return -1; } + uint64_t total = 0; // stops at SK_MSG_MAX + 1, whatever the lengths add up to + for (int i = 0; i < m->iovlen; i++) { + if (m->iov[i].len && !m->iov[i].base) { dm_net_set_errno(14); return -1; } + if (total <= SK_MSG_MAX) total = m->iov[i].len > SK_MSG_MAX - total ? SK_MSG_MAX + 1ull : total + m->iov[i].len; + } + if (total > SK_MSG_MAX) { if (datagram) { dm_net_set_errno(40); return -1; } total = SK_MSG_MAX; } + return (long)total; +} +static long sk_recvmsg(int s, sk_msghdr *m, int f) { + int datagram = dm_net_socket_type(s) == 2; long total = sk_msg_size(m, datagram); if (total < 0) return -1; + uint8_t *buffer = malloc((size_t)total + 1); if (!buffer) { dm_net_set_errno(12); return -1; } + unsigned namelen = m->name ? m->namelen : 0; + long got = dm_net_recv(s, buffer, (unsigned long)total + (unsigned long)datagram, f, m->name, m->name ? &namelen : NULL); + if (got >= 0) { + int cut = got > total; if (cut) got = total; + long left = got; for (int i = 0; i < m->iovlen && left > 0; i++) { uint64_t n = m->iov[i].len < (uint64_t)left ? m->iov[i].len : (uint64_t)left; memcpy(m->iov[i].base, buffer + (got - left), n); left -= (long)n; } + if (m->name) m->namelen = namelen; m->controllen = 0; m->flags = cut ? SK_MSG_TRUNC : 0; + } + free(buffer); return got; +} +HLE_FORCE_WAIT("nnsocketRecvMsg", "scatter receive through one host buffer; no ancillary data", long, h_c_sk_RecvMsg, int s, sk_msghdr *m, int f) { return SKD(sk_recvmsg(s, m, f), dm_sk_unavailable()); } +static long sk_sendmsg(int s, const sk_msghdr *m, int f) { + long total = sk_msg_size(m, dm_net_socket_type(s) == 2); if (total < 0) return -1; + if (m->control && m->controllen) { dm_net_set_errno(95); static int told; if (!told++) LOG("[RED] socket: SendMsg with ancillary data (%u bytes): not carried, the send fails", m->controllen); return -1; } + uint8_t *buffer = malloc(total ? (size_t)total : 1); if (!buffer) { dm_net_set_errno(12); return -1; } + long at = 0; for (int i = 0; i < m->iovlen && at < total; i++) { long n = m->iov[i].len < (uint64_t)(total - at) ? (long)m->iov[i].len : total - at; memcpy(buffer + at, m->iov[i].base, (size_t)n); at += n; } + long sent = dm_net_send(s, buffer, (unsigned long)total, f, m->name, m->name ? m->namelen : 0); + free(buffer); return sent; +} +HLE_FORCE_WAIT("nnsocketSendMsg", "gather send through one host buffer; ancillary data is refused", long, h_c_sk_SendMsg, int s, const sk_msghdr *m, int f) { return SKD(sk_sendmsg(s, m, f), dm_sk_unavailable()); } +HLE_FORCE("nnsocketShutdown", "socket call: the local service offline, the transport in a network mode", int, h_c_sk_Shutdown, int s, int h) { return SKD(dm_net_shutdown(s, h), dm_sk_shutdown(s, h)); } +// The C resolver takes the C struct addrinfo, the type of the plain-addrinfo C++ overload: in Wonder 1.2.1's SDK nnsocketGetAddrInfo (sdk+0x1481c0) branches straight to +// GetAddrInfo(const char *, const char *, const addrinfo *, addrinfo **, const ResolverOption *, size_t), and that SDK's decoders put the address at +0x20 for addrinfo +// (DNSSerializer::FromBufferInternal, sdk+0x1493f0) and at +0x18 for nn::socket::AddrInfo (sdk+0x148f60). So it gets that overload's layout whenever the SDK has +// it, as h_sk_Gai2 serves it, and the AddrInfo layout only in an SDK without it. An SDK with neither fails. Resolver options are not applied (the host resolver has none) +static int sk_c_gai(const char *h, const char *s, const void *hint, void **res) { + if (guest_sym("_ZN2nn6socket11GetAddrInfoEPKcS2_PK8addrinfoPPS3_")) return dm_net_getaddrinfo_legacy(h, s, hint, res); + if (guest_sym("_ZN2nn6socket11GetAddrInfoEPKcS2_PKNS0_8AddrInfoEPPS3_")) return dm_net_getaddrinfo(h, s, hint, res); + if (res) *res = NULL; return SK_EAI_FAIL; +} +HLE_FORCE_WAIT("nnsocketGetAddrInfoWithOptions", "name resolution in the C struct addrinfo layout; resolver options not applied", int, h_c_sk_GaiOpt, const char *h, const char *s, const void *hint, void **res, const void *o, unsigned long n) { + (void)o; (void)n; return sk_c_gai(h, s, hint, res); +} +HLE_FORCE_WAIT("nnsocketGetAddrInfo", "name resolution in the C struct addrinfo layout", int, h_c_sk_Gai, const char *h, const char *s, const void *hint, void **res) { return sk_c_gai(h, s, hint, res); } +HLE_FORCE("nnsocketFreeAddrInfo", "release only resolver allocations owned by the host", void, h_c_sk_FreeAi, void *ai) { dm_net_freeaddrinfo(ai); } HLE_FORCE("nnsocketGAIStrError", "resolver error text", const char *, h_c_sk_GaiStr, int e) { (void)e; return "network unavailable"; } -// ---------- bcat: news / data delivered from the server (Super Mario Odyssey). Initialize talks to the bcat service (an SDK abort without it); mounting the delivery cache fails, -// which the game treats as "nothing delivered" (main+0x6c9258: a failure skips the read unless the caller asked for an error dialog, which only logs here). Syncing needs the network, which nifm reports unavailable ---------- -HLE_FORCE("_ZN2nn4bcat10InitializeEv", "data delivery init (connects to the bcat service); the host has none, no-op", void, h_bcat_Init, void) {} -HLE_FORCE("_ZN2nn4bcat25MountDeliveryCacheStorageEv", "mount delivery cache: no delivery data, fails", Result, h_bcat_Mount, void) { return RES_FAIL; } -HLE_FORCE("_ZN2nn4bcat27UnmountDeliveryCacheStorageEv", "unmount delivery cache", void, h_bcat_Unmount, void) {} +// BCAT initialization retains the existing offline contract. Validated optional +// delivery snapshots are mounted by hle_fs.c; missing data still fails there. +HLE_FORCE("_ZN2nn4bcat10InitializeEv", "initialize optional data delivery, with no implied network/cache success", void, h_bcat_Init, void) {} diff --git a/dm/host/hle_sdk16.c b/dm/host/hle_sdk16.c index 78be7c0834..d11a3cfbb5 100644 --- a/dm/host/hle_sdk16.c +++ b/dm/host/hle_sdk16.c @@ -45,14 +45,6 @@ HLE_FORCE("_ZN2nn4time21GetDeviceLocationNameEPNS0_12LocationNameE", "device tim memset(out, 0, 0x24); tzset(); strlcpy(out, tzname[0] && *tzname[0] ? tzname[0] : "UTC", 0x24); return RES_OK; } HLE_FORCE("_ZN2nn4time8FinalizeEv", "pairs with Initialize; the host has no session", Result, h_time_Finalize, void) { return RES_OK; } -// "Ensure network clock availability" async task: no request is sent; the finish event fires immediately and the result is failure. The object itself is untouched (constructor / destructor no-ops), the event lives in host static storage -static _Alignas(16) uint8_t g_ev_netclock[0x100]; -HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTaskC1Ev", "network clock task constructor; the host opens no session", void, h_time_NcCtor, void *self) { (void)self; } -HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTaskD1Ev", "network clock task destructor; no session to close", void, h_time_NcDtor, void *self) { (void)self; } -HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTask10InitializeENS_2os14EventClearModeE", "network clock task init (offline)", Result, h_time_NcInit, void *self, int mode) { (void)self; (void)mode; return RES_OK; } -HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTask9StartTaskEv", "network clock task start: finishes at once with failure", Result, h_time_NcStart, void *self) { (void)self; hle_signal_system_event(g_ev_netclock); return RES_OK; } -HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTask14GetFinishEventEv", "network clock task finish event: already signalled", void *, h_time_NcEvent, void *self) { (void)self; hle_signal_system_event(g_ev_netclock); return g_ev_netclock; } -HLE_FORCE("_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTask9GetResultEv", "network clock task result: offline, failure", Result, h_time_NcResult, void *self) { (void)self; return RES_FAIL; } // The host has none of the original system shared fonts (0 standard / 1 Simplified Chinese / 2 Simplified Chinese extension / 3 Traditional Chinese / 4 Korean / 5 Nintendo extension) and uses stand-ins, // one file per type in $DM_FONT_DIR (font_file), all made by dm/tools/make_shared_fonts.py: types 0-4 are unhinted cuts of one source font (macOS's Arial Unicode), each with its type's characters, diff --git a/dm/host/hle_ssl.c b/dm/host/hle_ssl.c new file mode 100644 index 0000000000..bc45834407 --- /dev/null +++ b/dm/host/hle_ssl.c @@ -0,0 +1,128 @@ +// nn::ssl public service entry points. SDK4 C shims and SDK19 ALPN signatures were verified from dynamic symbols and their PLT relocations. +// Backend objects live in an owned registry; constructors do not invent the SDK private object layout. +#include "hle.h" +#include "ssl_backend.h" +#include +// The setup calls a game makes before its first TLS byte log a failure, once per call and result, as an import or a context that fails stops a game's connection +// before any socket traffic (no certificate, key or data is logged) +static Result ssl_note(const char *call, Result r) { + static struct { const char *call; Result r; } seen[32]; static unsigned count; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + if (!r) return r; + pthread_mutex_lock(&lock); int fresh = 1; for (unsigned i = 0; i < count; i++) if (seen[i].call == call && seen[i].r == r) fresh = 0; + if (fresh && count < 32) { seen[count].call = call; seen[count].r = r; count++; } pthread_mutex_unlock(&lock); + if (fresh) LOG("[RED] ssl: %s -> %#x", call, r); + return r; +} +// A built-in certificate request logs once per call, first ID, count and result (success too: a game that builds its own TLS roots from the store, as Super Mario +// Bros. Wonder's gRPC does one ID at a time, shows here whether it asked at all and which ID it stopped at). IDs only, never a certificate +static Result builtin_note(const char *call, const uint32_t *ids, unsigned n, Result r) { + static struct { const char *call; uint32_t id; unsigned n; Result r; } seen[48]; static unsigned count; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + uint32_t id = ids && n ? ids[0] : 0; + pthread_mutex_lock(&lock); int fresh = 1; + for (unsigned i = 0; i < count; i++) if (seen[i].call == call && seen[i].id == id && seen[i].n == n && seen[i].r == r) fresh = 0; + if (fresh && count < 48) { seen[count].call = call; seen[count].id = id; seen[count].n = n; seen[count].r = r; count++; } else fresh = 0; + pthread_mutex_unlock(&lock); + if (fresh) LOG("%sssl: built-in certificates %s: ID %#x%s -> %#x", r ? "[RED] " : "", call, id, n > 1 ? " and more" : "", r); + return r; +} + +HLE_FORCE_WAIT("_ZN2nn3ssl10InitializeEv", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_0, void) { return dm_ssl_initialize(3); } +HLE_FORCE_WAIT("_ZN2nn3ssl10InitializeEj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_1, unsigned n) { return dm_ssl_initialize(n); } +HLE_FORCE_WAIT("_ZN2nn3ssl8FinalizeEv", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_2, void) { return dm_ssl_finalize(); } +HLE_FORCE("_ZN2nn3ssl7ContextC1Ev", "client TLS service; scoped certificate and hostname validation", void, tls_hook_3, void *self) { (void)self; } +HLE_FORCE("_ZN2nn3ssl7ContextC2Ev", "client TLS service; scoped certificate and hostname validation", void, tls_hook_4, void *self) { (void)self; } +HLE_FORCE("_ZN2nn3ssl7ContextD1Ev", "client TLS service; scoped certificate and hostname validation", void, tls_hook_5, void *self) { (void)dm_ssl_context_destroy(self); } +HLE_FORCE("_ZN2nn3ssl7ContextD2Ev", "client TLS service; scoped certificate and hostname validation", void, tls_hook_6, void *self) { (void)dm_ssl_context_destroy(self); } +HLE_FORCE("_ZN2nn3ssl10ConnectionC1Ev", "client TLS service; scoped certificate and hostname validation", void, tls_hook_7, void *self) { (void)self; } +HLE_FORCE("_ZN2nn3ssl10ConnectionC2Ev", "client TLS service; scoped certificate and hostname validation", void, tls_hook_8, void *self) { (void)self; } +HLE_FORCE("_ZN2nn3ssl10ConnectionD1Ev", "client TLS service; scoped certificate and hostname validation", void, tls_hook_9, void *self) { (void)dm_ssl_connection_destroy(self); } +HLE_FORCE("_ZN2nn3ssl10ConnectionD2Ev", "client TLS service; scoped certificate and hostname validation", void, tls_hook_10, void *self) { (void)dm_ssl_connection_destroy(self); } +HLE_FORCE_WAIT("_ZN2nn3ssl7Context6CreateENS1_10SslVersionE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_11, void *self, unsigned version) { Result r = dm_ssl_context_create(self, version); return ssl_note("Context::Create", r); } +HLE_FORCE_WAIT("_ZN2nn3ssl14ContextPrivate6CreateENS1_10SslVersionE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_12, void *self, unsigned version) { return dm_ssl_context_create(self, version); } +HLE_FORCE_WAIT("_ZN2nn3ssl7Context7DestroyEv", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_13, void *self) { return dm_ssl_context_destroy(self); } +HLE_FORCE_WAIT("_ZN2nn3ssl7Context12GetContextIdEPm", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_14, void *self, uint64_t *out) { return dm_ssl_context_id(self, out); } +HLE_FORCE_WAIT("_ZN2nn3ssl7Context15ImportServerPkiEPmPKcjNS0_17CertificateFormatE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_15, void *self, uint64_t *out, const char *bytes, unsigned size, int format) { return ssl_note("ImportServerPki", dm_ssl_import_server(self, out, bytes, size, format)); } +HLE_FORCE_WAIT("_ZN2nn3ssl7Context15ImportClientPkiEPmPKcS4_jj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_16, void *self, uint64_t *out, const char *bytes, const char *password, unsigned size, unsigned password_size) { return ssl_note("ImportClientPki", dm_ssl_import_client(self, out, bytes, password, size, password_size)); } +HLE_FORCE_WAIT("_ZN2nn3ssl7Context9RemovePkiEm", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_17, void *self, uint64_t id) { return dm_ssl_remove_pki(self, id); } +HLE_FORCE_WAIT("_ZN2nn3ssl7Context19RegisterInternalPkiEPmNS1_11InternalPkiE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_18, void *self, uint64_t *out, int pki) { (void)self; (void)pki; if (out) *out = 0; return ssl_note("RegisterInternalPki", DM_SSL_FAIL); } +HLE_FORCE_WAIT("_ZN2nn3ssl7Context9ImportCrlEPmPKcj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_19, void *self, uint64_t *out, const char *bytes, unsigned size) { (void)self; (void)bytes; (void)size; if (out) *out = 0; return ssl_note("ImportCrl", DM_SSL_FAIL); } +HLE_FORCE_WAIT("_ZN2nn3ssl7Context12AddPolicyOidEPKcj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_20, void *self, const char *oid, unsigned size) { (void)self; (void)oid; (void)size; return DM_SSL_FAIL; } +HLE_FORCE_WAIT("_ZN2nn3ssl7Context9SetOptionENS1_13ContextOptionEi", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_21, void *self, unsigned option, int value) { (void)self; (void)option; (void)value; return DM_SSL_FAIL; } +HLE_FORCE_WAIT("_ZN2nn3ssl7Context9GetOptionEPiNS1_13ContextOptionE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_22, void *self, int *out, unsigned option) { (void)self; (void)option; if (out) *out = 0; return DM_SSL_FAIL; } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection6CreateEPNS0_7ContextE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_23, void *self, void *ctx) { Result r = dm_ssl_connection_create(self, ctx); return ssl_note("Connection::Create", r); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection7DestroyEv", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_24, void *self) { return dm_ssl_connection_destroy(self); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection19SetSocketDescriptorEi", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_25, void *self, int fd) { return ssl_note("SetSocketDescriptor", dm_ssl_set_socket(self, fd)); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection19GetSocketDescriptorEPi", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_26, void *self, int *out) { return dm_ssl_get_socket(self, out); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection11SetHostNameEPKcj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_27, void *self, const char *host, unsigned size) { return ssl_note("SetHostName", dm_ssl_set_hostname(self, host, size)); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection11GetHostNameEPcPjj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_28, void *self, char *host, unsigned *size, unsigned capacity) { return dm_ssl_get_hostname(self, host, size, capacity); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection9SetIoModeENS1_6IoModeE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_29, void *self, unsigned value) { return dm_ssl_set_value(self, DM_SSL_IO_MODE, value); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection9GetIoModeEPNS1_6IoModeE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_30, void *self, unsigned *out) { return dm_ssl_get_value(self, DM_SSL_IO_MODE, out); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection15SetVerifyOptionENS1_12VerifyOptionE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_31, void *self, unsigned value) { return dm_ssl_set_value(self, DM_SSL_VERIFY_OPTIONS, value); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection15GetVerifyOptionEPNS1_12VerifyOptionE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_32, void *self, unsigned *out) { return dm_ssl_get_value(self, DM_SSL_VERIFY_OPTIONS, out); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection19SetSessionCacheModeENS1_16SessionCacheModeE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_33, void *self, unsigned value) { return dm_ssl_set_value(self, DM_SSL_SESSION_CACHE, value); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection19GetSessionCacheModeEPNS1_16SessionCacheModeE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_34, void *self, unsigned *out) { return dm_ssl_get_value(self, DM_SSL_SESSION_CACHE, out); } +HLE_FORCE_WAIT("_ZN2nn3ssl17ConnectionPrivate12SetIoTimeoutEj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_35, void *self, unsigned value) { return dm_ssl_set_value(self, DM_SSL_IO_TIMEOUT, value); } +HLE_FORCE_WAIT("_ZN2nn3ssl17ConnectionPrivate12GetIoTimeoutEPj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_36, void *self, unsigned *out) { return dm_ssl_get_value(self, DM_SSL_IO_TIMEOUT, out); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection9SetOptionENS1_10OptionTypeEb", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_37, void *self, int option, unsigned value) { return dm_ssl_set_option(self, option, value); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection9GetOptionEPbNS1_10OptionTypeE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_38, void *self, void *out, int option) { return dm_ssl_get_option(self, out, option); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection11DoHandshakeEv", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_39, void *self) { Result r = dm_ssl_handshake(self); return ssl_note("DoHandshake", r); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection11DoHandshakeEPjS2_", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_40, void *self, unsigned *size, unsigned *count) { return ssl_note("DoHandshake (certificate sizes)", dm_ssl_handshake_certs(self, size, count, NULL, 0, true)); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection11DoHandshakeEPjS2_Pcj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_41, void *self, unsigned *size, unsigned *count, char *bytes, unsigned capacity) { return ssl_note("DoHandshake (certificates)", dm_ssl_handshake_certs(self, size, count, bytes, capacity, false)); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection19SetServerCertBufferEPcj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_42, void *self, char *bytes, unsigned capacity) { return dm_ssl_set_cert_buffer(self, bytes, capacity); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection29GetNeededServerCertBufferSizeEPj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_43, void *self, unsigned *out) { return dm_ssl_needed_cert_size(self, out); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection19GetServerCertDetailEPNS1_16ServerCertDetailEPKcj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_44, void *self, void *out, const char *bytes, unsigned index) { (void)self; return dm_ssl_cert_detail(out, bytes, index); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection4ReadEPcPij", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_45, void *self, char *bytes, int *out, unsigned size) { return dm_ssl_read(self, bytes, out, size, false); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection4ReadEPcj", "client TLS service; scoped certificate and hostname validation", int, tls_hook_46, void *self, char *bytes, unsigned size) { int out = 0; return dm_ssl_read(self, bytes, &out, size, false) ? -1 : out; } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection5WriteEPKcPij", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_47, void *self, const char *bytes, int *out, unsigned size) { return dm_ssl_write(self, bytes, out, size); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection5WriteEPKcj", "client TLS service; scoped certificate and hostname validation", int, tls_hook_48, void *self, const char *bytes, unsigned size) { int out = 0; return dm_ssl_write(self, bytes, &out, size) ? -1 : out; } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection4PeekEPcPij", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_49, void *self, char *bytes, int *out, unsigned size) { return dm_ssl_read(self, bytes, out, size, true); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection7PendingEPi", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_50, void *self, int *out) { return dm_ssl_pending(self, out); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection7PendingEv", "client TLS service; scoped certificate and hostname validation", int, tls_hook_51, void *self) { int out = 0; return dm_ssl_pending(self, &out) ? -1 : out; } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection4PollEPNS1_9PollEventES3_j", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_52, void *self, unsigned *out, const unsigned *events, unsigned timeout) { return dm_ssl_poll(self, out, events, timeout); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection12GetLastErrorEPNS_6ResultE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_53, void *self, uint32_t *out) { return dm_ssl_last_error(self, out, false); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection18GetVerifyCertErrorEPNS_6ResultE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_54, void *self, uint32_t *out) { return dm_ssl_last_error(self, out, true); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection15GetConnectionIdEPm", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_55, void *self, uint64_t *out) { return dm_ssl_connection_id(self, out, false); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection12GetContextIdEPm", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_56, void *self, uint64_t *out) { return dm_ssl_connection_id(self, out, true); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection13GetCipherInfoEPNS1_10CipherInfoE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_57, void *self, void *out) { return dm_ssl_cipher_info(self, out); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection16SetNextAlpnProtoEPKhj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_58, void *self, const uint8_t *bytes, unsigned size) { return dm_ssl_set_alpn(self, bytes, size); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection16GetNextAlpnProtoEPNS1_14AlpnProtoStateEPhPjj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_59, void *self, unsigned *state, uint8_t *bytes, unsigned *size, unsigned capacity) { return dm_ssl_get_alpn(self, state, bytes, size, capacity); } +HLE_FORCE_WAIT("_ZN2nn3ssl14BuiltInManager28GetBuiltInCertificateBufSizeEPjPNS0_15CaCertificateIdEj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_60, unsigned *out, const uint32_t *ids, unsigned count) { return builtin_note("size", ids, count, dm_ssl_builtin_size(out, ids, count)); } +HLE_FORCE_WAIT("_ZN2nn3ssl14BuiltInManager22GetBuiltInCertificatesEPPNS1_22BuiltInCertificateInfoEPhjPNS0_15CaCertificateIdEj", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_61, void **out, uint8_t *buffer, unsigned capacity, const uint32_t *ids, unsigned count) { return builtin_note("get", ids, count, dm_ssl_builtin_certificates(out, buffer, capacity, ids, count)); } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection17FlushSessionCacheEv", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_62, void *self) { (void)self; return DM_SSL_FAIL; } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection20SetRenegotiationModeENS1_17RenegotiationModeE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_63, void *self, unsigned mode) { (void)self; (void)mode; return DM_SSL_FAIL; } +HLE_FORCE_WAIT("_ZN2nn3ssl10Connection20GetRenegotiationModeEPNS1_17RenegotiationModeE", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_64, void *self, unsigned *out) { (void)self; if (out) *out = 0; return DM_SSL_FAIL; } +HLE_FORCE_WAIT("nnsslInitialize", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_65, void) { return dm_ssl_initialize(3); } +HLE_FORCE_WAIT("nnsslInitializeWithConcurrencyLimit", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_66, unsigned n) { return dm_ssl_initialize(n); } +HLE_FORCE_WAIT("nnsslFinalize", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_67, void) { return dm_ssl_finalize(); } +HLE_FORCE_WAIT("nnsslContextCreate", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_68, void *self, unsigned version) { return dm_ssl_context_create(self, version); } +HLE_FORCE_WAIT("nnsslContextDestroy", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_69, void *self) { return dm_ssl_context_destroy(self); } +HLE_FORCE_WAIT("nnsslContextGetContextId", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_70, void *self, uint64_t *out) { return dm_ssl_context_id(self, out); } +HLE_FORCE_WAIT("nnsslConnectionCreate", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_71, void *self, void *ctx) { return dm_ssl_connection_create(self, ctx); } +HLE_FORCE_WAIT("nnsslConnectionDestroy", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_72, void *self) { return dm_ssl_connection_destroy(self); } +HLE_FORCE_WAIT("nnsslConnectionSetSocketDescriptor", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_73, void *self, int fd) { return dm_ssl_set_socket(self, fd); } +HLE_FORCE_WAIT("nnsslConnectionGetSocketDescriptor", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_74, void *self, int *out) { return dm_ssl_get_socket(self, out); } +HLE_FORCE_WAIT("nnsslConnectionSetHostName", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_75, void *self, const char *host, unsigned size) { return dm_ssl_set_hostname(self, host, size); } +HLE_FORCE_WAIT("nnsslConnectionGetHostName", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_76, void *self, char *host, unsigned *size, unsigned capacity) { return dm_ssl_get_hostname(self, host, size, capacity); } +HLE_FORCE_WAIT("nnsslConnectionSetIoMode", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_77, void *self, unsigned value) { return dm_ssl_set_value(self, DM_SSL_IO_MODE, value); } +HLE_FORCE_WAIT("nnsslConnectionGetIoMode", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_78, void *self, unsigned *out) { return dm_ssl_get_value(self, DM_SSL_IO_MODE, out); } +HLE_FORCE_WAIT("nnsslConnectionSetVerifyOption", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_79, void *self, unsigned value) { return dm_ssl_set_value(self, DM_SSL_VERIFY_OPTIONS, value); } +HLE_FORCE_WAIT("nnsslConnectionGetVerifyOption", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_80, void *self, unsigned *out) { return dm_ssl_get_value(self, DM_SSL_VERIFY_OPTIONS, out); } +HLE_FORCE_WAIT("nnsslConnectionSetSessionCacheMode", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_81, void *self, unsigned value) { return dm_ssl_set_value(self, DM_SSL_SESSION_CACHE, value); } +HLE_FORCE_WAIT("nnsslConnectionSetOption", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_82, void *self, int option, unsigned value) { return dm_ssl_set_option(self, option, value); } +HLE_FORCE_WAIT("nnsslConnectionGetOption", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_83, void *self, void *out, int option) { return dm_ssl_get_option(self, out, option); } +HLE_FORCE_WAIT("nnsslConnectionDoHandshake", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_84, void *self) { return dm_ssl_handshake(self); } +HLE_FORCE_WAIT("nnsslConnectionDoHandshakeWithCertBuffer", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_85, void *self, unsigned *size, unsigned *count) { return dm_ssl_handshake_certs(self, size, count, NULL, 0, true); } +HLE_FORCE_WAIT("nnsslConnectionDoHandshakeWithBuffer", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_86, void *self, unsigned *size, unsigned *count, char *bytes, unsigned capacity) { return dm_ssl_handshake_certs(self, size, count, bytes, capacity, false); } +HLE_FORCE_WAIT("nnsslConnectionSetServerCertBuffer", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_87, void *self, char *bytes, unsigned capacity) { return dm_ssl_set_cert_buffer(self, bytes, capacity); } +HLE_FORCE_WAIT("nnsslConnectionGetServerCertDetail", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_88, void *self, void *out, const char *bytes, unsigned index) { (void)self; return dm_ssl_cert_detail(out, bytes, index); } +HLE_FORCE_WAIT("nnsslConnectionRead", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_89, void *self, char *bytes, int *out, unsigned size) { return dm_ssl_read(self, bytes, out, size, false); } +HLE_FORCE_WAIT("nnsslConnectionWrite", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_90, void *self, const char *bytes, int *out, unsigned size) { return dm_ssl_write(self, bytes, out, size); } +HLE_FORCE_WAIT("nnsslConnectionPeek", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_91, void *self, char *bytes, int *out, unsigned size) { return dm_ssl_read(self, bytes, out, size, true); } +HLE_FORCE_WAIT("nnsslConnectionPending", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_92, void *self, int *out) { return dm_ssl_pending(self, out); } +HLE_FORCE_WAIT("nnsslConnectionPoll", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_93, void *self, unsigned *out, const unsigned *events, unsigned timeout) { return dm_ssl_poll(self, out, events, timeout); } +HLE_FORCE_WAIT("nnsslConnectionGetVerifyCertError", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_94, void *self, uint32_t *out) { return dm_ssl_last_error(self, out, true); } +HLE_FORCE_WAIT("nnsslConnectionGetConnectionId", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_95, void *self, uint64_t *out) { return dm_ssl_connection_id(self, out, false); } +HLE_FORCE_WAIT("nnsslConnectionGetContextId", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_96, void *self, uint64_t *out) { return dm_ssl_connection_id(self, out, true); } +HLE_FORCE_WAIT("nnsslConnectionSetNextAlpnProto", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_97, void *self, const uint8_t *bytes, unsigned size) { return dm_ssl_set_alpn(self, bytes, size); } +HLE_FORCE_WAIT("nnsslConnectionGetNextAlpnProto", "client TLS service; scoped certificate and hostname validation", Result, tls_hook_98, void *self, unsigned *state, uint8_t *bytes, unsigned *size, unsigned capacity) { return dm_ssl_get_alpn(self, state, bytes, size, capacity); } +HLE_FORCE_WAIT("_ZN2nn3ssl14BuiltInManager22GetBuiltInCertificatesEPPNS0_26BuiltInCertificateInfoBaseEPhjPNS0_15CaCertificateIdEj", "original firmware certificate IDs and DER; context-scoped trust", Result, tls_legacy_builtin_info, void **out, uint8_t *buffer, unsigned capacity, const uint32_t *ids, unsigned count) { return builtin_note("get", ids, count, dm_ssl_builtin_certificates(out, buffer, capacity, ids, count)); } diff --git a/dm/host/hle_ssl_apple.m b/dm/host/hle_ssl_apple.m new file mode 100644 index 0000000000..fbbb5654d9 --- /dev/null +++ b/dm/host/hle_ssl_apple.m @@ -0,0 +1,685 @@ +// Public SecureTransport supplies the stream engine. SecTrust validates public PKI; +// an explicit private service CA additionally supports strict, SAN-only OpenSSL +// verification, with Apple's basic chain checks retained. No permissive callback. +// SecureTransport supports TLS through 1.2. TLS-1.3-only requests fail rather than silently downgrade. +#import +#import +#include "nextendo_x509.h" +#import +#include "ssl_backend.h" +#include "net_socket.h" +#include "ssl_trace.h" +#include +#include +#include +#include +#include +#include +#include +#include + +// These APIs remain public on the deployment targets. The existing guest's connected BSD +// descriptor cannot be adopted by Network.framework through a public API. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +void dm_guest_host_wait_begin(void); +void dm_guest_host_wait_end(void); + +@interface DmTlsContext : NSObject +@property(nonatomic) uint64_t identifier; +@property(nonatomic) unsigned version; +@property(nonatomic) NSLock *lock; +@property(nonatomic) NSMutableDictionary *anchors; +@property(nonatomic) NSArray *clientIdentity; +@property(nonatomic) uint64_t clientIdentifier; +@end +@implementation DmTlsContext +@end + +@interface DmTlsConnection : NSObject { +@public + _Atomic bool closed; + _Atomic int descriptor; + SSLContextRef tls; + short wanted; +} +@property(nonatomic) uint64_t identifier; +@property(nonatomic) DmTlsContext *context; +@property(nonatomic) NSLock *lock; +@property(nonatomic) int guestDescriptor; +@property(nonatomic) uint64_t socketGeneration; +@property(nonatomic) NSString *hostname; +@property(nonatomic) NSString *peerName; +@property(nonatomic) NSData *policyAnchor; +@property(nonatomic) BOOL policyPinned; +@property(nonatomic) unsigned ioMode, verifyOptions, sessionCache, timeout; +@property(nonatomic) BOOL certificateChain, enableAlpn, handshaking, established, verified, rejected; +@property(nonatomic) BOOL tracedRead, tracedWrite; +@property(atomic) BOOL doNotClose; +@property(atomic) uint32_t lastError, verifyError; +@property(nonatomic) NSMutableData *lookahead; +@property(nonatomic) NSData *pendingWrite; +@property(nonatomic) NSArray *alpn; +@property(nonatomic) void *certificateBuffer; +@property(nonatomic) unsigned certificateCapacity; +@end +@implementation DmTlsConnection +- (void)dealloc { + // No operation can still own this object at its final release. Send close_notify on the + // still-owned descriptor, without retaining a connection already inside dealloc. + if (tls) { atomic_store(&closed, false); SSLClose(tls); CFRelease(tls); } + int fd = atomic_load(&descriptor); if (fd >= 0) close(fd); +} +@end + +static NSMutableDictionary *contexts; +static NSMutableDictionary *connections; +static pthread_mutex_t registry = PTHREAD_MUTEX_INITIALIZER; +static pthread_once_t once = PTHREAD_ONCE_INIT; +static uint64_t nextIdentifier; +static _Atomic(dm_ssl_peer_policy_provider) peerProvider; +static _Atomic(dm_ssl_peer_policy_provider) pinProvider; +static _Atomic(bool (*)(const char *)) peerGuard; +static _Atomic(bool (*)(const uint8_t **, size_t *)) builtinFallback; +static void initialize_registry(void) { contexts = [NSMutableDictionary new]; connections = [NSMutableDictionary new]; } +static NSValue *key(void *object) { return [NSValue valueWithPointer:object]; } +static BOOL enabled(void) { return dm_net_enabled(); } +static uint64_t clock_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000; } +static DmTlsContext *get_context(void *object) { + pthread_once(&once, initialize_registry); pthread_mutex_lock(®istry); + DmTlsContext *c = contexts[key(object)]; pthread_mutex_unlock(®istry); return c; +} +static DmTlsConnection *get_connection(void *object) { + pthread_once(&once, initialize_registry); pthread_mutex_lock(®istry); + DmTlsConnection *c = connections[key(object)]; pthread_mutex_unlock(®istry); return c; +} +static uint32_t error(DmTlsConnection *c, uint32_t value) { c.lastError = value; return value; } +static void trace(DmTlsConnection *c, dm_tls_stage stage, uint32_t result, OSStatus native, uint64_t detail) { + unsigned flags = (c.handshaking ? 1u : 0u) | (c.established ? 2u : 0u) | + (c.verified ? 4u : 0u) | (c.rejected ? 8u : 0u) | + (c.policyPinned ? 16u : 0u) | (c.policyAnchor ? 32u : 0u); + dm_tls_trace(stage, c.identifier, result, native, detail, flags); +} +static uint32_t status_result(DmTlsConnection *c, OSStatus status) { + if (!status) return error(c, 0); + if (status == errSSLWouldBlock) return error(c, DM_SSL_WOULD_BLOCK); + return error(c, DM_SSL_FAIL); +} +static uint32_t wait_socket(DmTlsConnection *c, short events, uint64_t deadline) { + for (;;) { + if (atomic_load(&c->closed)) return error(c, DM_SSL_BAD_SOCKET); + uint64_t now = clock_ms(); if (now >= deadline) return error(c, DM_SSL_TIMEOUT); + uint64_t left = deadline - now; int ms = left > 100 ? 100 : (int)left; + struct pollfd p = {.fd = atomic_load(&c->descriptor), .events = events}; + dm_guest_host_wait_begin(); int n = poll(&p, 1, ms), e = errno; dm_guest_host_wait_end(); + if (n < 0 && e == EINTR) continue; + if (n < 0 || atomic_load(&c->closed)) return error(c, DM_SSL_BAD_SOCKET); + if (n) return 0; + } +} +static OSStatus transport_io(SSLConnectionRef reference, void *bytes, size_t *size, bool reading) { + __unsafe_unretained DmTlsConnection *c = (__bridge DmTlsConnection *)(void *)reference; + size_t requested = *size, done = 0; *size = 0; + while (done < requested) { + if (atomic_load(&c->closed)) return errSSLClosedAbort; + int fd = atomic_load(&c->descriptor); + ssize_t n = reading ? recv(fd, (char *)bytes + done, requested - done, 0) : send(fd, (char *)bytes + done, requested - done, 0); + if (n > 0) { done += (size_t)n; *size = done; continue; } + if (!n && reading) return errSSLClosedAbort; // Only a TLS close_notify is orderly EOF; bare TCP EOF may truncate an authenticated record. + if (n < 0 && errno == EINTR) continue; + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { c->wanted = reading ? POLLIN : POLLOUT; return errSSLWouldBlock; } + return errSSLClosedAbort; + } + return noErr; +} +static OSStatus transport_read(SSLConnectionRef c, void *p, size_t *n) { return transport_io(c, p, n, true); } +static OSStatus transport_write(SSLConnectionRef c, const void *p, size_t *n) { return transport_io(c, (void *)p, n, false); } + +void dm_ssl_set_peer_policy(dm_ssl_peer_policy_provider provider) { atomic_store(&peerProvider, provider); } +void dm_ssl_set_peer_pin_policy(dm_ssl_peer_policy_provider provider) { atomic_store(&pinProvider, provider); } +void dm_ssl_set_peer_guard(bool (*guard)(const char *)) { atomic_store(&peerGuard, guard); } +void dm_ssl_set_builtin_fallback(bool (*provider)(const uint8_t **, size_t *)) { atomic_store(&builtinFallback, provider); } +uint32_t dm_ssl_initialize(unsigned concurrency) { return concurrency >= 1 && concurrency <= 4 ? 0 : DM_SSL_FAIL; } +uint32_t dm_ssl_finalize(void) { @autoreleasepool { + pthread_once(&once, initialize_registry); pthread_mutex_lock(®istry); + NSArray *objects = connections.allValues; [connections removeAllObjects]; [contexts removeAllObjects]; pthread_mutex_unlock(®istry); + for (DmTlsConnection *c in objects) { atomic_store(&c->closed, true); if (atomic_load(&c->descriptor) >= 0 && !c.doNotClose && c.guestDescriptor >= 0) dm_net_close_generation(c.guestDescriptor, c.socketGeneration); } + return 0; +} } +uint32_t dm_ssl_context_create(void *object, unsigned version) { @autoreleasepool { + if (!object) return DM_SSL_BAD_POINTER; if (!enabled()) return DM_SSL_FAIL; + unsigned protocols = version & 0xff; if (!(protocols & (1 | 8 | 16 | 32)) || (protocols & ~(1u | 8u | 16u | 32u | 64u))) return DM_SSL_FAIL; + DmTlsContext *c = [DmTlsContext new]; if (!c) return DM_SSL_FAIL; c.version = version; c.lock = [NSLock new]; c.anchors = [NSMutableDictionary new]; + pthread_once(&once, initialize_registry); pthread_mutex_lock(®istry); + if (contexts[key(object)] || contexts.count >= 64) { pthread_mutex_unlock(®istry); return DM_SSL_FAIL; } + c.identifier = ++nextIdentifier; contexts[key(object)] = c; pthread_mutex_unlock(®istry); return 0; +} } +uint32_t dm_ssl_context_destroy(void *object) { @autoreleasepool { + if (!object) return DM_SSL_BAD_POINTER; + pthread_once(&once, initialize_registry); pthread_mutex_lock(®istry); DmTlsContext *c = contexts[key(object)]; + if (!c) { pthread_mutex_unlock(®istry); return DM_SSL_FAIL; } + for (DmTlsConnection *connection in connections.allValues) if (connection.context == c) { pthread_mutex_unlock(®istry); return DM_SSL_FAIL; } + [contexts removeObjectForKey:key(object)]; pthread_mutex_unlock(®istry); return 0; +} } +uint32_t dm_ssl_context_id(void *object, uint64_t *out) { @autoreleasepool { + if (!out || !object) return DM_SSL_BAD_POINTER; + // The SDK getter also succeeds before Create and after Destroy, with ID 0. + // This query must not allocate a context or imply a usable TLS session. + DmTlsContext *c = get_context(object); *out = c ? c.identifier : 0; return 0; +} } +static NSArray *parse_certificates(const void *bytes, unsigned size, int format) { + if (!bytes || !size || size > 4 * 1024 * 1024 || (format != 1 && format != 2)) return nil; + NSMutableArray *certificates = [NSMutableArray new]; + if (format == 2) { + CFDataRef data = CFDataCreate(kCFAllocatorDefault, bytes, size); SecCertificateRef certificate = SecCertificateCreateWithData(kCFAllocatorDefault, data); CFRelease(data); + if (!certificate) return nil; [certificates addObject:CFBridgingRelease(certificate)]; + } else { + NSString *text = [[NSString alloc] initWithBytes:bytes length:size encoding:NSASCIIStringEncoding]; if (!text) return nil; + NSRange remainder = NSMakeRange(0, text.length); + while (remainder.length) { + NSRange start = [text rangeOfString:@"-----BEGIN CERTIFICATE-----" options:0 range:remainder]; if (start.location == NSNotFound) break; + NSUInteger p = NSMaxRange(start); NSRange end = [text rangeOfString:@"-----END CERTIFICATE-----" options:0 range:NSMakeRange(p, text.length - p)]; if (end.location == NSNotFound) return nil; + NSData *data = [[NSData alloc] initWithBase64EncodedString:[text substringWithRange:NSMakeRange(p, end.location - p)] options:NSDataBase64DecodingIgnoreUnknownCharacters]; + SecCertificateRef certificate = data ? SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)data) : NULL; + if (!certificate) return nil; [certificates addObject:CFBridgingRelease(certificate)]; + remainder = NSMakeRange(NSMaxRange(end), text.length - NSMaxRange(end)); + } + } + return certificates.count ? certificates : nil; +} +// CertStore BDF entries are file records, not the SDK's pointer-bearing 24-byte +// BuiltInCertificateInfo. Offsets are relative to byte 8 of the original file. +// The store is the player's own firmware file, in either place: /0100000000000800/files/ssl_TrustedCerts.bdf, or the system data archive's RomFS +// file in /sysdata/0100000000000800/ (hle_fs.c's layout; the iOS app sets DM_SYSTEM_DIR to Documents/system, main.m). Its outcome is logged the first time +// each one happens (which place, how many certificates, or why there is none; never a path or a certificate): a game whose own TLS takes its roots from the store +// (Super Mario Bros. Wonder's gRPC, main+0xafaf50) builds no secure channel without it, unless a stand-in CA is set (dm_ssl_set_builtin_fallback: Nextendo's, in Nextendo mode) +static void store_note(const char *what, unsigned value) { // what: a digit (which outcome, logged once), a space, the text + static _Atomic unsigned told; unsigned bit = 1u << (what[0] & 15); + if (atomic_fetch_or(&told, bit) & bit) return; + fprintf(stderr, "%sssl: certificate store: %s %u\n", strstr(what, "not found") || strstr(what, "rejected") ? "[RED] " : "", what + 2, value); +} +static NSData *store_file(const char **where) { + const char *data = getenv("DM_SYSTEM_DATA_DIR"), *system = getenv("DM_SYSTEM_DIR"); + NSString *paths[2] = { + data && data[0] ? [[NSString stringWithUTF8String:data] stringByAppendingPathComponent:@"0100000000000800/files/ssl_TrustedCerts.bdf"] : nil, + system && system[0] ? [[NSString stringWithUTF8String:system] stringByAppendingPathComponent:@"sysdata/0100000000000800/ssl_TrustedCerts.bdf"] : nil }; + const char *names[2] = {"DM_SYSTEM_DATA_DIR", "DM_SYSTEM_DIR sysdata"}; + for (int i = 0; i < 2; i++) { + if (!paths[i]) continue; + NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:paths[i] error:nil]; + if (!attributes) continue; + *where = names[i]; + return [attributes fileSize] > 4 * 1024 * 1024 ? [NSData data] : ([NSData dataWithContentsOfFile:paths[i]] ?: [NSData data]); + } + return nil; +} +static BOOL der_sequence(const uint8_t *p, NSUInteger size) { // tag 0x30, then a short or a long (1 to 3 bytes) definite length that spans exactly the rest + if (size < 2 || p[0] != 0x30) return NO; + if (p[1] < 0x80) return 2u + p[1] == size; + unsigned n = p[1] & 0x7f; if (!n || n > 3 || size < 2u + n) return NO; + NSUInteger length = 0; for (unsigned i = 0; i < n; i++) length = length << 8 | p[2 + i]; + return 2u + n + length == size; +} +static NSData *fallback_ca(void) { + bool (*provider)(const uint8_t **, size_t *) = atomic_load(&builtinFallback); const uint8_t *der = NULL; size_t size = 0; + return provider && provider(&der, &size) && der && size && size <= 65536 && der_sequence(der, size) ? [NSData dataWithBytes:der length:size] : nil; +} +static NSArray *builtin_certificates(void) { + const char *where = NULL; NSData *file = store_file(&where); + if (!file && fallback_ca()) return nil; // select_builtin serves the stand-in and says so + if (!file) { store_note("1 not found (looked for ssl_TrustedCerts.bdf under DM_SYSTEM_DATA_DIR and DM_SYSTEM_DIR/sysdata); places set:", (getenv("DM_SYSTEM_DATA_DIR") ? 1u : 0u) + (getenv("DM_SYSTEM_DIR") ? 1u : 0u)); return nil; } + if (file.length < 8 || file.length > 4 * 1024 * 1024 || memcmp(file.bytes, "sslT", 4)) { store_note("2 rejected: not a CertStore file (size or magic); bytes", (unsigned)file.length); return nil; } + uint32_t count; memcpy(&count, (const char *)file.bytes + 4, 4); + if (!count || count > 4096 || 8u + 16u * count > file.length) { store_note("3 rejected: bad entry count", count); return nil; } + NSMutableArray *entries = [NSMutableArray new]; NSMutableSet *seen = [NSMutableSet new]; unsigned unreadable = 0; + for (uint32_t i = 0; i < count; i++) { + uint32_t row[4]; memcpy(row, (const char *)file.bytes + 8 + 16 * i, sizeof row); + uint64_t offset = 8ull + row[3]; + if (!row[0] || row[0] == UINT32_MAX || [seen containsObject:@(row[0])] || row[1] > 3 || !row[2] || offset < 8u + 16u * count || offset > file.length || row[2] > file.length - offset) { + store_note("4 rejected: malformed entry at index", i); return nil; + } + NSData *der = [file subdataWithRange:NSMakeRange((NSUInteger)offset, row[2])]; + // Each entry must be one DER SEQUENCE whose encoded length is the entry's size, or the store is rejected. The game parses the certificate itself: one in that + // shape that Apple's Security framework does not read is still the firmware's bytes, served to the game, and only left out as an anchor here + if (!der_sequence(der.bytes, der.length)) { store_note("8 rejected: an entry is not one DER SEQUENCE, at index", i); return nil; } + BOOL readable = parse_certificates(der.bytes, (unsigned)der.length, 2) != nil; unreadable += !readable; + [seen addObject:@(row[0])]; [entries addObject:@{@"id":@(row[0]), @"status":@(row[1]), @"data":der, @"readable":@(readable)}]; + } + if (unreadable) store_note("5 entries Apple's Security framework does not read (still served to the game, not used as anchors):", unreadable); + store_note(strcmp(where, "DM_SYSTEM_DIR sysdata") ? "6 loaded from DM_SYSTEM_DATA_DIR, certificates:" : "7 loaded from DM_SYSTEM_DIR/sysdata, certificates:", count); + return entries; +} +static NSArray *select_builtin(const uint32_t *ids, unsigned count, bool *all, unsigned *size) { + *size = 0; *all = false; if (!ids || !count || count > 4096 || !enabled()) return nil; + NSArray *store = builtin_certificates(); + for (unsigned i = 0; i < count; i++) if (ids[i] == UINT32_MAX) *all = true; + // No firmware store: the provider's CA stands in, under each ID asked for (an All query gets it once, as ID 1). Only when no store file exists at all: + // a file that is there but rejected still fails, so a broken store is never hidden + NSData *ca = !store && !store_file(&(const char *){NULL}) ? fallback_ca() : nil; + if (ca) { + store_note("9 none on the device: Nextendo's CA stands in for the built-in certificates, IDs asked for:", count); + NSMutableArray *standIn = [NSMutableArray new]; + if (*all) [standIn addObject:@{@"id":@1u, @"status":@1u, @"data":ca, @"readable":@YES}]; + else for (unsigned i = 0; i < count; i++) [standIn addObject:@{@"id":@(ids[i]), @"status":@1u, @"data":ca, @"readable":@YES}]; + store = standIn; + } + if (!store) return nil; + NSMutableArray *selected = [NSMutableArray new]; + if (*all) [selected addObjectsFromArray:store]; + else for (unsigned i = 0; i < count; i++) { + NSDictionary *found = nil; for (NSDictionary *entry in store) if ([entry[@"id"] unsignedIntValue] == ids[i]) { found = entry; break; } + if (!found) return nil; [selected addObject:found]; + } + uint64_t needed = 24 * (selected.count + (*all ? 1 : 0)); + for (NSDictionary *entry in selected) needed += ([entry[@"data"] length] + 3u) & ~(uint64_t)3; + if (needed > UINT32_MAX) return nil; *size = (unsigned)needed; return selected; +} +uint32_t dm_ssl_builtin_size(unsigned *out, const uint32_t *ids, unsigned count) { @autoreleasepool { + if (!out || !ids) return DM_SSL_BAD_POINTER; *out = 0; bool all; + return select_builtin(ids, count, &all, out) ? 0 : DM_SSL_FAIL; +} } +uint32_t dm_ssl_builtin_certificates(void **out, uint8_t *buffer, unsigned capacity, const uint32_t *ids, unsigned count) { @autoreleasepool { + if (!out || !buffer || !ids) return DM_SSL_BAD_POINTER; *out = NULL; bool all; unsigned size; + NSArray *entries = select_builtin(ids, count, &all, &size); if (!entries || capacity < size) return DM_SSL_FAIL; + memset(buffer, 0, size); size_t position = 24 * (entries.count + (all ? 1 : 0)); + for (NSUInteger i = 0; i < entries.count; i++) { + NSDictionary *entry = entries[i]; NSData *der = entry[@"data"]; + struct { uint32_t id, status; uint64_t size; const uint8_t *data; } info = {[entry[@"id"] unsignedIntValue], [entry[@"status"] unsignedIntValue], der.length, buffer + position}; + memcpy(buffer + 24 * i, &info, sizeof info); memcpy(buffer + position, der.bytes, der.length); position += (der.length + 3u) & ~(size_t)3; + } + if (all) { uint32_t sentinel[2] = {UINT32_MAX, UINT32_MAX}; memcpy(buffer + 24 * entries.count, sentinel, sizeof sentinel); } + *out = buffer; return 0; +} } +uint32_t dm_ssl_import_server(void *object, uint64_t *id, const void *bytes, unsigned size, int format) { @autoreleasepool { + if (!object || !id || !bytes) return DM_SSL_BAD_POINTER; *id = 0; DmTlsContext *c = get_context(object); if (!c) return DM_SSL_FAIL; + NSArray *certificates = parse_certificates(bytes, size, format); if (!certificates) return DM_SSL_FAIL; + pthread_mutex_lock(®istry); uint64_t identifier = ++nextIdentifier; pthread_mutex_unlock(®istry); + [c.lock lock]; if (c.anchors.count >= 71) { [c.lock unlock]; return DM_SSL_FAIL; } c.anchors[@(identifier)] = certificates; [c.lock unlock]; if (id) *id = identifier; return 0; +} } +uint32_t dm_ssl_import_client(void *object, uint64_t *out_id, const void *bytes, const char *password, unsigned size, unsigned password_size) { @autoreleasepool { + if (!object || !out_id || !bytes || (!password && password_size)) return DM_SSL_BAD_POINTER; *out_id = 0; + DmTlsContext *c = get_context(object); if (!c || !size || size > 4 * 1024 * 1024 || password_size > 1024) return DM_SSL_FAIL; + if (@available(macOS 15.0, iOS 18.0, *)) { + NSData *data = [NSData dataWithBytes:bytes length:size]; NSString *pass = [[NSString alloc] initWithBytes:password ?: "" length:password_size encoding:NSUTF8StringEncoding]; if (!pass) return DM_SSL_FAIL; + CFArrayRef items = NULL; OSStatus status = SecPKCS12Import((__bridge CFDataRef)data, (__bridge CFDictionaryRef)@{(__bridge id)kSecImportExportPassphrase:pass, (__bridge id)kSecImportToMemoryOnly:@YES}, &items); + if (status || !items || !CFArrayGetCount(items)) { if (items) CFRelease(items); return DM_SSL_FAIL; } + NSDictionary *first = (__bridge NSDictionary *)CFArrayGetValueAtIndex(items, 0); id identity = first[(__bridge id)kSecImportItemIdentity]; NSArray *chain = first[(__bridge id)kSecImportItemCertChain]; + if (!identity) { CFRelease(items); return DM_SSL_FAIL; } + NSMutableArray *identityChain = [NSMutableArray arrayWithObject:identity]; if (chain.count > 1) [identityChain addObjectsFromArray:[chain subarrayWithRange:NSMakeRange(1, chain.count - 1)]]; + pthread_mutex_lock(®istry); uint64_t identifier = ++nextIdentifier; pthread_mutex_unlock(®istry); + [c.lock lock]; if (c.clientIdentity) { [c.lock unlock]; CFRelease(items); return DM_SSL_FAIL; } c.clientIdentity = identityChain; c.clientIdentifier = identifier; [c.lock unlock]; CFRelease(items); if (out_id) *out_id = identifier; return 0; + } + return DM_SSL_FAIL; // Never import a guest private key into the user's persistent Keychain on older macOS. +} } +uint32_t dm_ssl_remove_pki(void *object, uint64_t identifier) { @autoreleasepool { + if (!object) return DM_SSL_BAD_POINTER; DmTlsContext *c = get_context(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; BOOL found = c.anchors[@(identifier)] != nil || c.clientIdentifier == identifier; + [c.anchors removeObjectForKey:@(identifier)]; if (c.clientIdentifier == identifier) { c.clientIdentity = nil; c.clientIdentifier = 0; } [c.lock unlock]; return found ? 0 : DM_SSL_FAIL; +} } +uint32_t dm_ssl_connection_create(void *object, void *context) { @autoreleasepool { + if (!object || !context) return DM_SSL_BAD_POINTER; if (!enabled()) return DM_SSL_FAIL; + DmTlsContext *parent = get_context(context); if (!parent) return DM_SSL_FAIL; + DmTlsConnection *c = [DmTlsConnection new]; if (!c) return DM_SSL_FAIL; c.context = parent; c.lock = [NSLock new]; c.lookahead = [NSMutableData new]; c.guestDescriptor = -1; + c.ioMode = 1; c.verifyOptions = 3; c.timeout = 300000; atomic_init(&c->closed, false); atomic_init(&c->descriptor, -1); + pthread_mutex_lock(®istry); + if (contexts[key(context)] != parent || connections[key(object)] || connections.count >= 512) { pthread_mutex_unlock(®istry); return DM_SSL_FAIL; } + unsigned count = 0; for (DmTlsConnection *other in connections.allValues) if (other.context == parent) count++; + if (count >= 8) { pthread_mutex_unlock(®istry); return DM_SSL_FAIL; } + c.identifier = ++nextIdentifier; connections[key(object)] = c; pthread_mutex_unlock(®istry); return 0; +} } +uint32_t dm_ssl_connection_destroy(void *object) { @autoreleasepool { + if (!object) return DM_SSL_BAD_POINTER; pthread_once(&once, initialize_registry); pthread_mutex_lock(®istry); + DmTlsConnection *c = connections[key(object)]; if (c) { atomic_store(&c->closed, true); [connections removeObjectForKey:key(object)]; } pthread_mutex_unlock(®istry); + if (!c) return DM_SSL_FAIL; + if (atomic_load(&c->descriptor) >= 0 && !c.doNotClose && c.guestDescriptor >= 0) dm_net_close_generation(c.guestDescriptor, c.socketGeneration); + return 0; // A running operation retains c and its owned dup until it observes closed at its next readiness boundary. +} } +uint32_t dm_ssl_connection_id(void *object, uint64_t *out, bool context) { @autoreleasepool { + if (!object || !out) return DM_SSL_BAD_POINTER; + DmTlsConnection *c = get_connection(object); + *out = c ? (context ? c.context.identifier : c.identifier) : 0; return 0; +} } +uint32_t dm_ssl_set_socket(void *object, int guest) { @autoreleasepool { + if (!object) return DM_SSL_BAD_POINTER; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; if (atomic_load(&c->closed) || atomic_load(&c->descriptor) >= 0) { [c.lock unlock]; return error(c, DM_SSL_FAIL); } + uint64_t generation; int fd = dm_net_dup_native_generation(guest, &generation); + struct sockaddr_storage address; socklen_t size = sizeof address; int type = 0; socklen_t type_size = sizeof type; + if (fd < 0 || getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &type_size) || type != SOCK_STREAM || getpeername(fd, (struct sockaddr *)&address, &size)) { if (fd >= 0) close(fd); trace(c, DM_TLS_SOCKET, DM_SSL_BAD_SOCKET, 0, 0); [c.lock unlock]; return error(c, DM_SSL_BAD_SOCKET); } + c.guestDescriptor = guest; c.socketGeneration = generation; atomic_store(&c->descriptor, fd); + if (atomic_load(&c->closed)) { if (!c.doNotClose) dm_net_close_generation(guest, generation); [c.lock unlock]; return error(c, DM_SSL_BAD_SOCKET); } + trace(c, DM_TLS_SOCKET, 0, 0, 0); [c.lock unlock]; return 0; +} } +uint32_t dm_ssl_get_socket(void *object, int *out) { @autoreleasepool { if (!object || !out) return DM_SSL_BAD_POINTER; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; if (atomic_load(&c->descriptor) < 0) return error(c, DM_SSL_NO_SOCKET); *out = c.guestDescriptor; return 0; } } +uint32_t dm_ssl_set_hostname(void *object, const char *name, unsigned size) { @autoreleasepool { + if (!object || !name) return DM_SSL_BAD_POINTER; if (!size || size > 255) return DM_SSL_FAIL; + if (!name[size - 1]) size--; if (!size || memchr(name, 0, size)) return DM_SSL_FAIL; + NSString *host = [[NSString alloc] initWithBytes:name length:size encoding:NSASCIIStringEncoding]; if (!host) return DM_SSL_FAIL; + struct in6_addr literal; + unsigned name_kind = (inet_pton(AF_INET, host.UTF8String, &literal) == 1 || + inet_pton(AF_INET6, host.UTF8String, &literal) == 1) ? 2u : 0u; + bool (*guard)(const char *) = atomic_load(&peerGuard); if (guard && !guard(host.UTF8String)) { dm_tls_trace(DM_TLS_HOSTNAME, 0, DM_SSL_FAIL, 0, name_kind, 0); return DM_SSL_FAIL; } + DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; if (c.handshaking) { [c.lock unlock]; return error(c, DM_SSL_FAIL); } + NSString *peer = host; NSData *anchor = nil; BOOL pinned = NO; + dm_ssl_peer_policy_provider provider = atomic_load(&peerProvider), pin = atomic_load(&pinProvider); + if (provider || pin) { + char mapped[256] = {0}; const uint8_t *der = NULL; size_t length = 0; + pinned = pin && pin(host.UTF8String, mapped, sizeof mapped, &der, &length); + if (pinned || (provider && provider(host.UTF8String, mapped, sizeof mapped, &der, &length))) { + if (!memchr(mapped, 0, sizeof mapped) || !mapped[0] || (!der && length) || length > 4 * 1024 * 1024) { [c.lock unlock]; return error(c, DM_SSL_FAIL); } + if (pinned && (!length || !dm_nextendo_x509_available())) { [c.lock unlock]; return error(c, DM_SSL_FAIL); } + peer = [NSString stringWithUTF8String:mapped]; if (!peer) { [c.lock unlock]; return error(c, DM_SSL_FAIL); } + if (length) { anchor = [NSData dataWithBytes:der length:length]; if (!parse_certificates(anchor.bytes, (unsigned)anchor.length, 2)) { [c.lock unlock]; return error(c, DM_SSL_FAIL); } } + } + } + c.hostname = host; c.peerName = peer; c.policyAnchor = anchor; c.policyPinned = pinned; + trace(c, DM_TLS_HOSTNAME, 0, 0, 1u | name_kind); [c.lock unlock]; return 0; +} } +uint32_t dm_ssl_get_hostname(void *object, char *out, unsigned *size, unsigned capacity) { @autoreleasepool { + if (!object || !out || !size) return DM_SSL_BAD_POINTER; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; const char *name = c.hostname.UTF8String ?: ""; size_t length = strlen(name); *size = (unsigned)length; + if (capacity <= length) { [c.lock unlock]; return DM_SSL_FAIL; } memcpy(out, name, length + 1); [c.lock unlock]; return 0; +} } +uint32_t dm_ssl_set_value(void *object, int property, unsigned value) { @autoreleasepool { + if (!object) return DM_SSL_BAD_POINTER; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; uint32_t result = 0; + if (property == DM_SSL_IO_MODE && (value == 1 || value == 2)) c.ioMode = value; + else if (property == DM_SSL_VERIFY_OPTIONS && !c.handshaking && (value & 3) == 3 && !(value & ~7u)) c.verifyOptions = value; + else if (property == DM_SSL_SESSION_CACHE && !c.handshaking && value <= 2) c.sessionCache = value; + else if (property == DM_SSL_IO_TIMEOUT && value) c.timeout = value; + else result = error(c, DM_SSL_FAIL); + trace(c, DM_TLS_VALUE, result, 0, ((uint64_t)(uint32_t)property << 32) | value); + [c.lock unlock]; return result; +} } +uint32_t dm_ssl_get_value(void *object, int property, unsigned *out) { @autoreleasepool { + if (!object || !out) return DM_SSL_BAD_POINTER; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; uint32_t result = 0; + switch (property) { case DM_SSL_IO_MODE: *out = c.ioMode; break; case DM_SSL_VERIFY_OPTIONS: *out = c.verifyOptions; break; case DM_SSL_SESSION_CACHE: *out = c.sessionCache; break; case DM_SSL_IO_TIMEOUT: *out = c.timeout; break; default: result = DM_SSL_FAIL; } + [c.lock unlock]; return result; +} } +uint32_t dm_ssl_set_option(void *object, int option, unsigned value) { @autoreleasepool { + if (!object) return DM_SSL_BAD_POINTER; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; value &= 1; + [c.lock lock]; uint32_t result = 0; + if (option == 0 && atomic_load(&c->descriptor) < 0) c.doNotClose = value; + else if (option == 1) c.certificateChain = value; + else if (option == 2 && !value) { /* Verification stays enabled. */ } + else if (option == 3 && !c.handshaking) c.enableAlpn = value; + else result = DM_SSL_FAIL; + trace(c, DM_TLS_OPTION, result, 0, ((uint64_t)(uint32_t)option << 32) | value); + [c.lock unlock]; return result; +} } +uint32_t dm_ssl_get_option(void *object, void *out, int option) { @autoreleasepool { + if (!object || !out) return DM_SSL_BAD_POINTER; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; uint8_t value; + switch (option) { case 0: value = c.doNotClose; break; case 1: value = c.certificateChain; break; case 2: value = 0; break; case 3: value = c.enableAlpn; break; default: [c.lock unlock]; return DM_SSL_FAIL; } + memcpy(out, &value, 1); [c.lock unlock]; return 0; +} } + +static uint32_t prepare(DmTlsConnection *c) { + if (atomic_load(&c->closed)) return error(c, DM_SSL_BAD_SOCKET); + if (c.rejected) return error(c, DM_SSL_FAIL); + if (atomic_load(&c->descriptor) < 0) return error(c, DM_SSL_NO_SOCKET); + if (!c.peerName.length) return error(c, DM_SSL_FAIL); + if (c->tls) return 0; + c->tls = SSLCreateContext(kCFAllocatorDefault, kSSLClientSide, kSSLStreamType); if (!c->tls) return error(c, DM_SSL_FAIL); + SSLProtocol min = kTLSProtocol1, max = kTLSProtocol12; unsigned v = c.context.version & 0xff; + if (!(v & 1)) { min = v & 8 ? kTLSProtocol1 : v & 16 ? kTLSProtocol11 : kTLSProtocol12; max = v & (32 | 64) ? kTLSProtocol12 : v & 16 ? kTLSProtocol11 : kTLSProtocol1; } + OSStatus s = SSLSetProtocolVersionMin(c->tls, min); if (!s) s = SSLSetProtocolVersionMax(c->tls, max); + if (!s) s = SSLSetIOFuncs(c->tls, transport_read, transport_write); + if (!s) s = SSLSetConnection(c->tls, (__bridge SSLConnectionRef)c); + if (!s) s = SSLSetPeerDomainName(c->tls, c.peerName.UTF8String, strlen(c.peerName.UTF8String)); + if (!s) s = SSLSetSessionOption(c->tls, kSSLSessionOptionBreakOnServerAuth, true); + if (!s) s = SSLSetSessionOption(c->tls, kSSLSessionOptionEnableSessionTickets, c.sessionCache == 2); + NSString *peerID = [NSString stringWithFormat:@"nxnative:%llu:%@:%llu", c.context.identifier, c.peerName, c.sessionCache ? 0ull : c.identifier]; + if (!s) s = SSLSetPeerID(c->tls, peerID.UTF8String, strlen(peerID.UTF8String)); + if (!s && c.enableAlpn && c.alpn.count) s = SSLSetALPNProtocols(c->tls, (__bridge CFArrayRef)c.alpn); + [c.context.lock lock]; NSArray *identity = c.context.clientIdentity; [c.context.lock unlock]; + if (!s && identity.count) s = SSLSetCertificate(c->tls, (__bridge CFArrayRef)identity); + c.handshaking = YES; uint32_t result = status_result(c, s); + trace(c, DM_TLS_PREPARE, result, s, v); return result; +} +static BOOL verify_peer(DmTlsConnection *c, unsigned *reason) { + SecTrustRef trust = NULL; if (SSLCopyPeerTrust(c->tls, &trust) || !trust) return NO; + if (c.policyPinned) { + SecCertificateRef leaf = SecTrustGetCertificateAtIndex(trust, 0); + NSData *der = leaf ? CFBridgingRelease(SecCertificateCopyData(leaf)) : nil; + BOOL valid = der.length && dm_nextendo_x509_verify_pin(c.peerName.UTF8String, + c.policyAnchor.bytes, c.policyAnchor.length, der.bytes, der.length); + CFRelease(trust); return valid; + } + if (c.policyAnchor && dm_nextendo_x509_available()) { + // The route's explicit private CA is the sole authority for this path. + // BasicX509 retains Apple's chain/time/trust checks; OpenSSL adds strict + // server purpose, SAN-only hostname, constraints and strength checks. + // This does not adopt a root sent by the server or alter system trust. + NSArray *scoped = parse_certificates(c.policyAnchor.bytes, (unsigned)c.policyAnchor.length, 2); + SecPolicyRef basic = SecPolicyCreateBasicX509(); + OSStatus result = basic ? SecTrustSetPolicies(trust, basic) : errSecParam; + if (basic) CFRelease(basic); + if (!result) result = SecTrustSetNetworkFetchAllowed(trust, false); + if (!result && scoped.count == 1) result = SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef)scoped); + else if (!result) result = errSecParam; + if (!result) result = SecTrustSetAnchorCertificatesOnly(trust, true); + CFErrorRef failure = NULL; + dm_guest_host_wait_begin(); + BOOL valid = !result && SecTrustEvaluateWithError(trust, &failure); + if (!valid) *reason = DM_TLS_VERIFY_PLATFORM_TRUST; + if (valid) { + CFIndex count = SecTrustGetCertificateCount(trust); + NSMutableArray *data = [NSMutableArray new]; + const uint8_t *chain[16]; size_t sizes[16]; + if (count < 1 || count > 16) valid = NO; + for (CFIndex i = 0; valid && i < count; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(trust, i); + NSData *der = certificate ? CFBridgingRelease(SecCertificateCopyData(certificate)) : nil; + if (!der.length || der.length > 65536) { valid = NO; break; } + [data addObject:der]; chain[i] = der.bytes; sizes[i] = der.length; + } + if (valid) valid = dm_nextendo_x509_verify(c.peerName.UTF8String, c.policyAnchor.bytes, + c.policyAnchor.length, chain, sizes, (size_t)count); + if (!valid) *reason = DM_TLS_VERIFY_STRICT_X509; + } + dm_guest_host_wait_end(); + if (failure) CFRelease(failure); CFRelease(trust); return valid; + } + SecPolicyRef policy = SecPolicyCreateSSL(true, (__bridge CFStringRef)c.peerName); + OSStatus status = policy ? SecTrustSetPolicies(trust, policy) : errSecParam; if (policy) CFRelease(policy); + if (!status) status = SecTrustSetNetworkFetchAllowed(trust, false); // Nonblocking TLS must not start hidden AIA/OCSP network work. + NSMutableArray *anchors = [NSMutableArray new]; [c.context.lock lock]; for (NSArray *list in c.context.anchors.allValues) [anchors addObjectsFromArray:list]; [c.context.lock unlock]; + // Horizon's default CertStore is context-local too. Preserve the dumped trust status; + // removed, untrusted and revoked records remain retrievable, never default anchors. + for (NSDictionary *entry in builtin_certificates()) if ([entry[@"status"] unsignedIntValue] == 1 && [entry[@"readable"] boolValue]) { + NSData *der = entry[@"data"]; [anchors addObjectsFromArray:parse_certificates(der.bytes, (unsigned)der.length, 2)]; + } + if (c.policyAnchor) { NSArray *scoped = parse_certificates(c.policyAnchor.bytes, (unsigned)c.policyAnchor.length, 2); if (!scoped) { CFRelease(trust); return NO; } [anchors addObjectsFromArray:scoped]; } + if (!status && anchors.count) { status = SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef)anchors); if (!status) status = SecTrustSetAnchorCertificatesOnly(trust, false); } + CFErrorRef failure = NULL; dm_guest_host_wait_begin(); BOOL valid = !status && SecTrustEvaluateWithError(trust, &failure); dm_guest_host_wait_end(); + if (failure) CFRelease(failure); CFRelease(trust); return valid; +} +static uint32_t handshake_locked(DmTlsConnection *c) { + if (c.established) return 0; + uint32_t result = prepare(c); if (result) return result; + uint64_t deadline = clock_ms() + c.timeout; + for (;;) { + if (atomic_load(&c->closed)) return error(c, DM_SSL_BAD_SOCKET); + c->wanted = POLLIN; OSStatus status = SSLHandshake(c->tls); + if (status == errSSLServerAuthCompleted) { + unsigned reason = 0; + BOOL valid = verify_peer(c, &reason); trace(c, DM_TLS_VERIFY, valid ? 0 : DM_SSL_FAIL, status, reason); + if (!valid) { c.rejected = YES; c.verifyError = DM_SSL_FAIL; SSLSetError(c->tls, errSSLXCertChainInvalid); return error(c, DM_SSL_FAIL); } + c.verified = YES; + continue; + } + if (!status) { + if (!c.verified) { + unsigned reason = 0; + BOOL valid = verify_peer(c, &reason); trace(c, DM_TLS_VERIFY, valid ? 0 : DM_SSL_FAIL, status, reason); + if (!valid) { c.rejected = YES; c.verifyError = DM_SSL_FAIL; SSLSetError(c->tls, errSSLXCertChainInvalid); return error(c, DM_SSL_FAIL); } + } + c.verified = YES; c.established = YES; trace(c, DM_TLS_HANDSHAKE, 0, 0, 0); return error(c, 0); + } + if (status != errSSLWouldBlock || c.ioMode == 2) { uint32_t r = status_result(c, status); trace(c, DM_TLS_HANDSHAKE, r, status, 0); return r; } + result = wait_socket(c, c->wanted, deadline); if (result) return result; + } +} +uint32_t dm_ssl_handshake(void *object) { @autoreleasepool { + if (!object) return DM_SSL_BAD_POINTER; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; uint32_t result = handshake_locked(c); [c.lock unlock]; return result; +} } +static NSArray *peer_certificates(DmTlsConnection *c) { + SecTrustRef trust = NULL; if (!c->tls || SSLCopyPeerTrust(c->tls, &trust) || !trust) return nil; + NSMutableArray *out = [NSMutableArray new]; CFIndex count = SecTrustGetCertificateCount(trust); + if (!c.certificateChain && count > 1) count = 1; + for (CFIndex i = 0; i < count; i++) { SecCertificateRef certificate = SecTrustGetCertificateAtIndex(trust, i); CFDataRef data = certificate ? SecCertificateCopyData(certificate) : NULL; if (data) [out addObject:CFBridgingRelease(data)]; } + CFRelease(trust); return out; +} +static uint32_t copy_certificates(DmTlsConnection *c, unsigned *size, unsigned *count, void *buffer, unsigned capacity) { + NSArray *certificates = peer_certificates(c); if (!certificates.count) return DM_SSL_FAIL; + size_t needed = c.certificateChain ? 16 + 8 * certificates.count : 0; for (NSData *data in certificates) needed += data.length; + if (needed > UINT32_MAX) return DM_SSL_FAIL; *size = (unsigned)needed; *count = (unsigned)certificates.count; + if (!buffer || capacity < needed) return DM_SSL_FAIL; + if (!c.certificateChain) memcpy(buffer, certificates[0].bytes, needed); + else { + uint64_t magic = 0x4e4d684374726543ull; uint32_t total = *count; memset(buffer, 0, 16); memcpy(buffer, &magic, 8); memcpy((char *)buffer + 8, &total, 4); + size_t offset = 16 + 8 * certificates.count; + for (NSUInteger i = 0; i < certificates.count; i++) { NSData *data = certificates[i]; uint32_t entry[2] = {(uint32_t)data.length, (uint32_t)offset}; memcpy((char *)buffer + 16 + i * 8, entry, 8); memcpy((char *)buffer + offset, data.bytes, data.length); offset += data.length; } + } + return 0; +} +uint32_t dm_ssl_handshake_certs(void *object, unsigned *size, unsigned *count, void *buffer, unsigned capacity, bool registered_buffer) { @autoreleasepool { + if (!object) return DM_SSL_BAD_POINTER; + unsigned ignored_size = 0, ignored_count = 0; + if (!size) size = &ignored_size; + if (!count) count = &ignored_count; + *size = *count = 0; + DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; uint32_t result = handshake_locked(c); + void *output = registered_buffer ? c.certificateBuffer : buffer; + unsigned available = registered_buffer ? c.certificateCapacity : capacity; + // The SDK overload delegates to ordinary DoHandshake when either the + // certificate buffer or its capacity is zero. Export is optional; peer + // verification in handshake_locked remains mandatory in both branches. + if (!result && output && available) result = copy_certificates(c, size, count, output, available); + trace(c, DM_TLS_CERTIFICATES, result, 0, output && available ? 1 : 0); + [c.lock unlock]; return error(c, result); +} } +uint32_t dm_ssl_set_cert_buffer(void *object, void *buffer, unsigned capacity) { @autoreleasepool { + if (!object || (!buffer && capacity)) return DM_SSL_BAD_POINTER; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; c.certificateBuffer = buffer; c.certificateCapacity = capacity; [c.lock unlock]; return 0; +} } +uint32_t dm_ssl_needed_cert_size(void *object, unsigned *out) { @autoreleasepool { + if (!object || !out) return DM_SSL_BAD_POINTER; *out = 0; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + unsigned count = 0; [c.lock lock]; copy_certificates(c, out, &count, NULL, 0); [c.lock unlock]; return *out ? 0 : DM_SSL_FAIL; +} } +uint32_t dm_ssl_cipher_info(void *object, void *out) { @autoreleasepool { + if (!object || !out) return DM_SSL_BAD_POINTER; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; SSLCipherSuite cipher = 0; SSLProtocol version = kSSLProtocolUnknown; + OSStatus status = !c.established ? errSSLBadConfiguration : SSLGetNegotiatedCipher(c->tls, &cipher); if (!status) status = SSLGetNegotiatedProtocolVersion(c->tls, &version); + if (!status) { struct { char cipher[64], protocol[8]; } info = {0}; snprintf(info.cipher, sizeof info.cipher, "0x%04x", cipher); snprintf(info.protocol, sizeof info.protocol, "%s", version == kTLSProtocol12 ? "TLSv1.2" : version == kTLSProtocol11 ? "TLSv1.1" : "TLSv1.0"); memcpy(out, &info, sizeof info); } + [c.lock unlock]; return status_result(c, status); +} } +uint32_t dm_ssl_read(void *object, void *buffer, int *out, unsigned capacity, bool peek) { @autoreleasepool { + if (!object || !out || (!buffer && capacity)) return DM_SSL_BAD_POINTER; *out = 0; if (capacity > INT_MAX) return DM_SSL_FAIL; + DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; [c.lock lock]; + uint32_t result = !c.established ? DM_SSL_FAIL : 0; + if (!result && c.lookahead.length) { + NSUInteger n = MIN(c.lookahead.length, capacity); if (n) memcpy(buffer, c.lookahead.bytes, n); *out = (int)n; + if (!peek && n) [c.lookahead replaceBytesInRange:NSMakeRange(0, n) withBytes:NULL length:0]; + } else if (!result && capacity) { + unsigned request = peek ? MIN(capacity, 16384u) : capacity; // A peek may return one record; never allocate the caller's arbitrarily large capacity. + NSMutableData *temporary = peek ? [NSMutableData dataWithLength:request] : nil; void *destination = peek ? temporary.mutableBytes : buffer; + if (peek && !temporary) { [c.lock unlock]; return error(c, DM_SSL_FAIL); } + uint64_t deadline = clock_ms() + c.timeout; + for (;;) { + if (atomic_load(&c->closed)) { result = DM_SSL_BAD_SOCKET; break; } + c->wanted = POLLIN; size_t n = 0; OSStatus status = SSLRead(c->tls, destination, request, &n); + if (n || !status || status == errSSLClosedGraceful) { *out = (int)n; if (peek && n) { [c.lookahead appendBytes:destination length:n]; memcpy(buffer, destination, n); } break; } + if (status != errSSLWouldBlock || c.ioMode == 2) { result = status_result(c, status); break; } + result = wait_socket(c, c->wanted, deadline); if (result) break; + } + } + if ((!result && *out > 0 && !c.tracedRead) || (result && result != DM_SSL_WOULD_BLOCK)) { + trace(c, DM_TLS_READ, result, 0, (unsigned)*out); if (!result) c.tracedRead = YES; + } + error(c, result); [c.lock unlock]; return result; +} } +uint32_t dm_ssl_write(void *object, const void *buffer, int *out, unsigned size) { @autoreleasepool { + if (!object || !out || (!buffer && size)) return DM_SSL_BAD_POINTER; *out = 0; if (size > INT_MAX) return DM_SSL_FAIL; + DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; [c.lock lock]; + uint32_t result = !c.established ? DM_SSL_FAIL : 0; uint64_t deadline = clock_ms() + c.timeout; + NSData *pending = c.pendingWrite; NSUInteger pendingSize = pending.length; + if (!result && pendingSize && (size < pendingSize || !buffer || memcmp(buffer, pending.bytes, pendingSize))) result = DM_SSL_FAIL; + while (!result && size) { + if (atomic_load(&c->closed)) { result = DM_SSL_BAD_SOCKET; break; } + // SSLWrite's processed count can describe its encrypted cache rather than the + // native socket. Flush that cache with no new data before acknowledging this + // bounded record; retrying the plaintext would duplicate it on a blocking path. + bool flushing = c.pendingWrite != nil; unsigned request = flushing ? (unsigned)c.pendingWrite.length : MIN(size, 16384u); + c->wanted = POLLOUT; size_t n = 0; OSStatus status = SSLWrite(c->tls, flushing ? NULL : buffer, flushing ? 0 : request, &n); + if (!status) { *out = flushing ? (int)request : (int)n; c.pendingWrite = nil; break; } + if (status != errSSLWouldBlock) { result = status_result(c, status); break; } + if (!flushing) { c.pendingWrite = [NSData dataWithBytes:buffer length:request]; if (!c.pendingWrite) { result = DM_SSL_FAIL; break; } } + if (c.ioMode == 2) { result = DM_SSL_WOULD_BLOCK; break; } + result = wait_socket(c, c->wanted, deadline); + } + if ((!result && *out > 0 && !c.tracedWrite) || (result && result != DM_SSL_WOULD_BLOCK)) { + trace(c, DM_TLS_WRITE, result, 0, (unsigned)*out); if (!result) c.tracedWrite = YES; + } + error(c, result); [c.lock unlock]; return result; +} } +uint32_t dm_ssl_pending(void *object, int *out) { @autoreleasepool { + if (!object || !out) return DM_SSL_BAD_POINTER; *out = 0; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; size_t pending = 0; OSStatus status = c->tls ? SSLGetBufferedReadSize(c->tls, &pending) : noErr; + if (!status) *out = (int)MIN((size_t)INT_MAX, pending + c.lookahead.length); [c.lock unlock]; return status_result(c, status); +} } +uint32_t dm_ssl_poll(void *object, unsigned *out, const unsigned *events, unsigned timeout_ms) { @autoreleasepool { + if (!object || !out || !events) return DM_SSL_BAD_POINTER; *out = 0; unsigned requested = *events; + if (requested & ~7u) return DM_SSL_FAIL; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; [c.lock lock]; + if (atomic_load(&c->descriptor) < 0) { [c.lock unlock]; return error(c, DM_SSL_NO_SOCKET); } + size_t pending = 0; if (c->tls) SSLGetBufferedReadSize(c->tls, &pending); + if ((requested & 1) && (pending || c.lookahead.length)) *out |= 1; + uint64_t deadline = clock_ms() + timeout_ms; uint32_t result = 0; + for (;;) { + if (atomic_load(&c->closed)) { result = DM_SSL_BAD_SOCKET; break; } + uint64_t now = clock_ms(), remaining = deadline > now ? deadline - now : 0; int ms = *out ? 0 : (int)MIN(remaining, 100); + struct pollfd p = {.fd = atomic_load(&c->descriptor), .events = ((requested & 1) ? POLLIN : 0) | ((requested & 2) ? POLLOUT : 0) | ((requested & 4) ? POLLPRI : 0)}; + dm_guest_host_wait_begin(); int n = poll(&p, 1, ms), e = errno; dm_guest_host_wait_end(); + if (n < 0 && e == EINTR) continue; if (n < 0) { result = DM_SSL_BAD_SOCKET; break; } + if ((requested & 1) && (p.revents & (POLLIN | POLLHUP))) *out |= 1; + if ((requested & 2) && (p.revents & POLLOUT)) *out |= 2; + if (p.revents & (POLLERR | POLLNVAL | POLLPRI)) *out |= 4; + if (*out || clock_ms() >= deadline) break; + } + [c.lock unlock]; return error(c, result); +} } +uint32_t dm_ssl_last_error(void *object, uint32_t *out, bool verify) { @autoreleasepool { + if (!object || !out) return DM_SSL_BAD_POINTER; DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; + [c.lock lock]; *out = verify ? c.verifyError : c.lastError; if (verify) c.verifyError = 0; [c.lock unlock]; return 0; +} } +uint32_t dm_ssl_set_alpn(void *object, const uint8_t *data, unsigned size) { @autoreleasepool { + if (!object || !data) return DM_SSL_BAD_POINTER; if (size < 2 || size > 4096) return DM_SSL_FAIL; + DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; NSMutableArray *protocols = [NSMutableArray new]; + for (unsigned pos = 0; pos < size;) { unsigned n = data[pos++]; if (!n || n > size - pos) return DM_SSL_FAIL; NSString *p = [[NSString alloc] initWithBytes:data + pos length:n encoding:NSASCIIStringEncoding]; if (!p) return DM_SSL_FAIL; [protocols addObject:p]; pos += n; } + [c.lock lock]; if (c.handshaking || atomic_load(&c->descriptor) < 0) { [c.lock unlock]; return DM_SSL_FAIL; } c.alpn = protocols; [c.lock unlock]; return 0; +} } +uint32_t dm_ssl_get_alpn(void *object, unsigned *state, uint8_t *buffer, unsigned *size, unsigned capacity) { @autoreleasepool { + if (!object || !state || !size || (!buffer && capacity)) return DM_SSL_BAD_POINTER; *state = *size = 0; + DmTlsConnection *c = get_connection(object); if (!c) return DM_SSL_FAIL; [c.lock lock]; + CFArrayRef protocols = NULL; OSStatus status = c->tls ? SSLCopyALPNProtocols(c->tls, &protocols) : noErr; + if (!status && protocols && CFArrayGetCount(protocols)) { + NSString *selected = (__bridge NSString *)CFArrayGetValueAtIndex(protocols, 0); NSData *data = [selected dataUsingEncoding:NSASCIIStringEncoding]; *size = (unsigned)data.length; *state = 1; + NSUInteger length = data.length; + if (capacity < length || (length && !buffer)) status = errSecParam; else if (length) memcpy(buffer, data.bytes, length); + } + if (protocols) CFRelease(protocols); [c.lock unlock]; return status_result(c, status); +} } +uint32_t dm_ssl_cert_detail(void *out, const void *buffer, unsigned index) { + if (!out || !buffer) return DM_SSL_BAD_POINTER; + uint64_t magic; uint32_t count; memcpy(&magic, buffer, 8); memcpy(&count, (const char *)buffer + 8, 4); + if (magic != 0x4e4d684374726543ull || index >= count || count > 64) return DM_SSL_FAIL; + uint32_t entry[2]; memcpy(entry, (const char *)buffer + 16 + index * 8, 8); + if (entry[1] < 16 + count * 8 || entry[1] > UINT32_MAX - entry[0]) return DM_SSL_FAIL; + struct { uint32_t size, pad; const void *data; } detail = {entry[0], 0, (const char *)buffer + entry[1]}; memcpy(out, &detail, sizeof detail); return 0; +} +#pragma clang diagnostic pop diff --git a/dm/host/hle_thread.c b/dm/host/hle_thread.c index 7a39960720..f4b2febfd7 100644 --- a/dm/host/hle_thread.c +++ b/dm/host/hle_thread.c @@ -11,6 +11,7 @@ // All waits hang on one global lock G, with one condition variable per thread; correctness first, performance to be measured later. #include #include "dm.h" +#include #include #include #include @@ -18,6 +19,7 @@ #include #include #include +#include #include #include @@ -90,6 +92,7 @@ typedef struct thr { // when stopped in guest code the signal handler saves it into ctx_*; pcv lets the requester wait for "stopped" and the paused thread wait for "resume" _Atomic int pause_req; int paused; uint64_t *_Atomic svc_regs; uint64_t svc_pc, svc_x18; // svc_x18: the guest's x18 at SVC entry (its thread slot; the gate frame holds the Apple platform register) + unsigned svc_depth; // owned by this thread: nested host operations retain the outer guest-to-host boundary's frame // SVC exit without G: bit 0 = inside an SVC, bit 1 = a pause was requested. The exit clears bit 0 with one compare-and-swap when bit 1 is clear, and takes G only otherwise; // the requester sets bit 1 and treats the thread as stopped only if bit 0 was set, so a thread it counts as stopped in an SVC cannot leave the SVC without G (svc_regs stays valid for GetThreadContext3) _Atomic int svc_state; @@ -132,6 +135,9 @@ static inline int g_cond_wait(pthread_cond_t *cv, const struct timespec *dl) { #define MAX_H 4096 static struct { int type; void *obj; } g_h[MAX_H]; static pthread_key_t g_keythr; +// Set once svc_thread_main_init has made g_keythr. Before that the key is 0, and on Darwin slot 0 of every thread holds the thread's own pthread +// structure, so pthread_getspecific(0) is never NULL: a host thread that asked before then was taken for a guest thread (dm_thread_native_wait) +static atomic_bool g_keythr_made; static uint64_t g_next_id = 0x51; static thr_t *g_wait; // All waiting threads (lock / condition / address / synchronization) @@ -239,6 +245,8 @@ void dm_thread_service_request(void) { // between publishing its blocked state and pthread_cond_wait releasing that // mutex. On return it is runnable before it goes back to guest code. void dm_thread_native_wait(int entering) { + // a host thread before the guest threads exist: nothing to release (Nextendo's start-of-session work begins while the modules load) + if (!atomic_load_explicit(&g_keythr_made, memory_order_acquire)) return; thr_t *t = pthread_getspecific(g_keythr); if (!t) return; g_lock(); @@ -247,6 +255,8 @@ void dm_thread_native_wait(int entering) { g_unlock(); } +void dm_guest_host_wait_begin(void) { dm_thread_native_wait(1); } +void dm_guest_host_wait_end(void) { dm_thread_native_wait(0); } // The peers a handoff waits for are the ones it made runnable, not every runnable higher-priority thread of the core. The host runs a // lower-priority thread beside busy higher-priority threads of its core all the time (it has no per-core scheduler; core_preempt aside), // and waiting for those threads at a wake had no bound: Tears of the Kingdom's BootupBackgroundWorkThread (priority 58) waited at each @@ -497,6 +507,7 @@ static void on_pause_sig(int sig, siginfo_t *si, void *uc_) { // called by the gate on SVC entry / exit (gate_dispatch in hle.c) void thr_svc_enter(uint64_t *regs, uint64_t pc) { thr_t *t = pthread_getspecific(g_keythr); if (!t) return; + if (t->svc_depth++ != 0) return; // do not publish a host helper's registers or lose an outer blocking hook's frame t->svc_pc = pc; t->svc_x18 = (uint64_t)(uintptr_t)pthread_getspecific(g_key18); atomic_store(&t->svc_regs, regs); atomic_fetch_or(&t->svc_state, 1); if (atomic_load_explicit(&t->qos_pending, memory_order_relaxed) && atomic_exchange(&t->qos_pending, 0)) { g_lock(); qos_apply(t); g_unlock(); @@ -505,6 +516,15 @@ void thr_svc_enter(uint64_t *regs, uint64_t pc) { } void thr_svc_leave(void) { thr_t *t = pthread_getspecific(g_keythr); if (!t) return; + assert(t->svc_depth); + if (--t->svc_depth) { + if (!atomic_load(&t->pause_req)) return; + pthread_mutex_lock(&G); + while (t->pause_req) { t->paused = 1; pthread_cond_broadcast(&t->pcv); pthread_cond_wait(&t->pcv, &G); } + t->paused = 0; // the outer frame stays published until its own exit + pthread_mutex_unlock(&G); + return; + } int in = 1; if (atomic_compare_exchange_strong(&t->svc_state, &in, 0)) { atomic_store(&t->svc_regs, NULL); return; } // no pause requested: G is not needed (every other thread's SVC takes it) g_lock(); while (t->pause_req) { t->paused = 1; pthread_cond_broadcast(&t->pcv); g_cond_wait(&t->pcv, NULL); } @@ -613,7 +633,7 @@ static void hitch_init(void) { } // Register the main thread and return its handle (passed to nnosInitialize as the main thread handle) uint32_t svc_thread_main_init(void) { - pthread_key_create(&g_keythr, NULL); + pthread_key_create(&g_keythr, NULL); atomic_store_explicit(&g_keythr_made, true, memory_order_release); qos_map_init(); { const char *e = getenv("DM_PREEMPT"); g_core_preempt = e ? atoi(e) != 0 : DM_GAME_CORE_PREEMPT; } { const char *e = getenv("DM_WAKE_UNLOCKED"); if (e) g_wake_unlocked = atoi(e) != 0; } diff --git a/dm/host/hle_time.c b/dm/host/hle_time.c index 7e75f14961..d1fc16639a 100644 --- a/dm/host/hle_time.c +++ b/dm/host/hle_time.c @@ -144,9 +144,6 @@ HLE_FORCE("_ZN2nn4time16LoadTimeZoneRuleEPNS0_12TimeZoneRuleERKNS0_12LocationNam void *rule, const char *name) { (void)rule; LOG("time::LoadTimeZoneRule %.36s (host time zone used instead)", name ? name : "?"); return RES_OK; } HLE_FORCE("_ZN2nn4time14ToCalendarTimeEPNS0_12CalendarTimeEPNS0_22CalendarAdditionalInfoERKNS0_9PosixTimeERKNS0_12TimeZoneRuleE", "conversion with an explicit time zone rule; same as the device zone (host localtime_r)", Result, h_time_ToCalendarTimeRule, CalendarTime *ct, CalendarAdditionalInfo *ai, const int64_t *pt, const void *rule) { (void)rule; return h_time_ToCalendarTime(ct, ai, pt); } -// Whether the network clock's last sync is recent enough (the service compares the steady time point of its context with now). The host does not know when its clock last synced, -// so it never claims it: the answer a Switch gives when its last sync is old -HLE_FORCE("_ZN2nn4time26StandardNetworkSystemClock20IsAccuracySufficientEv", "network clock accuracy (time service): the host does not know its last sync, never sufficient", unsigned, h_time_NetAccurate, void) { return 0; } // Clock snapshot (Tears of the Kingdom: CreateWithStandardSystemClock asks the time service, which the host never opens → abort in sm::Initialize). 0xD0 bytes, laid out // as Ryujinx lays out the service's ClockSnapshot and as this SDK's constructor clears it (its last store is the byte at +0xcd): +0x00 user clock context {offset, // steady time point}, +0x20 network clock context, +0x40 user time, +0x48 network time, +0x50 / +0x58 user / network calendar, +0x60 / +0x78 their additional info, diff --git a/dm/host/loader.c b/dm/host/loader.c index 5fdd9d7505..201a599356 100644 --- a/dm/host/loader.c +++ b/dm/host/loader.c @@ -12,7 +12,10 @@ #include #include #include "hle.h" +#include "net_socket.h" #include "../gfx/nvn/nvn_fstep.h" // the state page's target and tick unit (FSTEP_UNIT_OFF, nvn_fstep_target_put) + +static char g_nextendo_dir[1024]; // Nextendo's patched main, when it is the one loaded (nextendo_main) #if TARGET_OS_IPHONE #include #endif @@ -336,6 +339,14 @@ static void *force_lookup(const char *name) { } return NULL; } +// Validate the complete linked production table without loading game data, +// creating a window or reading credentials. Component-only fixtures cannot +// detect duplicate hooks registered in a different translation unit. +void dm_validate_hle_registry(void) { + if (!g_fmask) force_init(); + (void)hle_implements("__dm_registry_validation__"); + LOG("HLE registry validated: %u unique forced takeovers",g_nforce); +} // Generic host: the list serves several games, so entries a game does not reference are only noted; with DM_FORCE_STRICT=1 it still fails loudly (for checking a mistyped list) static void force_check(void) { unsigned unused = 0, disabled = 0; int strict = getenv("DM_FORCE_STRICT") != NULL; @@ -893,6 +904,8 @@ void dm_set_game_image_header(const void *mh) { g_game_image = mh; } typedef struct { char name[32]; uint64_t off[3][2]; } nro_ent; // DM_EMBED_TAG (main.m, an app holding several programs of one game): the running program's sections are tagged (gen_embed.py --tag: __dmx0, …, __dm_nro_x0) static const char *embed_tag(void) { const char *t = getenv("DM_EMBED_TAG"); return t ? t : ""; } +// The embedded module's name: Nextendo's patched main is nmain (gen_embed.py, nextendo_main) +static const char *embed_name(const module_t *m) { return g_nextendo_dir[0] && !strcmp(m->name, "main") ? "nmain" : m->name; } static int nro_pieces(const char *name, const uint8_t **x0, unsigned long *z0, const uint8_t **w, unsigned long *zw, const uint8_t **x1, unsigned long *z1) { unsigned long zt, s0, sw, s1; char st[17], s0n[17], swn[17], s1n[17]; const char *g = embed_tag(); @@ -908,8 +921,8 @@ static int nro_pieces(const char *name, const uint8_t **x0, unsigned long *z0, c } static void map_image(module_t *m, const char *dir) { (void)dir; - char sx0[17], sx1[17], dm[17]; const char *g = embed_tag(); - snprintf(sx0, sizeof sx0, "__dm%s%sx0", g, m->name); snprintf(sx1, sizeof sx1, "__dm%s%sx1", g, m->name); snprintf(dm, sizeof dm, "__DM%s%sW", g, m->name); + char sx0[17], sx1[17], dm[17]; const char *g = embed_tag(), *nm = embed_name(m); + snprintf(sx0, sizeof sx0, "__dm%s%sx0", g, nm); snprintf(sx1, sizeof sx1, "__dm%s%sx1", g, nm); snprintf(dm, sizeof dm, "__DM%s%sW", g, nm); unsigned long z0 = 0, zw = 0, z1 = 0; const uint8_t *x0 = NULL, *w = NULL, *x1 = NULL; if (m->nro) { if (!nro_pieces(m->name, &x0, &z0, &w, &zw, &x1, &z1)) die("NRO %s: not in the embedded NRO table (__DATA,__dm_nro_tab)", m->name); } @@ -918,7 +931,7 @@ static void map_image(module_t *m, const char *dir) { // The back patch area (patch_nso.py TWO) is a fourth section, __dmx2; NROs never have one (nro_pieces holds three pieces) unsigned long z2 = 0; const uint8_t *x2 = NULL; if (m->back_len) { - char sx2[17]; snprintf(sx2, sizeof sx2, "__dm%s%sx2", g, m->name); + char sx2[17]; snprintf(sx2, sizeof sx2, "__dm%s%sx2", g, nm); if (m->nro || !(x2 = getsectiondata(IMAGE_MH, "__TEXT", sx2, &z2)) || z2 != m->back_len || ((uintptr_t)x2 & 0x3FFF)) die("embedded back patch area %s missing or wrong", sx2); } // Patch area before the base (patch_off < 0): W ends at the end of data (FILE_IMAGE_LEN); bss and the key page are zero pages from vm_allocate and are not in the executable @@ -1066,8 +1079,29 @@ static void map_image(module_t *m, const char *dir) { static char g_module_dir[1024]; // the folder the modules were loaded from (dm_module_dir) const char *dm_module_dir(void) { return g_module_dir; } +// A --nextendo build (scripts/build_ipa_from_nsp.py nextendo_build) rewrites a copy of main with Nextendo's signed game patch into /nextendo. With Nextendo on +// (net_socket.h dm_net_nextendo_enabled), main comes from there; offline, LAN and LDN keep the original. On the iPhone, /nextendo holds the copy's tables and its +// code is embedded as module nmain (gen_embed.py; g_nextendo_dir, map_image) +static const char *module_dir(const module_t *m, const char *dir) { return g_nextendo_dir[0] && !strcmp(m->name, "main") ? g_nextendo_dir : dir; } +// A Nextendo session starts with the game: the account's Mii (hle_nextendo_social_apple.m has the strong definition; other hosts have none) +__attribute__((weak)) void dm_nextendo_session_start(void) {} +static void nextendo_main(const char *dir) { + g_nextendo_dir[0] = 0; + if (!dm_net_nextendo_enabled()) return; + dm_nextendo_session_start(); + char path[1100]; struct stat st; + if ((size_t)snprintf(g_nextendo_dir, sizeof g_nextendo_dir, "%s/nextendo", dir) >= sizeof g_nextendo_dir) die("Nextendo: module folder path too long: %s", dir); + snprintf(path, sizeof path, "%s/main.fixups.tsv", g_nextendo_dir); + if (lstat(path, &st) || !S_ISREG(st.st_mode)) { + LOG("Nextendo: no patched main in %s (the build had no --nextendo, or Nextendo publishes no patch for this build): the original main runs online", g_nextendo_dir); + g_nextendo_dir[0] = 0; return; + } + LOG("Nextendo: main from %s (Nextendo's signed game patch)", g_nextendo_dir); +} + void load_modules(const char *dir, const char **names, int n) { strlcpy(g_module_dir, dir, sizeof g_module_dir); + nextendo_main(dir); // Map everything and parse the symbol tables first, then relocate all at once (cross-module symbols must all be in place first) // DM_BOOTPROF: breakdown of ① host loading (milliseconds), to set the upper bound for ③ pre-relocation / mmap uint64_t t0 = now_ns(), tm = 0, tp = 0, tg = 0, tr = 0, t; @@ -1075,10 +1109,10 @@ void load_modules(const char *dir, const char **names, int n) { allocate_modules(n, nros); for (int i = 0; i < n; i++) { module_t *m = &g_mod[i]; - // "/": a module from another folder (a mod's code plugin), else one of the module folder + // "/": a module from another folder (a mod's code plugin), else one of the module folder (Nextendo's patched main: its own, module_dir) const char *sl = strrchr(names[i], '/'); if (sl) { char *d = strndup(names[i], (size_t)(sl - names[i])); if (!d) die("module folder"); m->dir = d; strlcpy(m->name, sl + 1, sizeof m->name); } - else { m->dir = g_module_dir; strlcpy(m->name, names[i], sizeof m->name); } + else { strlcpy(m->name, names[i], sizeof m->name); m->dir = module_dir(m, g_module_dir); } read_layout(m, m->dir); } create_keys(); diff --git a/dm/host/main.c b/dm/host/main.c index 283e09842a..606d6a76c1 100644 --- a/dm/host/main.c +++ b/dm/host/main.c @@ -1,6 +1,7 @@ // Bootstrap: after loading the modules, initialize the SDK runtime in the real order of nn::init::Start (sdk+0x2b0470) in the SDK, then enter nnMain. #include "dm.h" #include "front.h" +#include "nextendo_bcat.h" #include "../gfx/nvn/dmsh_chain.h" #include #include @@ -14,8 +15,12 @@ static void *req(const char *n){ void *p=guest_sym(n); if(!p) die("missing symbo // Game arguments: argv[0] is fixed to "game", and whatever follows "--" is appended as is (on a real device nn::init takes them from the process argument area and hands them to the SDK through SetHostArgc/Argv) static char *g_argv[64] = {"game"}; static int g_argc = 1; +static const char *g_module_directory; static void guest_main(void) { + // Calendar selection precedes all SDK initialization and the first guest + // filesystem read. The optional online provider defaults to offline. + dm_bcat_pre_guest_start(g_module_directory,DM_GAME_ID); guest_thread_init(); guest_gate_stack(0); // the guest code runs on this thread's own stack: its SVCs get a stack of their own { void dm_oodle_serve_maybe(int); dm_oodle_serve_maybe(0); } // DM_OODLE_SERVE tool mode: the game's own Oodle decoder over stdin / stdout (hle_oodle.c, exits when the input ends) @@ -99,6 +104,7 @@ static pthread_key_t g_race_keys[512]; static unsigned g_race_n, g_race_want; static void *keyrace_thread(void *unused); static void host_preload(int argc, char **argv) { + g_module_directory=argc>1?argv[1]:NULL; g_t0_ns = proc_start_mono_ns(); flags_init(); { void dm_diag_samplers_start(void); dm_diag_samplers_start(); } // DM_MEMSTAT / DM_THRCPU (memstat.m): after the iOS front end has set the env files' switches @@ -170,6 +176,7 @@ void dm_host_preload_start(int argc, char **argv) { if (pthread_create(&g_pre.th, &a, preload_thread, NULL)) die("dm_host_preload_start: cannot start the thread"); } int main(int argc, char **argv) { + if (argc==2 && !strcmp(argv[1],"--validate-hle")) { void dm_validate_hle_registry(void); dm_validate_hle_registry(); return 0; } if (argc == 2 && !strcmp(argv[1], "--check-tables")) { int dm_check_tables(void); return dm_check_tables(); } // build-time check of the linked __DATA,swforce table (loader.c) { int mtl_pso_prebuild_tool(void); int r = mtl_pso_prebuild_tool(); if (r) return r == 2; } // DM_PSO_PREBUILD=tool: what a first start would build, made with no game (nvn_mtl.m) if (getenv("DM_PRELOAD")) dm_host_preload_start(argc, argv); // Exercise the early-start path on Mac (on iOS it is called from the App's main()) diff --git a/dm/host/net_discovery.h b/dm/host/net_discovery.h new file mode 100644 index 0000000000..294dbc3f43 --- /dev/null +++ b/dm/host/net_discovery.h @@ -0,0 +1,43 @@ +// A bounded IPv4 discovery sweep. Addresses are in network byte order. +#pragma once +#include +#include +#include +#include + +enum { DM_DISCOVERY_BATCH = 32, DM_DISCOVERY_TICK_MS = 8, DM_DISCOVERY_MAX_HOSTS = 4094 }; +typedef struct { + uint32_t local, first, last, target, cursor; + unsigned count, automatic; +} dm_net_discovery_plan; +// Darwin can report a negative ARP entry as EHOSTDOWN. These are destination +// failures, not permission/interface failures; skip that neighbor in a sweep. +static inline int dm_net_discovery_unreachable(int error) { + return error==EHOSTUNREACH||error==ENETUNREACH||error==EHOSTDOWN; +} + +// This takes a validated adapter snapshot, not a guessed address range. /31, +// /32, noncontiguous masks and networks broader than /20 are not discoverable. +static inline int dm_net_discovery_subnet(dm_net_discovery_plan *p, uint32_t address, uint32_t mask) { + memset(p, 0, sizeof *p); + uint32_t a = ntohl(address), m = ntohl(mask), hosts = ~m; + if (!m || (hosts & (hosts + 1)) || hosts < 3 || hosts > DM_DISCOVERY_MAX_HOSTS + 1u || + !a || a >= 0xe0000000u || !(a & hosts) || (a & hosts) == hosts) return -1; + p->local = a; p->first = (a & m) + 1; p->last = (a | hosts) - 1; + p->cursor = p->first; p->count = hosts - 2; p->automatic = 1; + return 0; +} +static inline int dm_net_discovery_next(dm_net_discovery_plan *p, uint32_t *address) { + if (!p->automatic) { + if (p->cursor++) return 0; + *address = p->target; return 1; + } + while (p->cursor <= p->last) { + uint32_t a = p->cursor++; + if (a != p->local) { *address = htonl(a); return 1; } + } + return 0; +} +static inline unsigned dm_net_discovery_duration(const dm_net_discovery_plan *p) { + return p->automatic ? ((p->count + DM_DISCOVERY_BATCH - 1) / DM_DISCOVERY_BATCH) * DM_DISCOVERY_TICK_MS : 0; +} diff --git a/dm/host/net_discovery_queue.inc b/dm/host/net_discovery_queue.inc new file mode 100644 index 0000000000..f01e51bf62 --- /dev/null +++ b/dm/host/net_discovery_queue.inc @@ -0,0 +1,128 @@ +// Discovery-only UDP fanout. A duplicate retains the original kernel socket, +// source port and socket options. Slot generations cancel work on close/reuse. +// Queuing a datagram has UDP's usual best-effort delivery semantics; it is not +// an acknowledgement from a console. No ordinary unicast enters this queue. +enum { NET_DISCOVERY_JOBS = 16, NET_DISCOVERY_PER_SOCKET = 2, NET_DISCOVERY_BYTES = 32768 }; +typedef struct { + net_ref socket; dm_net_discovery_plan plan; struct sockaddr_in destination; + size_t size; int flags; uint64_t expires; unsigned char bytes[]; +} net_discovery_job; +static pthread_mutex_t g_discovery_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t g_discovery_changed = PTHREAD_COND_INITIALIZER; +static net_discovery_job *g_discovery_jobs[NET_DISCOVERY_JOBS]; +static int g_discovery_started; +#ifdef DM_NET_TEST +static _Atomic(dm_net_test_discovery_sender) g_discovery_sender; +void dm_net_test_set_discovery_sender(dm_net_test_discovery_sender sender) { atomic_store(&g_discovery_sender,sender); } +#endif +static long net_discovery_packet(int fd,const void *bytes,size_t size,int flags,const struct sockaddr_in *destination) { +#ifdef DM_NET_TEST + dm_net_test_discovery_sender sender=atomic_load(&g_discovery_sender); + if(sender)return sender(fd,bytes,size,flags,destination->sin_addr.s_addr,destination->sin_port); +#endif + return sendto(fd,bytes,size,flags,(const struct sockaddr *)destination,sizeof *destination); +} +long dm_net_discovery_send_native(int fd,const void *bytes,size_t size,int flags,uint32_t address,uint16_t port) { + struct sockaddr_in destination={.sin_len=sizeof destination,.sin_family=AF_INET,.sin_port=port,.sin_addr={address}}; + return net_discovery_packet(fd,bytes,size,flags,&destination); +} +static void net_discovery_drop(unsigned i) { + net_discovery_job *job = g_discovery_jobs[i]; + if (job) { close(job->socket.fd); free(job); g_discovery_jobs[i] = NULL; } +} +static void net_discovery_cancel(int guest, uint64_t generation) { + pthread_mutex_lock(&g_discovery_lock); + for (unsigned i = 0; i < NET_DISCOVERY_JOBS; ++i) + if (g_discovery_jobs[i] && g_discovery_jobs[i]->socket.guest == guest && + g_discovery_jobs[i]->socket.generation == generation) net_discovery_drop(i); + pthread_cond_signal(&g_discovery_changed); pthread_mutex_unlock(&g_discovery_lock); +} +static void *net_discovery_worker(void *unused) { + (void)unused; unsigned cursor = 0; uint64_t next = 0; + pthread_mutex_lock(&g_discovery_lock); + for (;;) { + unsigned i, n; + for (n = 0; n < NET_DISCOVERY_JOBS; ++n) { + i = (cursor + n) % NET_DISCOVERY_JOBS; + net_discovery_job *job = g_discovery_jobs[i]; + if (job && (!dm_net_enabled() || !net_live(&job->socket) || net_ms() >= job->expires)) net_discovery_drop(i); + if (g_discovery_jobs[i]) break; + } + if (n == NET_DISCOVERY_JOBS) { pthread_cond_wait(&g_discovery_changed, &g_discovery_lock); continue; } + uint64_t now = net_ms(); + if (now < next) { + struct timespec deadline; clock_gettime(CLOCK_REALTIME, &deadline); + deadline.tv_nsec += (long)(next - now) * 1000000L; + deadline.tv_sec += deadline.tv_nsec / 1000000000L; deadline.tv_nsec %= 1000000000L; + pthread_cond_timedwait(&g_discovery_changed, &g_discovery_lock, &deadline); continue; + } + net_discovery_job *job = g_discovery_jobs[i]; unsigned sent = 0, bytes = 0; + for (; sent < DM_DISCOVERY_BATCH; ++sent) { + if (sent && bytes + job->size > NET_DISCOVERY_BYTES) break; + dm_net_discovery_plan saved = job->plan; uint32_t address; + if (!dm_net_discovery_next(&job->plan, &address)) { net_discovery_drop(i); break; } + job->destination.sin_addr.s_addr = address; + ssize_t result = net_discovery_packet(job->socket.fd, job->bytes, job->size, job->flags,&job->destination); + if (result < 0 && (errno == EAGAIN || errno == ENOBUFS || errno == EINTR)) { job->plan = saved; break; } + if(result<0&&!dm_net_discovery_unreachable(errno)) { net_discovery_drop(i);break; } + // An unreachable neighbor does not prevent discovery of others. + bytes += (unsigned)job->size; + } + cursor = (i + 1) % NET_DISCOVERY_JOBS; next = net_ms() + DM_DISCOVERY_TICK_MS; + } + return NULL; +} +static long net_discovery_enqueue(const net_ref *socket, dm_net_discovery_plan plan, + struct sockaddr_in destination, const void *bytes, size_t size, int flags) { + if (size > 65507) return net_error(90); + net_discovery_job *job = malloc(sizeof *job + size); + if (!job) return net_error(12); + *job = (net_discovery_job){.socket = *socket, .plan = plan, .destination = destination, + .size = size, .flags = flags, .expires = net_ms() + 30000}; + if (size) memcpy(job->bytes, bytes, size); + pthread_mutex_lock(&g_discovery_lock); unsigned free_slot = NET_DISCOVERY_JOBS, same = 0; + for (unsigned i = 0; i < NET_DISCOVERY_JOBS; ++i) { + net_discovery_job *old = g_discovery_jobs[i]; + if (!old) { free_slot = i; continue; } + if (old->socket.guest != socket->guest || old->socket.generation != socket->generation) continue; + ++same; + if (old->size == size && old->flags == flags && old->destination.sin_port == destination.sin_port && + old->plan.first == plan.first && old->plan.last == plan.last && old->plan.local == plan.local && + (!size || !memcmp(old->bytes, bytes, size))) { + // Repeated identical queries during one sweep do not multiply it. + pthread_mutex_unlock(&g_discovery_lock); free(job); return (long)size; + } + } + if (free_slot == NET_DISCOVERY_JOBS || same >= NET_DISCOVERY_PER_SOCKET) { + pthread_mutex_unlock(&g_discovery_lock); free(job); return net_error(105); + } + if (!g_discovery_started) { + pthread_t thread; int error = pthread_create(&thread, NULL, net_discovery_worker, NULL); + if (error) { pthread_mutex_unlock(&g_discovery_lock); free(job); return net_error(net_errno(error)); } + pthread_detach(thread); g_discovery_started = 1; + } + job->socket.fd = fcntl(socket->fd, F_DUPFD_CLOEXEC, 0); + if (job->socket.fd < 0) { int error = errno; pthread_mutex_unlock(&g_discovery_lock); free(job); return net_error(net_errno(error)); } + ssize_t result=(ssize_t)size; + for(unsigned attempt=0;attemptplan,&first)) { + int error=errno;close(job->socket.fd);pthread_mutex_unlock(&g_discovery_lock);free(job);return net_error(net_errno(error)); + } + job->destination.sin_addr.s_addr=first; + result=net_discovery_packet(job->socket.fd,bytes,size,flags,&job->destination); + if(result>=0)break; + int error=errno; + if(dm_net_discovery_unreachable(error)) { result=(ssize_t)size;continue; } + close(job->socket.fd);pthread_mutex_unlock(&g_discovery_lock);free(job);return net_error(net_errno(error)); + } + g_discovery_jobs[free_slot] = job; pthread_cond_signal(&g_discovery_changed); + pthread_mutex_unlock(&g_discovery_lock); return result; +} +#ifdef DM_NET_TEST +unsigned dm_net_test_discovery_pending(void) { + unsigned count = 0; pthread_mutex_lock(&g_discovery_lock); + for (unsigned i = 0; i < NET_DISCOVERY_JOBS; ++i) count += g_discovery_jobs[i] != NULL; + pthread_mutex_unlock(&g_discovery_lock); return count; +} +#endif diff --git a/dm/host/net_socket.h b/dm/host/net_socket.h new file mode 100644 index 0000000000..057e4cc999 --- /dev/null +++ b/dm/host/net_socket.h @@ -0,0 +1,97 @@ +// Horizon socket ABI, translated by hle_net_backend.c. Opt-in Apple IPv4 TCP/UDP. +#pragma once +#include +#include +#include +#include "net_discovery.h" + +typedef struct { int32_t fd; int16_t events, revents; } dm_net_pollfd; +typedef struct { int32_t flags, family, type, protocol; uint32_t addrlen, pad; void *addr; char *canonname; void *next; } dm_net_addrinfo; +typedef struct { int32_t flags, family, type, protocol; uint32_t addrlen, pad; char *canonname; void *addr; void *next; } dm_net_addrinfo_legacy; +typedef enum { DM_NET_OFFLINE, DM_NET_LAN, DM_NET_LDN, DM_NET_NEXTENDO, DM_NET_AUTO } dm_net_mode_t; +dm_net_mode_t dm_net_mode(void); +// Automatic enables independent service capabilities, not a mutable global +// session type. The guest chooses sockets, LDN or online APIs from its menu. +static inline int dm_net_nextendo_enabled(void) { + dm_net_mode_t mode = dm_net_mode(); + const char *profile = getenv("DM_NEXTENDO_ROUTES"); + // A missing profile leaves automatic local play unchanged. An explicitly + // supplied but invalid profile still enables fail-closed service policy. + return mode == DM_NET_NEXTENDO || (mode == DM_NET_AUTO && profile && *profile); +} +static inline int dm_net_ldn_enabled(void) { + dm_net_mode_t mode = dm_net_mode(); + return mode == DM_NET_LDN || mode == DM_NET_AUTO; +} +int dm_net_enabled(void); +// Startup-only DNS policy: -1 refuses, 0 keeps the name, 1 supplies IPv4. +// Only explicit Nextendo/auto modes consult the provider. +typedef int (*dm_net_dns_provider)(const char *host, char *output, size_t capacity); +void dm_net_set_dns_provider(dm_net_dns_provider provider); +// Internal host API: caller owns the CLOEXEC, non-blocking duplicate. Closing or +// reusing the guest descriptor cannot attach the duplicate to another connection. +int dm_net_dup_native(int guest); +int dm_net_dup_native_generation(int guest, uint64_t *generation); +int dm_net_close_generation(int guest, uint64_t generation); +// Discovery uses native broadcast when permitted, an optional explicit peer, or +// a bounded unicast sweep of the actual adapter. Ordinary unicast is unchanged. +int dm_net_discovery_prepare(uint32_t destination, dm_net_discovery_plan *plan); +// For verified discovery queries only: 1 supplies a best-effort complementary +// unicast plan, 0 keeps native behavior. Does not alter the real capability, +// explicit peer choice, or the guest's last errno on native success. +int dm_net_discovery_supplement(uint32_t destination,dm_net_discovery_plan *plan); +// Internal native UDP sender shared by both discovery transports. Addresses +// and ports use network order. This does not apply a discovery policy itself. +long dm_net_discovery_send_native(int fd,const void *bytes,size_t size,int flags, + uint32_t address,uint16_t port); +int dm_net_discovery_target(uint32_t broadcast, uint32_t *target); +void dm_net_set_multicast_allowed(int allowed); +int dm_net_multicast_allowed(void); +#ifdef DM_NET_TEST +// Test-only adapter snapshots let real loopback datagrams exercise the complete +// production send path without probing the user's LAN or enabling broadcast. +typedef struct { uint32_t address, mask; unsigned index, flags; int local_link; } dm_net_test_interface; +void dm_net_test_set_interface(const dm_net_test_interface *interface); +unsigned dm_net_test_discovery_pending(void); +typedef long (*dm_net_test_discovery_sender)(int fd,const void *bytes,size_t size,int flags, + uint32_t address,uint16_t port); +void dm_net_test_set_discovery_sender(dm_net_test_discovery_sender sender); +#endif +int dm_net_errno(void); +void dm_net_set_errno(int e); +// A failed socket call also sets the game's own errno (hle_net.c): on Horizon nn::socket's errno is the C library's (detail::SetLastErrno writes +// *__errno_location()), and code such as gRPC's reads errno itself. Called by the hooks only, on the game's thread; returns r +long dm_net_guest_errno(long r); +int dm_net_guest_errno_get(void); // the game's errno, or the host's when the game has no __errno_location +int dm_net_socket(int family, int type, int protocol); +int dm_net_close(int fd); +int dm_net_socket_type(int fd); // 1 stream, 2 datagram, 0 none the host made; sets no errno +// Event descriptors in a network mode, in the socket table's numbering (hle_net_backend.c): Horizon's EventFd flags, Linux errno through dm_net_errno +int dm_net_eventfd(uint64_t initial, int flags); +int dm_net_eventfd_read(int fd, uint64_t *value); +int dm_net_eventfd_write(int fd, uint64_t value); +void dm_net_finalize(void); +int dm_net_bind(int fd, const void *addr, unsigned len); +int dm_net_connect(int fd, const void *addr, unsigned len); +int dm_net_listen(int fd, int backlog); +int dm_net_accept(int fd, void *addr, unsigned *len); +int dm_net_name(int fd, void *addr, unsigned *len, int peer); +int dm_net_shutdown(int fd, int how); +int dm_net_fcntl(int fd, int cmd, int flags); +int dm_net_sockopt(int fd, int level, int option, void *value, unsigned *len, int set); +long dm_net_recv(int fd, void *buf, unsigned long len, int flags, void *addr, unsigned *addrlen); +long dm_net_send(int fd, const void *buf, unsigned long len, int flags, const void *addr, unsigned addrlen); +int dm_net_poll(void *fds, uint64_t count, int timeout_ms); +int dm_net_idle(void); +int dm_net_select(int nfds, void *read, void *write, void *except, const int64_t *timeout); +int dm_net_getaddrinfo(const char *host, const char *service, const void *hints, void **result); +int dm_net_getaddrinfo_legacy(const char *host, const char *service, const void *hints, void **result); +void dm_net_freeaddrinfo(void *result); +void *dm_net_gethostbyname(const char *name); +// The cancellation identity owns no socket or registry slot until a query starts. +void *dm_net_gethostbyname_cancel(const char *name, uint32_t cancel_id); +uint32_t dm_net_request_cancel_handle(void); +int dm_net_cancel(uint32_t cancel_id); +int dm_net_ipconfig(uint32_t *address, uint32_t *mask, uint32_t *gateway, uint32_t *dns1, uint32_t *dns2); +int dm_nifm_available(void); +void dm_nifm_submit_wait(void); diff --git a/dm/host/nextendo_account.h b/dm/host/nextendo_account.h new file mode 100644 index 0000000000..3754fa76a1 --- /dev/null +++ b/dm/host/nextendo_account.h @@ -0,0 +1,43 @@ +// Native account bridge. The embedding host owns storage and authorization. +#pragma once +#include +#include +#include + +enum { DM_ACCOUNT_OK = 0, DM_ACCOUNT_FAIL = 0x2a2 }; +// Explicit embedding provider, installed before guest startup. It copies schema-1 +// JSON into the bounded caller buffer. It must not show UI or wait for authorization. +// No provider means unavailable; no token is accepted through the environment. +typedef bool (*dm_nextendo_credential_provider)(uint8_t *buffer, size_t capacity, size_t *size); +void dm_nextendo_set_credential_provider(dm_nextendo_credential_provider provider); +// Bundle metadata is read from the original game's CFBundleShortVersionString. +// An embedding host may provide its actual version before guest startup (not an update substitute). +void dm_nextendo_set_game_version(const char *version); +uint32_t dm_nextendo_account_available(uint8_t *out); +uint32_t dm_nextendo_account_id(uint64_t *out); +uint32_t dm_nextendo_account_ensure(void); +uint32_t dm_nextendo_account_load_token(uint64_t *size, char *buffer, uint64_t capacity); +// The signed-in Nextendo account's country ("FR"), "" when it has none; a network request the first time (hle_nextendo_api_apple.m) +uint32_t dm_nextendo_account_country(char output[3]); +// The signed-in Nextendo account's birthday ("1990-05-12"), "" when /api/me gives none; a network request the first time (hle_nextendo_api_apple.m) +uint32_t dm_nextendo_account_birthday(char output[11]); +// The signed-in Nextendo account's username, cut to the 32 bytes of an nn::account::Nickname at a UTF-8 character boundary (hle_nextendo_apple.m) +uint32_t dm_nextendo_account_username(char output[33]); +// Public PKCS#1 RSA key for verifying this process's local envelope signature. +// This does not claim registration with Nintendo or a Nextendo JWKS service. +uint32_t dm_nextendo_copy_public_signing_key(void *buffer, uint64_t capacity, uint64_t *size); +void dm_nextendo_async_construct(void *object); +void dm_nextendo_async_destroy(void *object); +void *dm_nextendo_async_move(void *object, void *source); +void dm_nextendo_async_swap(void *object, void *other); +uint32_t dm_nextendo_async_ensure(void *object); +// Execute an actual service operation with the same cancellation, move and +// completion-event lifetimes as account requests. The callback may block. +typedef uint32_t (*dm_nextendo_async_operation)(const void *context); +uint32_t dm_nextendo_async_execute(void *object, dm_nextendo_async_operation operation, const void *context); +uint32_t dm_nextendo_async_cancel(void *object); +uint32_t dm_nextendo_async_done(void *object, uint8_t *out); +uint32_t dm_nextendo_async_result(void *object); +bool dm_nextendo_async_valid(void *object); +uint64_t dm_nextendo_async_lifetime(void *object); +uint32_t dm_nextendo_async_attach(void *object, uint64_t lifetime, uint64_t event_binding); diff --git a/dm/host/nextendo_api_apple.h b/dm/host/nextendo_api_apple.h new file mode 100644 index 0000000000..b9588ba6cc --- /dev/null +++ b/dm/host/nextendo_api_apple.h @@ -0,0 +1,21 @@ +// Internal native HTTPS boundary. Never exposed to the guest HLE symbol table. +#pragma once +#import +#include +#include +#include + +// In explicit Nextendo mode with a currently valid game credential, the token resource takes (hle_nextendo_apple.m): the nx2 game token for +// "online-status"; for the others the sign-in's OAuth access token, or the nx2 game token without one. +NSString *dm_nextendo_api_bearer(const char *resource); +NSData *dm_nextendo_api_identity(void); +bool dm_nextendo_api_baas_namespace(const char *kind); +uint32_t dm_nextendo_api_baas_id(uint64_t *output); +// Only the canonical provider's friends, me, profile and presence (posted) resources are admitted, each with an output buffer. +uint32_t dm_nextendo_api_request(const char *resource, const uint8_t *body, size_t body_size, + uint8_t *output, size_t capacity, size_t *output_size); +#ifdef DM_NEXTENDO_API_TEST +typedef bool (*dm_nextendo_api_transport)(const char *url, const char *method, const char *authorization, + const uint8_t *body, size_t body_size, uint8_t *output, size_t capacity, size_t *size, unsigned *status); +void dm_nextendo_api_test_transport(dm_nextendo_api_transport transport); +#endif diff --git a/dm/host/nextendo_bcat.h b/dm/host/nextendo_bcat.h new file mode 100644 index 0000000000..d3be2f3134 --- /dev/null +++ b/dm/host/nextendo_bcat.h @@ -0,0 +1,31 @@ +#ifndef DM_NEXTENDO_BCAT_H +#define DM_NEXTENDO_BCAT_H +#include +#include +/* Public calendar data only. No account credential is required or accepted. */ +int dm_bcat_supported(const char *title); +/* Build helper: a verified catalog and complete immutable snapshot are required. */ +int dm_bcat_prepare(const char *title, const char *version, const char *catalog, + const char *destination, char *error, size_t error_size); +int dm_bcat_validate(const char *title, const char *version, const char *directory); +/* Called from the pre-guest boot thread, never from a UI/render callback. + * Online launches check before selecting the immutable RomFS overlay, sharing + * a 12-second network budget. Offline/errors retain the last validated copy. + * Later guest synchronization refreshes delivery opens only, never live RomFS. */ +void dm_bcat_start(const char *module_directory, const char *title, int online); +/* Optional online provider absent => offline. A valid local recipe is also + * required before any catalog/archive request can occur. */ +void dm_bcat_pre_guest_start(const char *module_directory, const char *title); +/* A provider may override the weak offline default after checking its own + * explicit network preference and configured, valid service policy. */ +int dm_bcat_online_enabled(void); +const char *dm_bcat_overlay(void); +const char *dm_bcat_delivery(void); +int dm_bcat_copy_delivery(char *out, size_t size); +int dm_bcat_request_sync(void); +int dm_bcat_sync_status(unsigned *result, uint64_t *downloaded); +void *dm_bcat_sync_observe(void); +int dm_bcat_sync_observer_status(const void *observer, unsigned *result, uint64_t *downloaded); +void dm_bcat_sync_release(void *observer); +void dm_bcat_digest(const void *bytes, size_t length, unsigned char out[16]); +#endif diff --git a/dm/host/nextendo_login_apple.inc b/dm/host/nextendo_login_apple.inc new file mode 100644 index 0000000000..958d874cb8 --- /dev/null +++ b/dm/host/nextendo_login_apple.inc @@ -0,0 +1,468 @@ +// SPDX-License-Identifier: MIT +// Nextendo sign-in on the Mac and the iPhone. Users: the host's credential provider (hle_nextendo_login_apple.m), the Mac tool +// (dm/tools/nextendo_login.m) and the iPhone app (dm/ios/Sources/NextendoSignIn.m). Written from Nextendo's public OAuth interface: +// - sign-in: OAuth 2 authorization code with PKCE (S256) at /oauth/authorize, redirected to a loopback address on this device; +// - /api/oauth/token trades the code, later the stored refresh token, for an access token, and sends a new refresh token each time; +// - /api/nex-token, with that access token, gives the game token: "nx2." base64url("..") "." signature. +// Only the refresh token is kept, in a private file (0600 in a 0700 folder) rather than the Keychain, which would ask again after every +// rebuild of dmhost; on the iPhone the folder is in the app's container. Tokens never go to the log: errors carry Nextendo's error code +// or the HTTP status. +#import +#import +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Not every user of this file needs every definition, hence the unused attributes. +static NSString *const kNxScopes __attribute__((unused)) = @"identity friends game.matchmaking presence profil"; // profil: /api/profile, the account's Mii (hle_nextendo_social_apple.m) +static NSString *const kNxAuthorize __attribute__((unused)) = @"https://nextendo.network/oauth/authorize"; +static NSString *const kNxTokenEndpoint __attribute__((unused)) = @"https://nextendo.network/api/oauth/token"; +static NSString *const kNxGameTokenEndpoint __attribute__((unused)) = @"https://nextendo.network/api/nex-token"; +static NSString *const kNxOnlineStatusEndpoint __attribute__((unused)) = @"https://nextendo.network/api/online-status"; +static NSString *const kNxUserInfoEndpoint __attribute__((unused)) = @"https://nextendo.network/api/oauth/userinfo"; +// The redirect is http://127.0.0.1:/callback. That client was registered with this port, so it is tried first; Nextendo also takes +// other loopback ports, which are used when it is busy. +static const uint16_t kNxCallbackPort __attribute__((unused)) = 47823; +static const NSTimeInterval kNxTimeout __attribute__((unused)) = 12; +enum { kNxRefreshMax = 8192, kNxReplyMax = 64 * 1024 }; + +__attribute__((unused)) static void nxl_fail(NSString **error, NSString *text) { if (error) *error = text; } + +// The OAuth client this build signs in as: a "public application (PKCE)" its builder registered at nextendo.network/developers, whose +// name Nextendo's sign-in page shows. DM_NEXTENDO_CLIENT_ID in the environment (the Mac), else DMNextendoClientID in the app's Info.plist +// (build_ipa.sh writes it from DM_NEXTENDO_CLIENT_ID at build time). nil when the build has none: then nobody can sign in. +__attribute__((unused)) static NSString *nxl_client_id(void) { + const char *env = getenv("DM_NEXTENDO_CLIENT_ID"); + id value = env && *env ? @(env) : [NSBundle.mainBundle objectForInfoDictionaryKey:@"DMNextendoClientID"]; + if (![value isKindOfClass:NSString.class] || [value length] == 0 || [value length] > 128) return nil; + NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_."]; + return [value rangeOfCharacterFromSet:allowed.invertedSet].location == NSNotFound ? value : nil; +} +static NSString *const kNxNoClient __attribute__((unused)) = + @"this build has no Nextendo client ID: register a public application at nextendo.network/developers and build with DM_NEXTENDO_CLIENT_ID set to its ID"; + +// ---- The stored refresh token ---- + +__attribute__((unused)) static NSString *nxl_dir(void) { + const char *dir = getenv("DM_NEXTENDO_LOGIN_DIR"); // tests point it at a scratch folder + return dir && *dir ? @(dir) : [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/nxnative/nextendo"]; +} +__attribute__((unused)) static NSString *nxl_refresh_path(void) { return [nxl_dir() stringByAppendingPathComponent:@"refresh_token"]; } + +// nil unless the file is a regular file of this user's that no one else can read, and not a link +__attribute__((unused)) static NSString *nxl_read_refresh(void) { + int fd = open(nxl_refresh_path().fileSystemRepresentation, O_RDONLY | O_NOFOLLOW | O_CLOEXEC); + if (fd < 0) return nil; + struct stat info; + bool private_file = !fstat(fd, &info) && S_ISREG(info.st_mode) && !(info.st_mode & (S_IRWXG | S_IRWXO)) && info.st_uid == geteuid() + && info.st_size > 0 && info.st_size <= kNxRefreshMax; + char text[kNxRefreshMax + 1]; ssize_t length = 0; + if (private_file) { + // NOLINTNEXTLINE(clang-analyzer-unix.BlockInCriticalSection): callers hold the sign-in's file lock (nxl_lock) on purpose, one refresh at a time; this reads a private regular file of at most kNxRefreshMax bytes + for (ssize_t n; length < info.st_size && (n = read(fd, text + length, (size_t)(info.st_size - length))) > 0;) length += n; + private_file = length == info.st_size; + } + close(fd); + if (!private_file) return nil; + NSString *token = [[NSString alloc] initWithBytes:text length:(NSUInteger)length encoding:NSUTF8StringEncoding]; + token = [token stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; + return token.length ? token : nil; +} + +// Saves the token through a temporary file and a rename, so a reader sees the old one or the new one; nil deletes it +__attribute__((unused)) static BOOL nxl_write_refresh(NSString *token) { + const char *path = nxl_refresh_path().fileSystemRepresentation; + if (!token) return unlink(path) == 0 || errno == ENOENT; + NSString *dir = nxl_dir(); + NSError *problem = nil; + if (![NSFileManager.defaultManager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:@{NSFilePosixPermissions: @0700} error:&problem] + || chmod(dir.fileSystemRepresentation, 0700) != 0) return NO; + NSString *staging = [dir stringByAppendingPathComponent:[NSString stringWithFormat:@".refresh_token.%d", getpid()]]; + unlink(staging.fileSystemRepresentation); + int fd = open(staging.fileSystemRepresentation, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); + if (fd < 0) return NO; + const char *bytes = token.UTF8String; size_t size = strlen(bytes), written = 0; + for (ssize_t n; written < size && (n = write(fd, bytes + written, size - written)) > 0;) written += (size_t)n; + bool saved = written == size && fsync(fd) == 0; + saved = close(fd) == 0 && saved && rename(staging.fileSystemRepresentation, path) == 0; + if (!saved) unlink(staging.fileSystemRepresentation); + return saved; +} + +// ---- Encoding ---- + +__attribute__((unused)) static NSString *nxl_b64url(NSData *data) { + NSMutableString *text = [[data base64EncodedStringWithOptions:0] mutableCopy]; + [text replaceOccurrencesOfString:@"+" withString:@"-" options:0 range:NSMakeRange(0, text.length)]; + [text replaceOccurrencesOfString:@"/" withString:@"_" options:0 range:NSMakeRange(0, text.length)]; + [text replaceOccurrencesOfString:@"=" withString:@"" options:0 range:NSMakeRange(0, text.length)]; + return text; +} +__attribute__((unused)) static NSData *nxl_unb64url(NSString *text) { + NSMutableString *padded = [text mutableCopy]; + [padded replaceOccurrencesOfString:@"-" withString:@"+" options:0 range:NSMakeRange(0, padded.length)]; + [padded replaceOccurrencesOfString:@"_" withString:@"/" options:0 range:NSMakeRange(0, padded.length)]; + while (padded.length % 4) [padded appendString:@"="]; + return [[NSData alloc] initWithBase64EncodedString:padded options:0]; +} +// application/x-www-form-urlencoded, with only RFC 3986's unreserved characters left as they are +__attribute__((unused)) static NSData *nxl_form_body(NSDictionary *fields) { + NSCharacterSet *unreserved = [NSCharacterSet characterSetWithCharactersInString: + @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"]; + NSMutableArray *pairs = [NSMutableArray arrayWithCapacity:fields.count]; + [fields enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) { + (void)stop; [pairs addObject:[NSString stringWithFormat:@"%@=%@", name, [value stringByAddingPercentEncodingWithAllowedCharacters:unreserved]]]; + }]; + return [[pairs componentsJoinedByString:@"&"] dataUsingEncoding:NSUTF8StringEncoding]; +} + +// ---- Nextendo's HTTPS endpoints ---- + +// Nextendo's clock less this device's, from the Date header of its last answer; 0 until one arrives, and below 2 s (the header has whole +// seconds). The game token's expiry is Nextendo's time, and the id token a game hands to Nextendo's game servers carries times they judge by +// their clock, so the sign-in judges and stamps them by this device's clock plus the offset (nxl_now, dm_nextendo_clock_offset): a phone whose +// time is set by hand still signs in. An offset of a minute or more is logged, again whenever its whole minutes change +static _Atomic double nxl_clock_offset; +__attribute__((unused)) static void nxl_note_server_date(NSHTTPURLResponse *response) { + NSString *header = [response valueForHTTPHeaderField:@"Date"]; if (!header.length) return; + NSDateFormatter *format = [NSDateFormatter new]; + format.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; format.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; + format.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss zzz"; // RFC 9110's IMF-fixdate, the form every current server sends + NSDate *server = [format dateFromString:header]; if (!server) return; + double offset = server.timeIntervalSince1970 - NSDate.date.timeIntervalSince1970; if (fabs(offset) < 2) offset = 0; + double before = atomic_exchange(&nxl_clock_offset, offset); + long minutes = (long)(offset / 60); + if (minutes && minutes != (long)(before / 60)) + fprintf(stderr, "[dm] [RED] nextendo: this device's clock is %ld min %s Nextendo's: set Date & Time to automatic; the sign-in uses Nextendo's time meanwhile\n", + labs(minutes), offset > 0 ? "behind" : "ahead of"); +} +__attribute__((unused)) static NSTimeInterval nxl_now(void) { return NSDate.date.timeIntervalSince1970 + atomic_load(&nxl_clock_offset); } + +// A request to one of the fixed endpoints above, fetched fresh. nil only if the endpoint were not a URL, which nxl_send reports as a failure +__attribute__((unused)) static NSMutableURLRequest *nxl_request(NSString *endpoint, NSTimeInterval timeout) { + NSURL *url = [NSURL URLWithString:endpoint]; + return url ? [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:timeout] : nil; +} +// The host credential provider and the iOS sign-in screen each include this file. +#ifndef NXL_TRANSFER_CLASS +#define NXL_TRANSFER_CLASS DmNextendoLoginTransfer +#endif +@interface NXL_TRANSFER_CLASS : NSObject +@property(nonatomic, readonly) NSMutableData *body; +@property(nonatomic, readonly) dispatch_semaphore_t finished; +@property(nonatomic, readonly) BOOL oversized; +@property(nonatomic, readonly) NSError *transport; +@end +@implementation NXL_TRANSFER_CLASS +- (instancetype)init { + if ((self = [super init])) { _body = [NSMutableData new]; _finished = dispatch_semaphore_create(0); } + return self; +} +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition))completion { + (void)session; (void)task; + _oversized = response.expectedContentLength > kNxReplyMax; + completion(_oversized ? NSURLSessionResponseCancel : NSURLSessionResponseAllow); +} +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data { + (void)session; + if (_oversized) return; + if (data.length > kNxReplyMax - _body.length) { _oversized = YES; [task cancel]; } + else [_body appendData:data]; +} +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { + (void)session; (void)task; _transport = error; dispatch_semaphore_signal(_finished); +} +@end + +// The caller's deadline bounds the whole request, not the idle time between bytes. After timeout the session still owns its delegate. +static NSDictionary *nxl_send_with_config(NSURLRequest *request, NSURLSessionConfiguration *config, NSString **error) { + if (!request) { nxl_fail(error, @"the endpoint is not a URL"); return nil; } + NSTimeInterval timeout = request.timeoutInterval > 0 ? fmin(request.timeoutInterval, kNxTimeout) : kNxTimeout; + config.timeoutIntervalForResource = timeout; + NXL_TRANSFER_CLASS *transfer = [NXL_TRANSFER_CLASS new]; + NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:transfer delegateQueue:nil]; + NSURLSessionDataTask *task = [session dataTaskWithRequest:request]; + dispatch_time_t deadline = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC)); + [task resume]; + if (dispatch_semaphore_wait(transfer.finished, deadline)) { + [session invalidateAndCancel]; nxl_fail(error, @"Nextendo did not answer in time"); return nil; + } + [session finishTasksAndInvalidate]; + if (transfer.oversized) { nxl_fail(error, @"Nextendo's answer is too large"); return nil; } + if (transfer.transport) { + nxl_fail(error, transfer.transport.code == NSURLErrorTimedOut ? @"Nextendo did not answer in time" : @"no complete answer from Nextendo"); + return nil; + } + NSHTTPURLResponse *response = [task.response isKindOfClass:NSHTTPURLResponse.class] ? (NSHTTPURLResponse *)task.response : nil; + NSData *body = transfer.body; + if (response) nxl_note_server_date(response); + id parsed = body.length ? [NSJSONSerialization JSONObjectWithData:body options:0 error:nil] : nil; + NSDictionary *json = [parsed isKindOfClass:NSDictionary.class] ? parsed : nil; + if (response.statusCode == 200) { + if (!json) nxl_fail(error, @"the answer from nextendo.network was not a JSON object"); + return json; + } + id code = json[@"error"]; + if ([code isKindOfClass:NSString.class]) nxl_fail(error, code); + else if (!response) nxl_fail(error, @"no answer from Nextendo (no response)"); + else nxl_fail(error, [NSString stringWithFormat:@"Nextendo answered HTTP %ld", (long)response.statusCode]); + return nil; +} +__attribute__((unused)) static NSDictionary *nxl_send(NSURLRequest *request, NSString **error) { + return nxl_send_with_config(request, NSURLSessionConfiguration.ephemeralSessionConfiguration, error); +} +#undef NXL_TRANSFER_CLASS + +// POSTs a grant to the token endpoint. Returns the access token and saves the refresh token that comes with it. A refused refresh +// token (invalid_grant) is deleted, since it will never work again +__attribute__((unused)) static NSString *nxl_token(NSDictionary *grant, NSString **error) { + NSMutableURLRequest *post = nxl_request(kNxTokenEndpoint, kNxTimeout); + post.HTTPMethod = @"POST"; + post.HTTPBody = nxl_form_body(grant); + [post setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; + NSString *why = nil; + NSDictionary *answer = nxl_send(post, &why); + if (!answer) { + bool refreshing = [grant[@"grant_type"] isEqual:@"refresh_token"]; + if (refreshing && [why isEqual:@"invalid_grant"]) { nxl_write_refresh(nil); why = @"the saved sign-in is no longer accepted: sign in to Nextendo again"; } + nxl_fail(error, why); + return nil; + } + NSString *access = answer[@"access_token"], *refresh = answer[@"refresh_token"]; + if (![access isKindOfClass:NSString.class] || access.length == 0) { nxl_fail(error, @"the token answer had no access_token"); return nil; } + if ([refresh isKindOfClass:NSString.class] && refresh.length && !nxl_write_refresh(refresh)) { + nxl_fail(error, @"the renewed refresh token could not be written"); + return nil; + } + return access; +} + +// The record hle_nextendo_apple.m's decode_credential accepts for an nx2 game token. Its identity is read from the token itself +// (".."; a username may contain dots), so the two can never disagree +__attribute__((unused)) static NSDictionary *nxl_record(NSString *token, NSTimeInterval now, NSString **error) { + NSArray *segments = [token componentsSeparatedByString:@"."]; + if (segments.count != 3 || ![segments[0] isEqual:@"nx2"]) { nxl_fail(error, @"the game token is not in nx2 form"); return nil; } + NSData *payload = nxl_unb64url(segments[1]); + NSString *claims = payload ? [[NSString alloc] initWithData:payload encoding:NSUTF8StringEncoding] : nil; + NSRange first = [claims rangeOfString:@"."], last = [claims rangeOfString:@"." options:NSBackwardsSearch]; + if (!claims || first.location == NSNotFound || last.location <= first.location + 1) { nxl_fail(error, @"the game token carries no player ID and name"); return nil; } + NSString *pidText = [claims substringToIndex:first.location], *expiryText = [claims substringFromIndex:last.location + 1]; + NSString *username = [claims substringWithRange:NSMakeRange(first.location + 1, last.location - first.location - 1)]; + NSCharacterSet *notDigit = NSCharacterSet.decimalDigitCharacterSet.invertedSet; + unsigned long long pid = strtoull(pidText.UTF8String, NULL, 10), expiry = strtoull(expiryText.UTF8String, NULL, 10); + bool numeric = pidText.length && expiryText.length && pidText.length <= 20 && expiryText.length <= 20 + && [pidText rangeOfCharacterFromSet:notDigit].location == NSNotFound && [expiryText rangeOfCharacterFromSet:notDigit].location == NSNotFound; + if (!numeric || pid == 0) { nxl_fail(error, @"the game token carries no player ID and name"); return nil; } + if ((double)expiry <= now) { nxl_fail(error, @"the game token is past its expiry"); return nil; } + return @{@"schema_version": @1, @"token_kind": @"nex", @"token": token, + @"identity": @{@"pid": @(pid), @"username": username}, + @"created_at": @(floor(now)), @"expires_at": @(expiry), + @"scopes": [kNxScopes componentsSeparatedByString:@" "]}; +} + +// /api/oauth/userinfo names the account the sign-in belongs to. The game token must be that account's (NX Port Studio checks the same): +// a mismatch, or no answer, gives no record +__attribute__((unused)) static BOOL nxl_same_account(NSString *access, NSDictionary *record, NSString **error) { + NSMutableURLRequest *get = nxl_request(kNxUserInfoEndpoint, kNxTimeout); + [get setValue:[NSString stringWithFormat:@"Bearer %@", access] forHTTPHeaderField:@"Authorization"]; + NSDictionary *answer = nxl_send(get, error); + if (!answer) return NO; + NSNumber *pid = record[@"identity"][@"pid"]; NSString *username = record[@"identity"][@"username"]; + bool named = false, same = true; // the account may sit at the top level, under "account" or under "identity"; each one present must agree + for (id place in @[answer, answer[@"account"] ?: NSNull.null, answer[@"identity"] ?: NSNull.null]) { + if (![place isKindOfClass:NSDictionary.class] || !place[@"pid"]) continue; + named = true; + same = same && [place[@"pid"] isKindOfClass:NSNumber.class] && [place[@"pid"] isEqual:pid] && [place[@"username"] isEqual:username]; + } + if (!named) { nxl_fail(error, @"nextendo.network did not say which account the sign-in belongs to"); return NO; } + if (!same) { nxl_fail(error, @"the game token belongs to another account than the sign-in; sign out and sign in again"); return NO; } + return YES; +} + +static NSString *nxl_refusal_words(id given); +// /api/online-status says whether this account may play online now: {"allow": true}, or {"allow": false, "reason": ...}. When it refuses, +// the reason in words for the player; nil when it allows, cannot be asked, or gives no answer +__attribute__((unused)) static NSString *nxl_online_refusal(NSString *access) { + NSMutableURLRequest *get = nxl_request(kNxOnlineStatusEndpoint, 8); + [get setValue:[NSString stringWithFormat:@"Bearer %@", access] forHTTPHeaderField:@"Authorization"]; + NSDictionary *answer = nxl_send(get, NULL); + if (![answer[@"allow"] isEqual:@NO]) return nil; + return nxl_refusal_words(answer[@"reason"]); +} +// A refusal's reason ("unverified", "discord_unlinked", ...) in words for the player. Nextendo's game servers apply the same gates at +// the game's own login, where the NEX protocol carries no reason (a game shows an authentication error, Mario Kart 8 Deluxe 2306-0807) +__attribute__((unused)) static NSString *nxl_refusal_words(id given) { + NSString *reason = [given isKindOfClass:NSString.class] ? given : @""; + NSDictionary *words = @{ + @"discord_unlinked": @"link a Discord account on your nextendo.network account page", + @"unverified": @"verify the account's e-mail address with the link Nextendo sent you", + @"elsewhere": @"this account is online on another device; leave online play there first", + @"disabled": @"this account is disabled", + @"unknown": @"Nextendo does not know this account; sign out and sign in again"}; + NSString *what = words[reason] ?: [NSString stringWithFormat:@"Nextendo gave the reason \"%@\"", reason.length ? reason : @"none"]; + return [@"Nextendo does not allow online play yet: " stringByAppendingString:what]; +} + +// Each refresh replaces the token the next one needs, so one runs at a time, across threads and processes (the Mac tool beside dmhost, +// the iPhone launcher's check beside the game): an exclusive flock on a file in the sign-in's folder. The descriptor (close releases it), +// or -1 when the folder does not exist, which means no sign-in is saved either +__attribute__((unused)) static int nxl_lock(void) { + int fd = open([nxl_dir() stringByAppendingPathComponent:@".lock"].fileSystemRepresentation, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0600); + if (fd >= 0 && flock(fd, LOCK_EX) != 0) { close(fd); fd = -1; } + return fd; +} + +// From an access token to a game token's record: /api/nex-token, then the account check. nil and the reason when a step fails +__attribute__((unused)) static NSDictionary *nxl_record_for(NSString *access, NSString **error) { + NSMutableURLRequest *get = nxl_request(kNxGameTokenEndpoint, kNxTimeout); + [get setValue:[NSString stringWithFormat:@"Bearer %@", access] forHTTPHeaderField:@"Authorization"]; + NSDictionary *answer = nxl_send(get, error); + NSString *token = answer[@"nex_token"]; + if (![token isKindOfClass:NSString.class] || token.length == 0) { + NSString *reason = nxl_online_refusal(access); + if (reason) nxl_fail(error, reason); + else if (answer) nxl_fail(error, @"Nextendo issued no game token for this account (Nextendo asks for a verified e-mail address and a Discord link before online play)"); + return nil; + } + NSDictionary *record = nxl_record(token, nxl_now(), error); + return record && nxl_same_account(access, record, error) ? record : nil; +} + +// From the saved sign-in to a game token's record: refresh grant (under nxl_lock), then nxl_record_for. nil and the reason when a step fails. +// With access set, it also gets the refresh's access token (about an hour's life), which the caller keeps in memory only and never logs +__attribute__((unused)) static NSDictionary *nxl_game_record_access(NSString **error, NSString **access_out) { + if (access_out) *access_out = nil; + NSString *client = nxl_client_id(); + if (!client) { nxl_fail(error, kNxNoClient); return nil; } + int lock = nxl_lock(); + NSString *refresh = nxl_read_refresh(); + NSString *access = refresh ? nxl_token(@{@"grant_type": @"refresh_token", @"refresh_token": refresh, @"client_id": client}, error) : nil; + if (lock >= 0) close(lock); + if (!refresh) { +#if TARGET_OS_IPHONE + nxl_fail(error, @"this iPhone is not signed in to Nextendo: sign in on the game's settings screen"); +#else + nxl_fail(error, @"this Mac is not signed in to Nextendo: run nextendo_login sign-in"); +#endif + return nil; + } + NSDictionary *record = access ? nxl_record_for(access, error) : nil; + if (record && access_out) *access_out = access; + return record; +} +__attribute__((unused)) static NSDictionary *nxl_game_record(NSString **error) { return nxl_game_record_access(error, NULL); } + +// ---- Signing in (the browser part belongs to the caller: the Mac opens the default browser, the iPhone a web authentication session) ---- + +__attribute__((unused)) static NSString *nxl_random_urlsafe(size_t bytes) { + NSMutableData *random = [NSMutableData dataWithLength:bytes]; + if (bytes == 0 || bytes > 64 || SecRandomCopyBytes(kSecRandomDefault, bytes, random.mutableBytes) != errSecSuccess) return nil; + return nxl_b64url(random); +} + +// A TCP listener on 127.0.0.1 for the redirect: kNxCallbackPort when free, else a port the system picks. The descriptor, or -1 +__attribute__((unused)) static int nxl_listen_loopback(uint16_t *port) { + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) return -1; + int on = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on); + struct sockaddr_in address = {.sin_len = sizeof address, .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK)}; + const uint16_t tries[2] = {kNxCallbackPort, 0}; + bool bound = false; + for (int i = 0; i < 2 && !bound; i++) { address.sin_port = htons(tries[i]); bound = bind(fd, (struct sockaddr *)&address, sizeof address) == 0; } + socklen_t size = sizeof address; + if (!bound || listen(fd, 4) != 0 || getsockname(fd, (struct sockaddr *)&address, &size) != 0) { close(fd); return -1; } + *port = ntohs(address.sin_port); + return fd; +} + +__attribute__((unused)) static void nxl_answer(int client, int status, const char *html) { + char header[200]; + int length = snprintf(header, sizeof header, "HTTP/1.1 %d %s\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %zu\r\nConnection: close\r\n\r\n", + status, status == 200 ? "OK" : "Not Found", strlen(html)); + (void)!write(client, header, (size_t)length); + (void)!write(client, html, strlen(html)); +} + +// Serves the listener until a GET /callback with our state arrives (anything else gets a 404) and returns its query parameters. +// nil once `seconds` pass or *cancel (may be NULL) becomes nonzero; the poll wakes twice a second to notice that +__attribute__((unused)) static NSDictionary *nxl_wait_callback(int fd, NSString *state, int seconds, _Atomic int *cancel) { + const time_t deadline = time(NULL) + seconds; + while (!(cancel && atomic_load(cancel)) && time(NULL) < deadline) { + struct pollfd ready = {.fd = fd, .events = POLLIN}; + if (poll(&ready, 1, 500) <= 0) continue; + int client = accept(fd, NULL, NULL); + if (client < 0) continue; + int on = 1; // a browser's preconnect may close before the answer; a write to it must fail, not raise SIGPIPE + setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof on); + struct timeval limit = {.tv_sec = 5}; + setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &limit, sizeof limit); + char request[16384]; size_t have = 0; // only the request line is needed + while (have < sizeof request - 1 && !memchr(request, '\n', have)) { + ssize_t n = read(client, request + have, sizeof request - 1 - have); + if (n <= 0) break; + have += (size_t)n; + } + request[have] = 0; + char target[16384] = ""; + NSDictionary *query = nil; + NSString *path = sscanf(request, "GET %16383s HTTP/", target) == 1 ? [NSString stringWithUTF8String:target] : nil; // nil when not UTF-8 + if (path) { + NSURLComponents *url = [NSURLComponents componentsWithString:[@"http://127.0.0.1" stringByAppendingString:path]]; + NSMutableDictionary *items = [NSMutableDictionary dictionary]; + for (NSURLQueryItem *item in url.queryItems) items[item.name] = item.value ?: @""; + if ([url.path isEqual:@"/callback"] && [items[@"state"] isEqual:state]) query = items; + } + if (query) nxl_answer(client, 200, "nxnative

Nextendo sign-in received. You can close this page.

"); + else nxl_answer(client, 404, ""); + close(client); + if (query) return query; + } + return nil; +} + +// Nextendo's sign-in page for this redirect, with `state` and the S256 challenge of `verifier` +__attribute__((unused)) static NSURL *nxl_authorize_url(NSString *redirect, NSString *state, NSString *verifier) { + NSData *plain = [verifier dataUsingEncoding:NSUTF8StringEncoding]; + NSMutableData *challenge = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH]; + CC_SHA256(plain.bytes, (CC_LONG)plain.length, challenge.mutableBytes); + NSURLComponents *page = [NSURLComponents componentsWithString:kNxAuthorize]; + NSString *client = nxl_client_id(); + if (!client) return nil; // callers check nxl_client_id() first + NSDictionary *parameters = @{@"response_type": @"code", @"client_id": client, @"redirect_uri": redirect, @"scope": kNxScopes, + @"state": state, @"code_challenge": nxl_b64url(challenge), @"code_challenge_method": @"S256"}; + NSMutableArray *items = [NSMutableArray array]; + for (NSString *name in [parameters.allKeys sortedArrayUsingSelector:@selector(compare:)]) [items addObject:[NSURLQueryItem queryItemWithName:name value:parameters[name]]]; + page.queryItems = items; + return page.URL; +} + +// After the redirect: the code becomes the saved sign-in, and a game token is fetched as a game would, to show the account works. +// nil and the reason when a step fails +__attribute__((unused)) static NSDictionary *nxl_finish_sign_in(NSDictionary *query, NSString *verifier, NSString *redirect, NSString **error) { + if (!query) { nxl_fail(error, @"no answer from the sign-in page"); return nil; } + if (query[@"error"]) { nxl_fail(error, [NSString stringWithFormat:@"the sign-in page answered with an error: %@", query[@"error"]]); return nil; } + NSString *code = query[@"code"]; + if (code.length == 0) { nxl_fail(error, @"the sign-in page returned without an authorization code"); return nil; } + NSString *client = nxl_client_id(); + if (!client) { nxl_fail(error, kNxNoClient); return nil; } + NSDictionary *grant = @{@"grant_type": @"authorization_code", @"code": code, @"code_verifier": verifier, @"redirect_uri": redirect, @"client_id": client}; + int lock = nxl_lock(); + nxl_write_refresh(nil); + NSString *access = nxl_token(grant, error), *saved = nxl_read_refresh(); + if (lock >= 0) close(lock); + if (!access) return nil; + if (!saved) { nxl_fail(error, @"the token answer had no refresh_token, so there is nothing to keep for later"); return nil; } + return nxl_record_for(access, error); // the code's own access token: no second refresh +} diff --git a/dm/host/nextendo_routes.h b/dm/host/nextendo_routes.h new file mode 100644 index 0000000000..0e407cf4f9 --- /dev/null +++ b/dm/host/nextendo_routes.h @@ -0,0 +1,22 @@ +// Public endpoint policy, separate from account credentials and game eligibility. +#pragma once +#include +enum { DM_NEXTENDO_ROUTES_UNINITIALIZED = -1, DM_NEXTENDO_ROUTES_READY = 0, + DM_NEXTENDO_ROUTES_MISSING = 1, DM_NEXTENDO_ROUTES_INVALID = 2, + DM_NEXTENDO_ROUTES_IO = 3, DM_NEXTENDO_ROUTES_LIMIT = 4, + DM_NEXTENDO_ROUTES_CERTIFICATE = 5 }; +// Call after network preferences and before the guest. Reads DM_NEXTENDO_ROUTES +// once; no token is accepted through the file or environment. Repeated calls are +// idempotent. DNS/TLS callbacks also initialize lazily if registered at startup. +// V2's pinned-exact kind requires an explicitly enrolled, hash-checked DER leaf +// for one exact host, with unchanged SNI. It never discovers or updates a pin. +// pinned-address pairs one numeric handoff with that exact identity, address and +// certificate. An unpaired address or a changed certificate is rejected. +int dm_nextendo_routes_initialize(void); +int dm_nextendo_routes_status(void); +size_t dm_nextendo_routes_count(void); +// Explicit setup recovery only. A successfully published policy stays immutable. +int dm_nextendo_routes_retry_unconfigured(void); + +// Strong capability hook for an optional BCAT backend; absent providers default off. +int dm_bcat_online_enabled(void); diff --git a/dm/host/nextendo_social.h b/dm/host/nextendo_social.h new file mode 100644 index 0000000000..68934f4979 --- /dev/null +++ b/dm/host/nextendo_social.h @@ -0,0 +1,27 @@ +// Provider social data, independent of the guest SDK's object ABI. +#pragma once +#include +#include +#include +enum { DM_SOCIAL_FRIEND_MAX=1024, DM_SOCIAL_APP_FIELD=192 }; +typedef struct { + uint64_t pid, nsa, application, last_online; + char nickname[33]; + uint8_t app_field[DM_SOCIAL_APP_FIELD]; + uint32_t presence; + bool favorite; +} dm_social_friend; +uint32_t dm_nextendo_social_friends(dm_social_friend **output, size_t *count); +uint32_t dm_nextendo_social_friends_refresh(dm_social_friend **output, size_t *count); +bool dm_nextendo_api_baas_namespace(const char *kind); +uint32_t dm_nextendo_friends_list(int *count,void *output,const void *uid,int offset,int capacity,const void *filter,bool ids_only); +uint32_t dm_nextendo_friends_update(void *output,const void *uid,const uint64_t *ids,int count); +uint32_t dm_nextendo_friends_ensure(const void *uid); +uint32_t dm_nextendo_friends_available(uint8_t *available,const void *uid); +uint32_t dm_nextendo_presence_initialize(void *object,const void *uid); +uint32_t dm_nextendo_presence_commit(const void *object); +uint32_t dm_nextendo_presence_describe(void *object, const char *description); // UserPresence::SetDescription: the SDK's own code with Nextendo on, else a failure +uint32_t dm_nextendo_social_publish(unsigned status,const uint8_t *app_field,size_t size); // queues the presence and returns (hle_nextendo_social_apple.m sends it) +#ifdef DM_NEXTENDO_API_TEST +void dm_nextendo_social_flush(void); // waits for the presence sends queued so far +#endif diff --git a/dm/host/nextendo_x509.h b/dm/host/nextendo_x509.h new file mode 100644 index 0000000000..f56f7ad77c --- /dev/null +++ b/dm/host/nextendo_x509.h @@ -0,0 +1,13 @@ +// Strict private-PKI verification for an explicitly configured Nextendo route. +// No default trust store, user credentials, clock override or permissive callback. +#pragma once +#include +#include +#include +bool dm_nextendo_x509_available(void); +bool dm_nextendo_x509_verify(const char *hostname, const uint8_t *anchor, size_t anchor_size, + const uint8_t *const *chain, const size_t *sizes, size_t count); +// Explicitly enrolled self-signed leaf identity for one exact service route. +// No peer certificate is adopted automatically; DER must equal the enrolled pin. +bool dm_nextendo_x509_verify_pin(const char *hostname, const uint8_t *pin, size_t pin_size, + const uint8_t *leaf, size_t leaf_size); diff --git a/dm/host/nsd.h b/dm/host/nsd.h new file mode 100644 index 0000000000..c50080824f --- /dev/null +++ b/dm/host/nsd.h @@ -0,0 +1,6 @@ +// Horizon retail service-name expansion. This is separate from socket DNS and +// from the explicit provider routing/trust policy. +#pragma once +#include +enum { DM_NSD_FQDN_CAPACITY = 0x100, DM_NSD_FAIL = 0x2a2 }; +uint32_t dm_nsd_resolve(void *output, const void *input); diff --git a/dm/host/ssl_backend.h b/dm/host/ssl_backend.h new file mode 100644 index 0000000000..c2a0a8131f --- /dev/null +++ b/dm/host/ssl_backend.h @@ -0,0 +1,59 @@ +// Client TLS adapter. Guest objects are registry keys; no guessed SDK object fields are written. +#pragma once +#include +#include +#include + +enum { DM_SSL_OK = 0, DM_SSL_FAIL = 0x2a2, DM_SSL_BAD_POINTER = 0xe27b, + DM_SSL_NO_SOCKET = 0xce7b, DM_SSL_BAD_SOCKET = 0xd47b, + DM_SSL_WOULD_BLOCK = 0x1987b, DM_SSL_TIMEOUT = 0x19a7b }; +typedef bool (*dm_ssl_peer_policy_provider)(const char *guest_host, char *tls_host, size_t host_cap, + const uint8_t **ca_der, size_t *ca_size); +// Set before guest startup. A provider returns true only for its explicit host whitelist; +// its DER bytes remain immutable for the duration of the callback (the adapter copies them). +void dm_ssl_set_peer_policy(dm_ssl_peer_policy_provider provider); +// Separate, explicit exact-service certificate enrollment. This must never be +// installed as a catch-all or populated automatically from the current peer. +void dm_ssl_set_peer_pin_policy(dm_ssl_peer_policy_provider provider); +// Optional exact-host admission guard. Install before startup; NULL retains the +// adapter's normal strict certificate/hostname validation without routing policy. +void dm_ssl_set_peer_guard(bool (*guard)(const char *guest_host)); +// Optional stand-in for the player's firmware certificate store. With no store, a built-in certificate request is answered with this one CA, under each ID +// asked for: the online service's own CA, which hle_nextendo_routes.c gives in Nextendo mode from its checked service profile. NULL or false: no stand-in, +// the request fails as before. A game whose own TLS takes its roots from the store (gRPC) then needs no file from the player. The DER stays valid for the process +void dm_ssl_set_builtin_fallback(bool (*provider)(const uint8_t **ca_der, size_t *ca_size)); +uint32_t dm_ssl_initialize(unsigned concurrency); +uint32_t dm_ssl_finalize(void); +uint32_t dm_ssl_context_create(void *object, unsigned version); +uint32_t dm_ssl_context_destroy(void *object); +uint32_t dm_ssl_context_id(void *object, uint64_t *out); +uint32_t dm_ssl_import_server(void *object, uint64_t *id, const void *bytes, unsigned size, int format); +uint32_t dm_ssl_import_client(void *object, uint64_t *id, const void *bytes, const char *password, unsigned size, unsigned password_size); +uint32_t dm_ssl_remove_pki(void *object, uint64_t id); +uint32_t dm_ssl_connection_create(void *object, void *context); +uint32_t dm_ssl_connection_destroy(void *object); +uint32_t dm_ssl_connection_id(void *object, uint64_t *out, bool context); +uint32_t dm_ssl_set_socket(void *object, int socket); +uint32_t dm_ssl_get_socket(void *object, int *out); +uint32_t dm_ssl_set_hostname(void *object, const char *name, unsigned size); +uint32_t dm_ssl_get_hostname(void *object, char *out, unsigned *size, unsigned capacity); +enum { DM_SSL_IO_MODE, DM_SSL_VERIFY_OPTIONS, DM_SSL_SESSION_CACHE, DM_SSL_IO_TIMEOUT }; +uint32_t dm_ssl_set_value(void *object, int property, unsigned value); +uint32_t dm_ssl_get_value(void *object, int property, unsigned *out); +uint32_t dm_ssl_set_option(void *object, int option, unsigned value); +uint32_t dm_ssl_get_option(void *object, void *out_bool, int option); +uint32_t dm_ssl_handshake(void *object); +uint32_t dm_ssl_handshake_certs(void *object, unsigned *size, unsigned *count, void *buffer, unsigned capacity, bool registered_buffer); +uint32_t dm_ssl_set_cert_buffer(void *object, void *buffer, unsigned capacity); +uint32_t dm_ssl_needed_cert_size(void *object, unsigned *out); +uint32_t dm_ssl_cipher_info(void *object, void *out); +uint32_t dm_ssl_read(void *object, void *buffer, int *out, unsigned capacity, bool peek); +uint32_t dm_ssl_write(void *object, const void *buffer, int *out, unsigned size); +uint32_t dm_ssl_pending(void *object, int *out); +uint32_t dm_ssl_poll(void *object, unsigned *out, const unsigned *events, unsigned timeout_ms); +uint32_t dm_ssl_last_error(void *object, uint32_t *out, bool verify); +uint32_t dm_ssl_set_alpn(void *object, const uint8_t *data, unsigned size); +uint32_t dm_ssl_get_alpn(void *object, unsigned *state, uint8_t *buffer, unsigned *size, unsigned capacity); +uint32_t dm_ssl_cert_detail(void *out, const void *buffer, unsigned index); +uint32_t dm_ssl_builtin_size(unsigned *out, const uint32_t *ids, unsigned count); +uint32_t dm_ssl_builtin_certificates(void **out, uint8_t *buffer, unsigned capacity, const uint32_t *ids, unsigned count); diff --git a/dm/host/ssl_trace.h b/dm/host/ssl_trace.h new file mode 100644 index 0000000000..e64edf4921 --- /dev/null +++ b/dm/host/ssl_trace.h @@ -0,0 +1,40 @@ +// Opt-in, bounded TLS state metadata. Never pass names, pointers or stream data. +#pragma once +#include +#include +#include +#include +#include +#include + +typedef enum { + DM_TLS_HOSTNAME, DM_TLS_SOCKET, DM_TLS_VALUE, DM_TLS_OPTION, + DM_TLS_PREPARE, DM_TLS_VERIFY, DM_TLS_HANDSHAKE, DM_TLS_CERTIFICATES, + DM_TLS_READ, DM_TLS_WRITE +} dm_tls_stage; + +enum { DM_TLS_VERIFY_PLATFORM_TRUST = 1, DM_TLS_VERIFY_STRICT_X509 }; + +static inline void dm_tls_trace(dm_tls_stage stage, uint64_t session, uint32_t result, + int32_t native, uint64_t detail, unsigned flags) { + int saved = errno; + const char *flag = getenv("DM_SSL_TRACE"); + static _Atomic unsigned events; + if (flag && !strcmp(flag, "1")) { + unsigned used = atomic_load(&events); + while (used < 128) { + if (atomic_compare_exchange_weak(&events, &used, used + 1)) { + const char *reason = ""; + if (stage == DM_TLS_VERIFY && result) { + if (detail == DM_TLS_VERIFY_PLATFORM_TRUST) reason = " verify=platform-trust"; + else if (detail == DM_TLS_VERIFY_STRICT_X509) reason = " verify=strict-x509"; + } + fprintf(stderr, "[ssl-trace] stage=%u session=%" PRIu64 " result=0x%08" PRIx32 + " native=%" PRId32 " detail=%" PRIu64 " flags=0x%02x%s\n", + (unsigned)stage, session, result, native, detail, flags, reason); + break; + } + } + } + errno = saved; +} diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile index e1bc077f4c..704b7bdd92 100644 --- a/dm/host/tests/Makefile +++ b/dm/host/tests/Makefile @@ -12,6 +12,33 @@ QUIET = $(if $(findstring -fsanitize,$(SAN)),,2>/dev/null) GINC = $(if $(strip $(GAME)),-I../gen/$(GAME) -I../../games/$(GAME),$(error GAME is not set: make GAME=: $(shell python3 ../../games/game.py list | awk -F'\t' '{printf "%s (%s) ", $$1, $$3}'))) $(B)/t_fs $(B)/t_fs_case $(B)/t_fs_commit_list $(B)/t_fs_commit_list_tsan: ../romfs_image.h GAME_H = ../gen/$(GAME)/game_profile.h +.PHONY: bcat bcat-sanitize bcat-fixtures bcat-launch bcat-tools +# The optional static crypto prefix belongs to the online-provider series. A +# standalone source fixture supplies its reviewed prefix explicitly; this +# Makefile does not download or build a second cryptography dependency. +BCAT_CRYPTO_FLAGS = -DDM_OPENSSL_X509 "-I$(DM_OPENSSL_ROOT)/include" +BCAT_CRYPTO_LIB = "$(DM_OPENSSL_ROOT)/lib/libcrypto.a" +BCAT_WARN = -O1 -g -Wall -Wextra -Werror -Wno-unused-function -Wno-unused-parameter -Wno-deprecated-declarations +$(B)/t_bcat_store: t_bcat_store.m ../hle_bcat_apple.m ../nextendo_bcat.h | $(B) + test -n "$(DM_OPENSSL_ROOT)" + $(CLANG) $(BCAT_WARN) -fobjc-arc $(BCAT_CRYPTO_FLAGS) -o $@ t_bcat_store.m $(BCAT_CRYPTO_LIB) -lz -framework Foundation +$(B)/t_bcat_sdk: t_bcat_sdk.c t_bcat_guest.S ../hle_bcat.c ../nextendo_bcat.h ../hle_bigstack.c $(GAME_H) | $(B) + $(CLANG) $(BCAT_WARN) $(GINC) -o $@ t_bcat_sdk.c t_bcat_guest.S ../hle_bigstack.c +$(B)/t_bcat_fs: t_bcat_fs.c t_bcat_fs_provider.c t_fs_stub.c ../hle_fs.c ../hle_account_users.c ../account_users.h ../nextendo_bcat.h ../hle_bigstack.c ../save_sync.c $(GAME_H) | $(B) + $(CLANG) $(BCAT_WARN) $(GINC) -o $@ t_bcat_fs.c t_bcat_fs_provider.c t_fs_stub.c ../hle_account_users.c ../hle_bigstack.c ../save_sync.c +$(B)/t_fs $(B)/t_fs_directory $(B)/t_fs_case $(B)/t_fs_commit_list $(B)/t_fs_commit_list_tsan $(B)/t_save_sync $(B)/t_bcat_fs: bcat_absent.h +bcat-fixtures: $(B)/t_bcat_store $(B)/t_bcat_sdk $(B)/t_bcat_fs + $(B)/t_bcat_store + $(PYTHON) test_bcat_zip.py $(abspath $(B))/t_bcat_store + $(B)/t_bcat_sdk + $(B)/t_bcat_fs +bcat-launch: + DM_OPENSSL_ROOT="$(DM_OPENSSL_ROOT)" $(PYTHON) test_bcat_launch.py +bcat-tools: + DM_OPENSSL_ROOT="$(DM_OPENSSL_ROOT)" $(PYTHON) -m unittest discover -s ../../tools/tests -p test_nextendo_bcat.py +bcat: bcat-fixtures bcat-launch bcat-tools +bcat-sanitize: + $(MAKE) B=build/bcat-asan SAN="-fsanitize=address,undefined -fno-omit-frame-pointer" bcat run: $(B)/t_mii $(B)/t_net_eventfd $(B)/t_language $(B)/t_motion $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_friends $(B)/t_fs $(B)/t_fs_commit_list $(B)/t_thread_leak $(B)/t_fs_case $(B)/t_audio $(B)/t_output_stream $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_crash_diag $(B)/t_condvar $(B)/t_condvar_old $(B)/t_pollwait $(B)/t_clockwait $(B)/t_pause $(B)/t_pause_stress $(B)/t_pctl $(B)/t_sf $(B)/t_audren_sv $(B)/t_time $(B)/t_shared_font $(B)/t_vorbis $(B)/t_vorbis_divides $(B)/t_hid $(B)/t_haptics $(B)/t_haptics_apple $(B)/t_cheats $(B)/t_pad_hid $(B)/t_switch2 $(B)/t_language $(B)/t_heap_size @@ -111,8 +138,8 @@ $(B)/t_gates: t_gates.c ../hle.c ../hle.h ../dm.h $(GAME_H) | $(B) gates: $(B)/t_gates $(B)/t_gates run: $(B)/t_server_environment -$(B)/t_server_environment: t_server_environment.c ../hle_offline.c ../hle_net.h ../hle.h ../dm.h $(GAME_H) | $(B) - $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_server_environment.c +$(B)/t_server_environment: t_server_environment.c t_net_off.c ../hle_offline.c ../hle_net.h ../hle.h ../dm.h $(GAME_H) | $(B) + $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_server_environment.c t_net_off.c .PHONY: server-environment server-environment: $(B)/t_server_environment $(B)/t_server_environment @@ -139,6 +166,12 @@ $(B)/t_system_event: t_system_event.c ../hle_thread.c ../hle_sdk16.c ../hle_misc .PHONY: system-event system-event: $(B)/t_system_event $(B)/t_system_event +$(B)/t_network_clock: t_network_clock.c ../hle_network_clock.c ../hle_thread.c ../hle.h ../dm.h $(GAME_H) | $(B) + $(CLANG) -O1 -g -Wall -Wextra -Werror -Wno-unused-function -Wno-frame-address -I.. $(GINC) -o $@ t_network_clock.c +.PHONY: network-clock +network-clock: $(B)/t_network_clock + $(B)/t_network_clock +run: network-clock $(B)/t_nro: t_nro.c ../loader.c ../hle_ro.c ../hle.h ../dm.h $(GAME_H) | $(B) $(CLANG) -O1 -g -Wall -Wno-unused-function -Wno-deprecated-declarations -I.. $(GINC) -o $@ t_nro.c .PHONY: nro @@ -271,11 +304,11 @@ $(B)/t_altstack: t_altstack.c t_altstack_stub.c ../crash.c ../dm.h $(GAME_H) | $ $(CLANG) -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_altstack.c t_altstack_stub.c ../crash.c $(B)/t_crash_diag: t_crash_diag.m t_altstack_stub.c ../crash.c ../memstat.m ../dm.h $(GAME_H) | $(B) $(CLANG) -O1 -fobjc-arc -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_crash_diag.m t_altstack_stub.c ../crash.c ../memstat.m -framework Foundation -framework Metal -$(B)/t_net_eventfd: t_net_eventfd.c ../hle_net.c ../hle_net.h ../hle.h ../dm.h $(GAME_H) | $(B) - $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function $(if $(findstring -fsanitize,$(SAN)),,-fsanitize=address,undefined) -I.. $(GINC) -o $@ t_net_eventfd.c +$(B)/t_net_eventfd: t_net_eventfd.c ../hle_net.c ../hle_net.h ../hle.h ../dm.h $(NET_SOURCES) $(NET_HEADERS) $(GAME_H) | $(B) + $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function $(if $(findstring -fsanitize,$(SAN)),,-fsanitize=address,undefined) -I.. $(GINC) -o $@ t_net_eventfd.c $(NET_SOURCES) run: $(B)/t_net_loopback -$(B)/t_net_loopback: t_net_loopback.c ../hle_net.c ../hle_net.h ../hle.h ../dm.h $(GAME_H) | $(B) - $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function $(if $(findstring -fsanitize,$(SAN)),,-fsanitize=address,undefined) -I.. $(GINC) -o $@ t_net_loopback.c +$(B)/t_net_loopback: t_net_loopback.c ../hle_net.c ../hle_net.h ../hle.h ../dm.h $(NET_SOURCES) $(NET_HEADERS) $(GAME_H) | $(B) + $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function $(if $(findstring -fsanitize,$(SAN)),,-fsanitize=address,undefined) -I.. $(GINC) -o $@ t_net_loopback.c $(NET_SOURCES) $(B)/t_pctl: t_pctl.c ../hle_misc.c ../hle.h ../dm.h $(GAME_H) | $(B) $(CLANG) -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_pctl.c @@ -314,14 +347,14 @@ run: $(B)/t_pad_apple $(B)/t_pad_apple: t_pad_apple.m ../pad_apple.h ../dm_input.h | $(B) $(CLANG) -O1 -g -fobjc-arc -Wall -Werror -I.. -o $@ t_pad_apple.m -framework Foundation -framework GameController run: $(B)/t_account -$(B)/t_account: t_account.c ../hle_account.c ../hle_account_users.c ../account_users.h ../front.h ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) | $(B) - $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function $(GINC) -o $@ t_account.c ../hle_account_users.c ../hle_bigstack.c +$(B)/t_account: t_account.c t_nextendo_off.c ../hle_account.c ../hle_account_users.c ../account_users.h ../front.h ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) | $(B) + $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function $(GINC) -o $@ t_account.c t_nextendo_off.c ../hle_account_users.c ../hle_bigstack.c run: account-saves .PHONY: account-saves account-saves: $(B)/t_account_save $(B)/t_account_save -$(B)/t_account_save: t_account_save.c t_fs_stub.c ../hle_account.c ../hle_account_users.c ../account_users.h ../hle_fs.c ../hle_bigstack.c ../save_sync.c ../hle.h ../front.h $(GAME_H) | $(B) - $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_account_save.c t_fs_stub.c ../hle_account_users.c ../hle_bigstack.c ../save_sync.c +$(B)/t_account_save: t_account_save.c t_fs_stub.c t_nextendo_off.c ../hle_account.c ../hle_account_users.c ../account_users.h ../hle_fs.c ../hle_bigstack.c ../save_sync.c ../hle.h ../front.h $(GAME_H) | $(B) + $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_account_save.c t_fs_stub.c t_nextendo_off.c ../hle_account_users.c ../hle_bigstack.c ../save_sync.c run: $(B)/t_home_quit $(B)/t_home_quit_mac $(B)/t_home_quit: t_home_quit.c ../home_quit.h | $(B) $(CLANG) -O1 -g -Wall -Werror -I.. -o $@ t_home_quit.c @@ -355,8 +388,8 @@ $(B)/t_time: t_time.c ../hle_time.c ../hle_table.c ../hle.h ../dm.h $(GAME_H) | $(CLANG) -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_time.c ../hle_table.c $(B)/t_oe: t_oe.c ../hle_oe.c ../hle.h ../dm.h $(GAME_H) | $(B) $(CLANG) -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_oe.c -$(B)/t_friends: t_friends.c ../hle_friends.c ../hle.h ../dm.h $(GAME_H) | $(B) - $(CLANG) -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_friends.c +$(B)/t_friends: t_friends.c t_nextendo_off.c ../hle_friends.c ../hle.h ../dm.h $(GAME_H) | $(B) + $(CLANG) -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_friends.c t_nextendo_off.c $(B)/t_condvar: t_condvar.c t_condvar_stub.c ../hle_thread.c ../dm.h $(GAME_H) | $(B) $(CLANG) -O1 -Wno-unused-function -DDM_TEST_HOOKS -I.. $(GINC) -o $@ t_condvar.c t_condvar_stub.c ../hle_thread.c $(B)/t_condvar_old: t_condvar.c t_condvar_stub.c ../hle_thread.c ../dm.h $(GAME_H) | $(B) @@ -541,5 +574,172 @@ coverage: rm -rf $(B)/cov/prof LLVM_PROFILE_FILE="$(call cov_profile,$(B)/cov)" $(MAKE) -i B=$(B)/cov SAN="$(COV_FLAGS)" run @$(call cov_export,$(B)/cov) + +# Local transport fixtures use only synthetic packets and loopback peers. +NET_SOURCES = ../hle_net_backend.c ../hle_nsd_backend.c t_net_write_stub.c +NET_HEADERS = ../nsd.h ../net_socket.h ../net_discovery.h ../net_discovery_queue.inc ../discovery_protocol.h +NET_FLAGS = -O1 -g -Wall -Wextra -Werror -Wno-unused-function +$(B)/t_hle_wait: t_hle_wait.c t_hle_wait.S ../hle.h ../entry.S ../hle_bigstack.c $(GAME_H) | $(B) + $(CLANG) $(NET_FLAGS) $(GINC) -o $@ t_hle_wait.c t_hle_wait.S ../entry.S ../hle_bigstack.c +$(B)/t_net: t_net.c ../hle_net.c ../hle_offline.c ../hle.h ../entry.S ../hle_bigstack.c $(NET_SOURCES) $(NET_HEADERS) $(GAME_H) | $(B) + $(CLANG) $(NET_FLAGS) $(GINC) -o $@ t_net.c ../hle_net.c ../hle_offline.c $(NET_SOURCES) ../entry.S ../hle_bigstack.c +$(B)/t_net_discovery: t_net_discovery.c $(NET_SOURCES) $(NET_HEADERS) | $(B) + $(CLANG) $(NET_FLAGS) -DDM_NET_TEST -o $@ t_net_discovery.c $(NET_SOURCES) +$(B)/t_discovery_protocol: t_discovery_protocol.c ../discovery_protocol.h | $(B) + $(CLANG) -std=c11 -O2 -Wall -Wextra -Werror -pedantic -o $@ t_discovery_protocol.c +LDN_SOURCES = ../hle_ldn.c ../hle_ldn_protocol.c +LDN_HEADERS = ../hle_ldn.h $(NET_HEADERS) +$(B)/t_ldn: t_ldn.c $(LDN_SOURCES) $(LDN_HEADERS) $(NET_SOURCES) | $(B) + $(CLANG) $(NET_FLAGS) -DDM_NET_TEST -DDM_LDN_TEST -DDM_LDN_NET_TEST -o $@ t_ldn.c $(LDN_SOURCES) $(NET_SOURCES) +$(B)/t_ldn_events: t_ldn_events.c ../hle_ldn.c ../hle_ldn_protocol.c ../hle_ldn.h $(GAME_H) | $(B) + $(CLANG) $(NET_FLAGS) $(GINC) -o $@ t_ldn_events.c ../hle_ldn_protocol.c +.PHONY: local-network-tests +local-network-tests: $(B)/t_hle_wait $(B)/t_net $(B)/t_net_discovery $(B)/t_discovery_protocol $(B)/t_ldn $(B)/t_ldn_events + $(B)/t_hle_wait + $(B)/t_oe_handoff + $(B)/t_net --no-broadcast + $(B)/t_net_discovery + $(B)/t_discovery_protocol + $(B)/t_ldn + $(B)/t_ldn_events + $(B)/t_friends_history +run: local-network-tests + +$(B)/t_friends_history: t_friends_history.c ../hle_friends_history.c ../friends_history.h ../hle_friends.c ../account_local.h memory_profile/game_profile.h | $(B) + $(CLANG) $(NET_FLAGS) -DDM_FRIENDS_HISTORY_TEST -Imemory_profile -o $@ t_friends_history.c ../hle_friends_history.c +local-network-tests: $(B)/t_friends_history + +$(B)/t_oe_handoff: t_oe_handoff.c t_condvar_stub.c ../hle_thread.c ../hle_oe.c ../hle.h ../dm.h $(GAME_H) | $(B) + $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_oe_handoff.c t_condvar_stub.c +local-network-tests: $(B)/t_oe_handoff + +# A kernel socket receive must prepare tracked guest pages, including after waits. +$(B)/t_net_write_prepare: t_net_write_prepare.c ../hle_net_backend.c ../hle_nsd_backend.c ../nsd.h ../net_socket.h ../net_discovery.h ../net_discovery_queue.inc ../discovery_protocol.h ../../gfx/nvn/nvn_dirty.c ../../gfx/nvn/nvn_dirty.h $(GAME_H) | $(B) + $(CLANG) $(NET_FLAGS) $(GINC) -o $@ t_net_write_prepare.c ../hle_nsd_backend.c ../../gfx/nvn/nvn_dirty.c +.PHONY: net-write net-write-sanitize +net-write: $(B)/t_net_write_prepare + $(B)/t_net_write_prepare +net-write-sanitize: + $(call san_fresh,build/net-write-asan,$(ASAN_FLAGS)) + $(ASAN_ENV) $(MAKE) B=build/net-write-asan SAN="$(ASAN_FLAGS)" net-write +run: net-write + +# Original synthetic DNSService callbacks exercise ownership/cancellation offline. +$(B)/t_resolver_cancel: t_resolver_cancel.c t_net_write_stub.c ../hle_net_backend.c ../hle_nsd_backend.c ../net_socket.h ../nsd.h | $(B) + $(CLANG) -O1 -g -Wall -Wextra -Werror -Wno-unused-function -o $@ t_resolver_cancel.c t_net_write_stub.c ../hle_nsd_backend.c +.PHONY: resolver +resolver: $(B)/t_resolver_cancel + $(B)/t_resolver_cancel +run: resolver +# Optional system API smoke uses only localhost and is not part of CI. +$(B)/t_resolver_live: t_resolver_live.c $(NET_SOURCES) $(NET_HEADERS) | $(B) + $(CLANG) -O1 -g -Wall -Wextra -Werror -o $@ t_resolver_live.c $(NET_SOURCES) +.PHONY: resolver-live +resolver-live: $(B)/t_resolver_live + $(B)/t_resolver_live +# Native TLS and explicit provider policy; all certificates are ephemeral fixtures. +DM_OPENSSL_ROOT ?= $(shell python3 ../../tools/apple_crypto.py macos) +PRIVATE_PKI_FLAGS = -DDM_OPENSSL_X509 "-I$(DM_OPENSSL_ROOT)/include" +PRIVATE_PKI_LIB = "$(DM_OPENSSL_ROOT)/lib/libcrypto.a" +OPENSSL_TOOL ?= $(shell command -v openssl) +SSL_SOURCES = t_ssl.m t_net_write_stub.c ../hle_ssl.c ../hle_ssl_apple.m ../hle_nextendo_x509.c ../hle_net_backend.c ../hle_nsd_backend.c ../hle_bigstack.c ../entry.S +SSL_DEPS = t_gate_fixture.h ../nsd.h $(SSL_SOURCES) ../ssl_backend.h ../net_socket.h ../hle.h $(GAME_H) test_ssl_transport.py +SSL_FLAGS = -O1 -g -fobjc-arc -mmacosx-version-min=14.0 -Wall -Wextra -Werror -Wno-unused-function $(GINC) +$(B)/t_ssl $(B)/t_ssl_asan $(B)/t_nextendo_routes $(B)/t_nextendo_routes_asan: ../ssl_trace.h +$(B)/t_ssl_trace: t_ssl_trace.c ../ssl_trace.h | $(B) + $(CLANG) -O1 -g -Wall -Wextra -Werror -o $@ t_ssl_trace.c +$(B)/t_ssl_trace_asan: t_ssl_trace.c ../ssl_trace.h | $(B) + $(CLANG) -O1 -g -Wall -Wextra -Werror -fsanitize=address,undefined -fno-omit-frame-pointer -o $@ t_ssl_trace.c +$(B)/t_ssl: $(SSL_DEPS) | $(B) + $(CLANG) $(SSL_FLAGS) -o $@ $(SSL_SOURCES) -framework Foundation -framework Security +$(B)/t_ssl_asan: $(SSL_DEPS) | $(B) + $(CLANG) $(SSL_FLAGS) -fsanitize=address,undefined -mllvm -asan-globals=0 -fno-omit-frame-pointer -o $@ $(SSL_SOURCES) -framework Foundation -framework Security +.PHONY: ssl ssl-sanitize +ssl: $(B)/t_ssl $(B)/t_ssl_trace + $(B)/t_ssl_trace + $(PYTHON) test_ssl_transport.py $(B)/t_ssl +ssl-sanitize: $(B)/t_ssl_asan $(B)/t_ssl_trace_asan + $(B)/t_ssl_trace_asan + $(PYTHON) test_ssl_transport.py $(B)/t_ssl_asan + +ROUTE_SOURCES = t_nextendo_routes.c t_net_write_stub.c ../hle_nextendo_routes.c ../hle_net_backend.c ../hle_nsd_backend.c ../hle_ssl_apple.m ../hle_nextendo_x509.c +ROUTE_DEPS = ../nsd.h $(ROUTE_SOURCES) ../nextendo_routes.h ../net_socket.h ../ssl_backend.h test_nextendo_routes.py test_ssl_transport.py Makefile +$(B)/t_nextendo_routes: $(ROUTE_DEPS) | $(B) + $(CLANG) -O1 -g -fobjc-arc -mmacosx-version-min=14.0 -Wall -Wextra -Werror $(PRIVATE_PKI_FLAGS) -o $@ $(ROUTE_SOURCES) $(PRIVATE_PKI_LIB) -framework Foundation -framework Security +$(B)/t_nextendo_routes_asan: $(ROUTE_DEPS) | $(B) + $(CLANG) -O1 -g -fobjc-arc -mmacosx-version-min=14.0 -Wall -Wextra -Werror $(PRIVATE_PKI_FLAGS) -fsanitize=address,undefined -fno-omit-frame-pointer -o $@ $(ROUTE_SOURCES) $(PRIVATE_PKI_LIB) -framework Foundation -framework Security +.PHONY: nextendo-routes nextendo-routes-sanitize +nextendo-routes: $(B)/t_nextendo_routes + $(PYTHON) test_nextendo_routes.py $(B)/t_nextendo_routes +nextendo-routes-sanitize: $(B)/t_nextendo_routes_asan + $(PYTHON) test_nextendo_routes.py $(B)/t_nextendo_routes_asan + +$(B)/t_nextendo_x509: t_nextendo_x509.c ../hle_nextendo_x509.c ../nextendo_x509.h | $(B) + $(CLANG) -O1 -g -Wall -Wextra -Werror $(PRIVATE_PKI_FLAGS) -o $@ t_nextendo_x509.c ../hle_nextendo_x509.c $(PRIVATE_PKI_LIB) +$(B)/t_nextendo_x509_asan: t_nextendo_x509.c ../hle_nextendo_x509.c ../nextendo_x509.h | $(B) + $(CLANG) -O1 -g -Wall -Wextra -Werror $(PRIVATE_PKI_FLAGS) -fsanitize=address,undefined -fno-omit-frame-pointer -o $@ t_nextendo_x509.c ../hle_nextendo_x509.c $(PRIVATE_PKI_LIB) +.PHONY: nextendo-x509 nextendo-x509-sanitize +nextendo-x509: $(B)/t_nextendo_x509 + $(PYTHON) test_nextendo_x509.py $(B)/t_nextendo_x509 "$(OPENSSL_TOOL)" +nextendo-x509-sanitize: $(B)/t_nextendo_x509_asan + $(PYTHON) test_nextendo_x509.py $(B)/t_nextendo_x509_asan "$(OPENSSL_TOOL)" + +$(B)/t_nsd: t_nsd.c ../hle_nsd_backend.c ../nsd.h ../net_socket.h | $(B) + $(CLANG) -O1 -g -Wall -Wextra -Werror -o $@ t_nsd.c ../hle_nsd_backend.c +$(B)/t_nsd_asan: t_nsd.c ../hle_nsd_backend.c ../nsd.h ../net_socket.h | $(B) + $(CLANG) -O1 -g -Wall -Wextra -Werror -fsanitize=address,undefined -fno-omit-frame-pointer -o $@ t_nsd.c ../hle_nsd_backend.c +.PHONY: nsd nsd-sanitize +nsd: $(B)/t_nsd + $(B)/t_nsd +nsd-sanitize: $(B)/t_nsd_asan + $(B)/t_nsd_asan +run: ssl nextendo-routes nextendo-x509 nsd + +ACCOUNT_SOURCES = t_nextendo_account.m ../hle_account.c ../hle_account_users.c ../hle_nextendo_apple.m ../hle_nextendo_api_apple.m ../hle_bigstack.c ../entry.S +ACCOUNT_DEPS = t_gate_fixture.h ../nextendo_login_apple.inc $(ACCOUNT_SOURCES) ../nextendo_account.h ../net_socket.h ../hle.h $(GAME_H) +$(B)/t_nextendo_account: $(ACCOUNT_DEPS) | $(B) + $(CLANG) $(SSL_FLAGS) -o $@ $(ACCOUNT_SOURCES) -framework Foundation -framework Security +$(B)/t_nextendo_account_asan: $(ACCOUNT_DEPS) | $(B) + $(CLANG) $(SSL_FLAGS) -fsanitize=address,undefined -mllvm -asan-globals=0 -fno-omit-frame-pointer -o $@ $(ACCOUNT_SOURCES) -framework Foundation -framework Security +.PHONY: nextendo-account nextendo-account-sanitize +# The Mac sign-in tool (dm/tools/nextendo_login.m) is built with the account fixtures, so CI compiles it; it signs in only when run by hand +$(B)/nextendo_login: ../../tools/nextendo_login.m ../nextendo_login_apple.inc | $(B) + $(CLANG) -O1 -g -fobjc-arc -Wall -Wextra -Werror -o $@ ../../tools/nextendo_login.m -framework Foundation -framework Security -framework AppKit +nextendo-account: $(B)/t_nextendo_account $(B)/nextendo_login + $(B)/t_nextendo_account +nextendo-account-sanitize: $(B)/t_nextendo_account_asan $(B)/nextendo_login + $(B)/t_nextendo_account_asan +API_SOURCES = t_nextendo_api.m ../hle_nextendo_api_apple.m +$(B)/t_nextendo_api: $(API_SOURCES) ../nextendo_api_apple.h | $(B) + $(CLANG) -O1 -g -fobjc-arc -Wall -Wextra -Werror -DDM_NEXTENDO_API_TEST -o $@ $(API_SOURCES) -framework Foundation +$(B)/t_nextendo_api_asan: $(API_SOURCES) ../nextendo_api_apple.h | $(B) + $(CLANG) -O1 -g -fobjc-arc -Wall -Wextra -Werror -DDM_NEXTENDO_API_TEST -fsanitize=address,undefined -fno-omit-frame-pointer -o $@ $(API_SOURCES) -framework Foundation +.PHONY: nextendo-api nextendo-api-sanitize +nextendo-api: $(B)/t_nextendo_api + $(B)/t_nextendo_api +nextendo-api-sanitize: $(B)/t_nextendo_api_asan + $(B)/t_nextendo_api_asan + +SOCIAL_SOURCES = t_nextendo_social.m ../hle_nextendo_social_apple.m ../hle_nextendo_api_apple.m ../hle_nextendo_friends.c +$(B)/t_nextendo_social: $(SOCIAL_SOURCES) ../nextendo_social.h ../nextendo_api_apple.h | $(B) + $(CLANG) -O1 -g -fobjc-arc -Wall -Wextra -Werror -DDM_NEXTENDO_API_TEST -Isocial_profile -o $@ $(SOCIAL_SOURCES) -framework Foundation +$(B)/t_nextendo_social_asan: $(SOCIAL_SOURCES) ../nextendo_social.h ../nextendo_api_apple.h | $(B) + $(CLANG) -O1 -g -fobjc-arc -Wall -Wextra -Werror -DDM_NEXTENDO_API_TEST -Isocial_profile -fsanitize=address,undefined -fno-omit-frame-pointer -o $@ $(SOCIAL_SOURCES) -framework Foundation +.PHONY: nextendo-social nextendo-social-sanitize +nextendo-social: $(B)/t_nextendo_social + $(B)/t_nextendo_social +nextendo-social-sanitize: $(B)/t_nextendo_social_asan + $(B)/t_nextendo_social_asan +run: nextendo-account nextendo-api nextendo-social +$(B)/t_online_policy: t_online_policy.c t_net_write_stub.c ../hle_net_backend.c ../hle_nsd_backend.c ../net_socket.h ../nsd.h | $(B) + $(CLANG) -O1 -g -Wall -Wextra -Werror -o $@ t_online_policy.c t_net_write_stub.c ../hle_net_backend.c ../hle_nsd_backend.c +$(B)/t_online_policy_asan: t_online_policy.c t_net_write_stub.c ../hle_net_backend.c ../hle_nsd_backend.c ../net_socket.h ../nsd.h | $(B) + $(CLANG) -O1 -g -Wall -Wextra -Werror -fsanitize=address,undefined -fno-omit-frame-pointer -o $@ t_online_policy.c t_net_write_stub.c ../hle_net_backend.c ../hle_nsd_backend.c +.PHONY: online-policy online-policy-sanitize +online-policy: $(B)/t_online_policy + $(B)/t_online_policy +online-policy-sanitize: $(B)/t_online_policy_asan + $(B)/t_online_policy_asan +run: online-policy # loader.c includes the frame step's header (FSTEP_UNIT_OFF, nvn_fstep_target_put) $(B)/t_symbols $(B)/t_nro: ../../gfx/nvn/nvn_fstep.h diff --git a/dm/host/tests/bcat_absent.h b/dm/host/tests/bcat_absent.h new file mode 100644 index 0000000000..8ac16ce3b4 --- /dev/null +++ b/dm/host/tests/bcat_absent.h @@ -0,0 +1,10 @@ +// Source-only filesystem fixtures have no calendar store. Explicit definitions +// also satisfy sanitizer-generated references to weak-imported functions. +// A fixture linking a real provider overrides these weak definitions normally. +#ifndef DM_TEST_BCAT_ABSENT_H +#define DM_TEST_BCAT_ABSENT_H +#include +__attribute__((weak)) const char *dm_bcat_overlay(void) { return NULL; } +__attribute__((weak)) const char *dm_bcat_delivery(void) { return NULL; } +__attribute__((weak)) int dm_bcat_copy_delivery(char *out, size_t size) { (void)out; (void)size; return 0; } +#endif diff --git a/dm/host/tests/social_profile/game_profile.h b/dm/host/tests/social_profile/game_profile.h new file mode 100644 index 0000000000..8719caaf63 --- /dev/null +++ b/dm/host/tests/social_profile/game_profile.h @@ -0,0 +1,3 @@ +// Synthetic profile identity for social adapter tests. +#include "../memory_profile/game_profile.h" +#define DM_GAME_ID "0100152000022000" diff --git a/dm/host/tests/t_account.c b/dm/host/tests/t_account.c index b826f60b80..a14a324a24 100644 --- a/dm/host/tests/t_account.c +++ b/dm/host/tests/t_account.c @@ -40,6 +40,13 @@ int main(int argc, char **argv) { assert(h_acc_Exists(&exists, &u2) == RES_OK && exists); assert(h_acc_ListOpen(&n, list, 8) == RES_OK && n == 0); assert(h_acc_LastOpened(&out) == RES_OK && !memcmp(&out, &k_uid, 16)); + } else if (!strcmp(argv[1], "--picked")) { // the game shows the selector first and opens the chosen user 2 + UserHandle h1, h2; + assert(!dm_account_uid_exists(&k_uid) && !dm_account_copy_uid(&out)); // no active user before an open + assert(h_acc_OpenUser(&h2, &u2) == RES_OK && dm_account_uid_exists(&u2) && !dm_account_uid_exists(&k_uid)); + assert(h_acc_OpenPre(&h1) == RES_OK && dm_account_uid_exists(&u2) && !dm_account_uid_exists(&k_uid)); // a later open does not move it + h_acc_CloseUser(&h2); assert(dm_account_copy_uid(&out) && !memcmp(&out, &u2, 16)); // nor does closing it + uint8_t avail = 7; assert(h_acc_NsaAvail(&avail, &h1) == RES_OK && !avail); // another user has no network account } else if (!strcmp(argv[1], "--corrupt")) { assert(h_acc_ListAll(&n, list, 8) == RES_FAIL && n == 0); choice = FRONT_USER_CREATE; assert(h_acc_ShowCreator() == RES_FAIL && calls == 0); @@ -54,7 +61,9 @@ int main(int argc, char **argv) { snprintf(save, sizeof save, "%s/save", root); setenv("DM_SAVE", save, 1); Uid out, list[8]; UserHandle h, other; int n; assert(h_acc_ListOpen(&n, list, 8) == RES_OK && n == 0); + assert(!dm_account_uid_exists(&k_uid)); assert(h_acc_TryOpenPre(&h) && h_acc_OpenPre(&other) == RES_OK && h.v[2] != other.v[2]); + assert(dm_account_uid_exists(&k_uid)); // the launch user, opened first, is the active user assert(h_acc_ListOpen(&n, list, 8) == RES_OK && n == 1); h_acc_CloseUser(&h); h_acc_CloseUser(&h); assert(h_acc_ListOpen(&n, list, 8) == RES_OK && n == 1); @@ -88,7 +97,7 @@ int main(int argc, char **argv) { assert(h_acc_ListAll(&n, list, 8) == RES_OK && n == 2 && dm_uid_user(&list[1]) == 2); assert(h_acc_OpenUser(&h, &u2) == RES_FAIL); assert(h_acc_OpenUser(&h, &u3) == RES_OK && h_acc_OpenUser(&other, &u3) == RES_OK); - assert(h_acc_LastOpened(&out) == RES_OK && !memcmp(&out, &u3, 16)); + assert(h_acc_LastOpened(&out) == RES_OK && !memcmp(&out, &u3, 16) && !dm_account_uid_exists(&u3) && dm_account_uid_exists(&k_uid)); assert(h_acc_EnsureNsa(&h) == 0x27c); // ResultCancelledByUser for an open local account h_acc_CloseUser(&h); h_acc_CloseUser(&h); assert(h_acc_ListOpen(&n, list, 8) == RES_OK && n == 1 && dm_uid_user(list) == 2); @@ -118,11 +127,12 @@ int main(int argc, char **argv) { for (int i = 0; i < 4; i++) assert(!pthread_join(threads[i], NULL)); assert(h_acc_ListOpen(&n, list, 8) == RES_OK && n == 0 && waiting == 0); child(argv[0], "--restart", save); + child(argv[0], "--picked", save); snprintf(path, sizeof path, "%s.users", save); FILE *f = fopen(path, "w"); assert(f); fputs("broken registry\n", f); fclose(f); child(argv[0], "--corrupt", save); unlink(path); snprintf(path, sizeof path, "%s/missing/save", root); child(argv[0], "--unwritable", path); rmdir(root); - puts("t_account: OK (selection, sessions, concurrent closes, fresh-process persistence)"); + puts("t_account: OK (selection, sessions, concurrent closes, fresh-process persistence, the active user)"); return 0; } diff --git a/dm/host/tests/t_bcat_fs.c b/dm/host/tests/t_bcat_fs.c new file mode 100644 index 0000000000..32db5baedb --- /dev/null +++ b/dm/host/tests/t_bcat_fs.c @@ -0,0 +1,18 @@ +#include "../hle_fs.c" +#include +struct dm_flags g_flag;uint64_t g_t0_ns;uint64_t now_ns(void){return 0;} +void dm_guest_write_prepare(void *p,size_t n){(void)p;(void)n;} +extern char bcat_fixture_overlay[1024],bcat_fixture_delivery[1024]; +static unsigned checks; +#define CHECK(c) do{checks++;if(!(c)){fprintf(stderr,"BCAT FS failed line%d: %s\n",__LINE__,#c);return 1;}}while(0) +static void put(const char *p,const char *s){FILE *f=fopen(p,"w");if(!f)abort();fwrite(s,1,strlen(s),f);fclose(f);} +int main(void){char root[]="/tmp/nx-bcat-fs-XXXXXX",base[1024],overlay[1024],delivery[1024],p[1200];CHECK(mkdtemp(root));snprintf(base,sizeof base,"%s/base",root);snprintf(overlay,sizeof overlay,"%s/overlay",root);snprintf(delivery,sizeof delivery,"%s/delivery",root);CHECK(!mkdir(base,0700)&&!mkdir(overlay,0700)&&!mkdir(delivery,0700));snprintf(p,sizeof p,"%s/base.txt",base);put(p,"base");snprintf(p,sizeof p,"%s/calendar.txt",overlay);put(p,"calendar");snprintf(p,sizeof p,"%s/event.txt",delivery);put(p,"event"); + CHECK(h_bcat_Mount()!=RES_OK);strlcpy(bcat_fixture_overlay,overlay,1024);strlcpy(bcat_fixture_delivery,delivery,1024);setenv("DM_ROMFS",base,1);CHECK(!h_fs_MountRom("content",NULL,0)); + uint64_t handle;size_t n;char bytes[16]={0};CHECK(!h_fs_OpenFile(&handle,"content:/calendar.txt",MODE_READ));CHECK(!h_fs_ReadFile(&n,handle,0,bytes,8)&&n==8&&!memcmp(bytes,"calendar",8));h_fs_CloseFile(handle); + CHECK(!h_fs_OpenFile(&handle,"content:/base.txt",MODE_READ));h_fs_CloseFile(handle); + CHECK(h_fs_OpenFile(&handle,"content:/calendar.txt",MODE_WRITE)!=0); + uint64_t dir;CHECK(!h_fs_OpenDirectory(&dir,"content:/",DIRMODE_FILE));DirectoryEntry entries[4];int64_t count;CHECK(!h_fs_ReadDirectory(&count,entries,dir,4)&&count==2);h_fs_CloseDirectory(dir); + CHECK(!h_bcat_Mount());CHECK(!h_fs_OpenFile(&handle,"bcat:/event.txt",MODE_READ));h_bcat_Unmount();uint64_t other;CHECK(h_fs_OpenFile(&other,"bcat:/event.txt",MODE_READ)!=0);CHECK(!h_fs_ReadFile(&n,handle,0,bytes,5)&&n==5&&!memcmp(bytes,"event",5));h_fs_CloseFile(handle); + CHECK(!h_bcat_Mount());CHECK(!h_fs_OpenFile(&handle,"bcat:/event.txt",MODE_READ));h_fs_CloseFile(handle);CHECK(h_fs_OpenFile(&handle,"bcat:/event.txt",MODE_WRITE)!=0);h_bcat_Unmount(); + for(const char **name=(const char *[]){"base/base.txt","overlay/calendar.txt","delivery/event.txt",NULL};*name;name++){snprintf(p,sizeof p,"%s/%s",root,*name);CHECK(!unlink(p));}CHECK(!rmdir(base)&&!rmdir(overlay)&&!rmdir(delivery)&&!rmdir(root));printf("BCAT RomFS merge/read-only mount/unmount: %u checks passed\n",checks);return 0; +} diff --git a/dm/host/tests/t_bcat_fs_provider.c b/dm/host/tests/t_bcat_fs_provider.c new file mode 100644 index 0000000000..3b1184654f --- /dev/null +++ b/dm/host/tests/t_bcat_fs_provider.c @@ -0,0 +1,6 @@ +#include +#include +char bcat_fixture_overlay[1024],bcat_fixture_delivery[1024]; +const char *dm_bcat_overlay(void){return bcat_fixture_overlay[0]?bcat_fixture_overlay:NULL;} +const char *dm_bcat_delivery(void){return bcat_fixture_delivery[0]?bcat_fixture_delivery:NULL;} +int dm_bcat_copy_delivery(char *out,size_t size){if(!bcat_fixture_delivery[0])return 0;return strlcpy(out,bcat_fixture_delivery,size) +#import +static NSString *fixtureRoot,*fixtureMode; +static unsigned requests,catalogRequests,archiveRequests,conditionals; +@interface DmBcatFixtureProtocol : NSURLProtocol @end +@implementation DmBcatFixtureProtocol ++(BOOL)canInitWithRequest:(NSURLRequest *)r{(void)r;return YES;} ++(NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)r{return r;} +-(void)startLoading{ + @synchronized(DmBcatFixtureProtocol.class){requests++;} + NSString *path=self.request.URL.path,*file=nil;NSInteger status=200;NSDictionary *headers=@{}; + if([path isEqual:@"/service-catalog/v1/game-catalog"]){ + @synchronized(DmBcatFixtureProtocol.class){catalogRequests++;} + if([fixtureMode isEqual:@"interrupt"]){[@"ready" writeToFile:[fixtureRoot stringByAppendingPathComponent:@"interrupt-ready"] atomically:YES encoding:NSUTF8StringEncoding error:nil];return;} + // The catalog uses part of the launch budget, then the archive stalls. + // A fresh per-request deadline would incorrectly add another 12 seconds. + if([fixtureMode isEqual:@"timeout"])[NSThread sleepForTimeInterval:4]; + if([fixtureMode isEqual:@"error"]){[self.client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotConnectToHost userInfo:nil]];return;} + file=[fixtureMode isEqual:@"invalid"]?@"invalid.json":@"catalog.json"; + }else if([path isEqual:@"/api/bcat/0100f8f0000a2000"]){ + @synchronized(DmBcatFixtureProtocol.class){archiveRequests++;if([self.request valueForHTTPHeaderField:@"If-None-Match"])conditionals++;} + if([fixtureMode isEqual:@"timeout"])return; + if([fixtureMode isEqual:@"304"]){status=304;headers=@{@"ETag":@"\"fixture-v1\""};} + else{file=[fixtureMode isEqual:@"corrupt"]?@"corrupt.zip":[fixtureMode isEqual:@"v2"]?@"v2.zip":@"v1.zip";if(![fixtureMode isEqual:@"noetag"])headers=@{@"ETag":[fixtureMode isEqual:@"v2"]?@"\"fixture-v2\"":@"\"fixture-v1\""};} + }else if([path hasSuffix:@"/System/GameConfigSetting.xml"])file=@"static.xml"; + else if([path hasSuffix:@"/dummy/dummy.txt"])file=@"dummy.txt"; + else{[self.client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorUnsupportedURL userInfo:nil]];return;} + NSData *data=file?[NSData dataWithContentsOfFile:[fixtureRoot stringByAppendingPathComponent:file]]:NSData.data; + if(!data)abort();NSHTTPURLResponse *r=[[NSHTTPURLResponse alloc]initWithURL:self.request.URL statusCode:status HTTPVersion:@"HTTP/1.1" headerFields:headers]; + [self.client URLProtocol:self didReceiveResponse:r cacheStoragePolicy:NSURLCacheStorageNotAllowed]; + [self.client URLProtocol:self didLoadData:data];[self.client URLProtocolDidFinishLoading:self]; +} +-(void)stopLoading{} +@end +@interface NSURLSessionConfiguration(DmBcatFixture) ++(instancetype)dm_bcat_fixture_configuration; +@end +@implementation NSURLSessionConfiguration(DmBcatFixture) ++(instancetype)dm_bcat_fixture_configuration{ + NSURLSessionConfiguration *c=[self dm_bcat_fixture_configuration];c.protocolClasses=@[DmBcatFixtureProtocol.class];return c; +} +@end +#ifndef DM_BCAT_RUNTIME_INCLUDE +#define DM_BCAT_RUNTIME_INCLUDE "../hle_bcat_apple.m" +#endif +// Exercise public startup without reading/writing the developer's real cache. +// Only this fixture substitutes the OS-supplied private home directory. +static NSString *fixtureHome(void){return [fixtureRoot stringByAppendingPathComponent:[@"home-" stringByAppendingString:fixtureMode]];} +#define NSHomeDirectory fixtureHome +#import DM_BCAT_RUNTIME_INCLUDE +#undef NSHomeDirectory + +int main(int argc,const char **argv){@autoreleasepool{ + if(argc!=4)return 2;fixtureRoot=@(argv[1]);fixtureMode=@(argv[2]);NSString *cache=@(argv[3]); + Method a=class_getClassMethod(NSURLSessionConfiguration.class,@selector(ephemeralSessionConfiguration)); + Method b=class_getClassMethod(NSURLSessionConfiguration.class,@selector(dm_bcat_fixture_configuration));method_exchangeImplementations(a,b); + BOOL gate=[fixtureMode hasPrefix:@"gate-"]; + activeCache=cache;activeVersion=gate?nil:@"5.5.2";startTitle=@"0100f8f0000a2000";startOnline=![fixtureMode isEqual:@"offline"]; + NSString *seed=[fixtureRoot stringByAppendingPathComponent:@"empty-seed"]; + uint64_t before=monotonicTime(); + if(gate){ + [NSFileManager.defaultManager createDirectoryAtPath:fixtureHome() withIntermediateDirectories:YES attributes:nil error:nil]; + NSString *profile=[fixtureRoot stringByAppendingPathComponent:[fixtureMode isEqual:@"gate-missing"]?@"missing-profile":[fixtureMode isEqual:@"gate-invalid"]?@"invalid-profile":@"valid-profile"]; + setenv("DM_NEXTENDO_BCAT_DIR",profile.fileSystemRepresentation,1); + const char *title=[fixtureMode isEqual:@"gate-unrelated"]?"0100152000022000":"0100f8f0000a2000"; + if([fixtureMode isEqual:@"gate-no-provider"]||[fixtureMode isEqual:@"gate-provider-online"])dm_bcat_pre_guest_start(fixtureRoot.fileSystemRepresentation,title); + else dm_bcat_start(fixtureRoot.fileSystemRepresentation,title,1); + }else selectAtLaunch(seed); + double elapsed=(monotonicTime()-before)/(double)NSEC_PER_SEC; + // This is the first calendar open; it must see the completed launch choice. + const char *overlay=dm_bcat_overlay();NSString *file=overlay?[@(overlay) stringByAppendingPathComponent:@"DebugUnderPilot/bcat/vsdata/VSSetting_0.byaml"]:nil; + NSData *first=file?boundedRead(file,1024):nil;unsigned char marker=first.length?((const unsigned char *)first.bytes)[first.length-1]:0; + unsigned deliveryMarker=0,overlayMarker=0,retainedMarker=0; + if([fixtureMode isEqual:@"runtime-refresh"]){ + int original=open(file.fileSystemRepresentation,O_RDONLY|O_CLOEXEC);if(original<0)abort(); + fixtureMode=@"v2";lastRefresh=0;if(!dm_bcat_request_sync())abort(); + uint64_t limit=monotonicTime()+5*NSEC_PER_SEC;unsigned result=1; + while(dm_bcat_sync_status(&result,NULL)!=9&&monotonicTime() +#include +#include +#include +#include +struct dm_flags g_flag;uint64_t g_t0_ns;uint64_t now_ns(void){return 0;} +static uintptr_t guest_begin,guest_end;static int guest_routes; +int dm_guest_as_contains(uintptr_t p){int guest=p>=guest_begin&&p +static unsigned checks; +#define CHECK(c) do{checks++;if(!(c)){fprintf(stderr,"BCAT assertion failed at %d: %s\n",__LINE__,#c);return 1;}}while(0) +static NSData *envelope(NSData *payload,EVP_PKEY *key){ + uint8_t signature[64];size_t length=sizeof signature;EVP_MD_CTX *ctx=EVP_MD_CTX_new(); + if(!ctx||EVP_DigestSignInit(ctx,NULL,NULL,NULL,key)!=1||EVP_DigestSign(ctx,signature,&length,payload.bytes,payload.length)!=1)abort();EVP_MD_CTX_free(ctx); + return jsonData(@{@"key_id":@"catalog-key-1",@"payload":[payload base64EncodedStringWithOptions:0],@"signature":[[NSData dataWithBytes:signature length:length] base64EncodedStringWithOptions:0]}); +} +int main(int argc,const char **argv){@autoreleasepool{ + if(argc==3){NSData *zip=boundedRead([NSString stringWithUTF8String:argv[1]],zipLimit+1);BOOL expected=atoi(argv[2])!=0;NSDictionary *files=unzip(zip,NULL);if((files!=nil)!=expected)return 1;return 0;} + CHECK(dm_bcat_supported("0100F8F0000A2000"));CHECK(!dm_bcat_supported("0100152000022000")); + CHECK(!dm_bcat_supported("\xff")); + CHECK(validETag(@"\"fixture\""));CHECK(!validETag(@[]));CHECK(!validETag(NSNull.null));CHECK(!validETag(@"bad\nheader"));CHECK(!validETag(@"")); + CHECK(safePath(@"vsdata/VSSetting_0.byaml"));CHECK(!safePath(@"../data"));CHECK(!safePath(@"/absolute"));CHECK(!safePath(@"a//b"));CHECK(!safePath(@"a/../b"));CHECK(!safePath(@"a\\b"));CHECK(!safePath(@"c:/b")); + CHECK(!json([@"{\"a\":1,\"a\":2}" dataUsingEncoding:NSUTF8StringEncoding])); + CHECK(!json([@"{\"a\":1,\"\\u0061\":2}" dataUsingEncoding:NSUTF8StringEncoding])); + CHECK(!json([@"{\"p\":[{\"x\":1,\"x\":2}]}" dataUsingEncoding:NSUTF8StringEncoding])); + CHECK(json([@"{\"p\":[{\"x\":1},{\"x\":2}]}" dataUsingEncoding:NSUTF8StringEncoding])); + CHECK(!json([NSData dataWithBytes:"{\"a\":1}\0" length:8])); + NSMutableString *nested=[NSMutableString stringWithString:@"{\"a\":"]; + for(int i=0;i<40;i++)[nested appendString:@"["];[nested appendString:@"0"];for(int i=0;i<40;i++)[nested appendString:@"]"];[nested appendString:@"}"]; + CHECK(!json([nested dataUsingEncoding:NSUTF8StringEncoding])); + uint8_t secret[32]={7},public[32];size_t publicLength=32;EVP_PKEY *key=EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519,NULL,secret,32);CHECK(key&&EVP_PKEY_get_raw_public_key(key,public,&publicLength)==1);NSData *pub=[NSData dataWithBytes:public length:publicLength]; + NSISO8601DateFormatter *formatter=[NSISO8601DateFormatter new];NSTimeInterval now=NSDate.date.timeIntervalSince1970; + NSMutableDictionary *game=[@{@"title_ids":@[@"0100f8f0000a2000"],@"name":@"Original fixture",@"enabled":@YES,@"required_capabilities":@[@"versions.exact.v1"],@"versions":@{@"policy":@"exact",@"accepted":@[@"5.5.2"]}} mutableCopy]; + NSMutableDictionary *document=[@{@"document_type":@"game_catalog",@"schema_version":@1,@"revision":@4,@"issued_at":[formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:now-100]],@"expires_at":[formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:now+100]],@"games":@[game]} mutableCopy]; + NSData *signedData=envelope(jsonData(document),key); + CHECK(catalogWithKey(signedData,@"0100f8f0000a2000",@"5.5.2",YES,4,pub,NULL)); + CHECK(!catalogWithKey(signedData,@"0100f8f0000a2000",@"5.5.1",YES,4,pub,NULL)); + CHECK(!catalogWithKey(signedData,@"01003bc0000a0000",@"5.5.2",YES,4,pub,NULL)); + CHECK(!catalogWithKey(signedData,@"0100f8f0000a2000",@"5.5.2",YES,5,pub,NULL)); + CHECK(!catalog(signedData,@"0100f8f0000a2000",@"5.5.2",YES,0,NULL)); // original key is not the provider + NSMutableData *bad=[signedData mutableCopy];((uint8_t *)bad.mutableBytes)[bad.length/2]^=1;CHECK(!catalogWithKey(bad,@"0100f8f0000a2000",@"5.5.2",YES,0,pub,NULL)); + game[@"enabled"]=@NO;CHECK(!catalogWithKey(envelope(jsonData(document),key),@"0100f8f0000a2000",@"5.5.2",YES,0,pub,NULL));game[@"enabled"]=@YES; + game[@"required_capabilities"]=@[@"future.unknown.v2"];CHECK(!catalogWithKey(envelope(jsonData(document),key),@"0100f8f0000a2000",@"5.5.2",YES,0,pub,NULL));game[@"required_capabilities"]=@[@"versions.exact.v1"]; + document[@"expires_at"]=[formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:now-1]]; + CHECK(!catalogWithKey(envelope(jsonData(document),key),@"0100f8f0000a2000",@"5.5.2",YES,0,pub,NULL)); + CHECK(catalogWithKey(envelope(jsonData(document),key),@"0100f8f0000a2000",@"5.5.2",NO,0,pub,NULL)); + game[@"title_ids"]=@[@"0100f8f0000a2000",@"0100F8F0000A2000"];CHECK(!catalogWithKey(envelope(jsonData(document),key),@"0100f8f0000a2000",@"5.5.2",NO,0,pub,NULL)); + EVP_PKEY_free(key); + char canonical[4096];CHECK(realpath(NSTemporaryDirectory().fileSystemRepresentation,canonical)); + NSString *dir=[[NSString stringWithUTF8String:canonical] stringByAppendingPathComponent:NSUUID.UUID.UUIDString];CHECK(safeDirectory(dir,YES)); + NSString *file=[dir stringByAppendingPathComponent:@"current.json"];NSData *original=[@"original" dataUsingEncoding:NSUTF8StringEncoding];CHECK(atomicWrite(original,file)); + CHECK([boundedRead(file,8) isEqual:original]);CHECK(!boundedRead(file,3)); + NSString *link=[dir stringByAppendingPathComponent:@"link"];CHECK(!symlink(dir.fileSystemRepresentation,link.fileSystemRepresentation));CHECK(!safeDirectory([link stringByAppendingPathComponent:@"nested"],YES)); + CHECK(!snapshot(dir,@"0100f8f0000a2000",@"5.5.2"));CHECK([boundedRead(file,8) isEqual:original]); + CHECK(atomicWrite(jsonData(@{@"formatVersion":@1,@"titleID":@"0100f8f0000a2000",@"version":@"5.5.2"}),[dir stringByAppendingPathComponent:@"setup.json"])); + // A descriptor for another region must not select even a valid local cache. + startModules=dir;startTitle=@"01003bc0000a0000";startOnline=NO;setenv("DM_NEXTENDO_BCAT_DIR",dir.UTF8String,1);start();unsetenv("DM_NEXTENDO_BCAT_DIR"); + CHECK(!activeVersion&&!activeRefresh&&!refreshRunning); + [NSFileManager.defaultManager removeItemAtPath:dir error:nil]; + // Retained observers belong to one job even after a later refresh starts. + startOnline=YES;activeVersion=@"5.5.2";lastRefresh=NSDate.date.timeIntervalSince1970; + DmBcatRefresh *first=[DmBcatRefresh new];first.status=2;first.result=1;activeRefresh=first; + void *observer=dm_bcat_sync_observe();CHECK(observer);unsigned outcome=123;uint64_t downloaded=123; + CHECK(dm_bcat_sync_observer_status(observer,&outcome,&downloaded)==2); + activeRefresh=[DmBcatRefresh new];activeRefresh.status=9;activeRefresh.result=0;activeRefresh.bytes=99; + CHECK(dm_bcat_sync_observer_status(observer,&outcome,&downloaded)==2&&downloaded==0); + first.status=9;first.result=1; + CHECK(dm_bcat_sync_observer_status(observer,&outcome,&downloaded)==9&&outcome==1); + dm_bcat_sync_release(observer);activeVersion=nil;activeRefresh=nil;startOnline=NO; + setenv("DM_OODLE_SERVE","1",1);dm_bcat_start("/absent", "0100f8f0000a2000", 1);CHECK(!startupAccepted&&!activeRefresh);unsetenv("DM_OODLE_SERVE"); + setenv("DM_OODLE_JOB","fixture-job",1);dm_bcat_start("/absent", "0100f8f0000a2000", 1);CHECK(!startupAccepted&&!activeRefresh);unsetenv("DM_OODLE_JOB"); + dm_bcat_start("/absent", "0100f8f0000a2000", 0);CHECK(!dm_bcat_overlay());CHECK(!dm_bcat_delivery());CHECK(!dm_bcat_request_sync()); + dm_bcat_start("/different", "01003bc0000a0000", 1);CHECK([startTitle isEqual:@"0100f8f0000a2000"]&&!startOnline); + printf("BCAT signed policy/path/atomic store: %u checks passed\n",checks);return 0; +}} diff --git a/dm/host/tests/t_discovery_protocol.c b/dm/host/tests/t_discovery_protocol.c new file mode 100644 index 0000000000..57561a8bfc --- /dev/null +++ b/dm/host/tests/t_discovery_protocol.c @@ -0,0 +1,196 @@ +// Pure, synthetic protocol fixtures: no sockets, LAN, game files or devices. +// This checks eligibility for supplemental routing, not reachability or replies. +#include "../discovery_protocol.h" +#include +#include +#include +#include +#include + +static unsigned checks; +#define CHECK(c) do { ++checks; if (!(c)) { fprintf(stderr, "FAIL %d: %s\n", __LINE__, #c); abort(); } } while (0) + +enum { PIA_PORT = 30000, LDN_PORT = 11452, PIA_OVERHEAD = 0x12f, PIA_MAX = 1364 }; +static const unsigned char ldn_query[12] = {0, 0x14, 0x45, 0x11, 0, 0, 0, 0, 0, 0, 0, 0}; + +static void be32(unsigned char *p, uint32_t n) { + p[0] = (unsigned char)(n >> 24); p[1] = (unsigned char)(n >> 16); + p[2] = (unsigned char)(n >> 8); p[3] = (unsigned char)n; +} + +// The bodies deliberately contain arbitrary data. Only the verified query +// envelope determines eligibility; no title ID, payload magic or reply nonce +// may be inferred here. The counter belongs to the client sending the query. +static size_t pia_query(unsigned char *p, unsigned payload, unsigned flags) { + size_t size = payload + PIA_OVERHEAD; + for (size_t i = 0; i < size; ++i) p[i] = (unsigned char)(i * 197u + payload * 17u); + p[0] = 0; be32(p + 1, payload); + p[payload + 5] = 1; p[payload + 6] = (unsigned char)flags; + memset(p + payload + 7, 0, 8); p[payload + 14] = 1; + return size; +} + +static void valid_pia_lengths(void) { + unsigned char packet[PIA_MAX + 1]; + // Both sides of the 255/256 boundary catch a little-endian length decoder; + // 1061 bytes is the largest payload whose complete envelope fits in 1364. + for (unsigned payload = 0; payload <= PIA_MAX - PIA_OVERHEAD; ++payload) { + for (unsigned flags = 0; flags <= 1; ++flags) { + size_t size = pia_query(packet, payload, flags); + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == DM_DISCOVERY_PIA); + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size + 1) == 0); + } + } + size_t size = pia_query(packet, 0, 0); + for (unsigned byte = 0; byte < 8; ++byte) { + const unsigned values[] = {1, 0x80, 0xff}; + for (unsigned i = 0; i < sizeof values / sizeof values[0]; ++i) { + memset(packet + 7, 0, 8); packet[7 + byte] = (unsigned char)values[i]; + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == DM_DISCOVERY_PIA); + } + } + memset(packet + 7, 0, 8); + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == 0); +} + +static void malformed_pia(void) { + unsigned char packet[PIA_MAX + 1]; + const unsigned payloads[] = {0, 1, 2, 255, 256, 1060, 1061}; + for (unsigned i = 0; i < sizeof payloads / sizeof payloads[0]; ++i) { + unsigned payload = payloads[i]; + size_t size = pia_query(packet, payload, 0); + // Test every truncation with an allocation ending at the advertised + // size so ASan can catch reads into an incomplete header or footer. + for (size_t cut = 0; cut < size; ++cut) { + unsigned char *short_packet = malloc(cut ? cut : 1); CHECK(short_packet != NULL); + memcpy(short_packet, packet, cut); + CHECK(dm_discovery_query_protocol(PIA_PORT, short_packet, cut) == 0); + free(short_packet); + } + for (unsigned type = 1; type <= 255; ++type) { + packet[0] = (unsigned char)type; + // Type 1 is a response, even if all other fields match a query. + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == 0); + } + packet[0] = 0; + for (unsigned version = 0; version <= 255; ++version) { + if (version == 1) continue; + packet[payload + 5] = (unsigned char)version; + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == 0); + } + packet[payload + 5] = 1; + for (unsigned flags = 2; flags <= 255; ++flags) { + packet[payload + 6] = (unsigned char)flags; + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == 0); + } + packet[payload + 6] = 0; + memset(packet + payload + 7, 0, 8); + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == 0); + } + size_t size = pia_query(packet, 256, 1); + const uint32_t wrong_lengths[] = {0, 1, 255, 257, 1061, 1062, 0x10000, 0x01000000, 0x7fffffff, UINT32_MAX}; + for (unsigned i = 0; i < sizeof wrong_lengths / sizeof wrong_lengths[0]; ++i) { + be32(packet + 1, wrong_lengths[i]); + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == 0); + } + // The length itself is plausible in little endian, but not on the wire. + packet[1] = 0; packet[2] = 1; packet[3] = 0; packet[4] = 0; + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == 0); + size = pia_query(packet, 1061, 0); + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == DM_DISCOVERY_PIA); + packet[PIA_MAX] = 0; + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, sizeof packet) == 0); + // Oversize must be rejected before indexing with the untrusted length. + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, SIZE_MAX) == 0); +} + +static void exact_ldn(void) { + unsigned char packet[32]; + CHECK(dm_discovery_query_protocol(LDN_PORT, ldn_query, sizeof ldn_query) == DM_DISCOVERY_LDN); + for (unsigned byte = 0; byte < sizeof ldn_query; ++byte) { + for (unsigned value = 0; value <= 255; ++value) { + if (value == ldn_query[byte]) continue; + memcpy(packet, ldn_query, sizeof ldn_query); packet[byte] = (unsigned char)value; + CHECK(dm_discovery_query_protocol(LDN_PORT, packet, sizeof ldn_query) == 0); + } + } + memset(packet, 0, sizeof packet); memcpy(packet, ldn_query, sizeof ldn_query); + for (size_t size = 0; size <= sizeof packet; ++size) { + unsigned char *copy = malloc(size ? size : 1); CHECK(copy != NULL); + memcpy(copy, packet, size); + CHECK(dm_discovery_query_protocol(LDN_PORT, copy, size) == (size == sizeof ldn_query ? DM_DISCOVERY_LDN : 0)); + free(copy); + } + CHECK(dm_discovery_query_protocol(LDN_PORT, packet, SIZE_MAX) == 0); +} + +static void routing_scope(void) { + unsigned char packet[PIA_MAX]; + size_t size = pia_query(packet, 17, 1); + // The input is a host-order destination port, including on little-endian + // hosts. A verified query on another port must not start supplemental work. + for (unsigned port = 0; port <= 65535; ++port) { + CHECK(dm_discovery_query_protocol(port, packet, size) == (port == PIA_PORT ? DM_DISCOVERY_PIA : 0)); + CHECK(dm_discovery_query_protocol(port, ldn_query, sizeof ldn_query) == (port == LDN_PORT ? DM_DISCOVERY_LDN : 0)); + } + CHECK(dm_discovery_query_protocol(65536, packet, size) == 0); + CHECK(dm_discovery_query_protocol(UINT_MAX, packet, size) == 0); + CHECK(dm_discovery_query_protocol(65536, ldn_query, sizeof ldn_query) == 0); + CHECK(dm_discovery_query_protocol(UINT_MAX, ldn_query, sizeof ldn_query) == 0); + const unsigned ports[] = {0, PIA_PORT, LDN_PORT, 65535, UINT_MAX}; + const size_t sizes[] = {0, 1, 5, 12, PIA_OVERHEAD, PIA_MAX, SIZE_MAX}; + for (unsigned p = 0; p < sizeof ports / sizeof ports[0]; ++p) + for (unsigned s = 0; s < sizeof sizes / sizeof sizes[0]; ++s) + CHECK(dm_discovery_query_protocol(ports[p], NULL, sizes[s]) == 0); +} + +static uint32_t random_word(uint32_t *state) { + uint32_t n = *state; n ^= n << 13; n ^= n >> 17; n ^= n << 5; *state = n; return n; +} + +static void fuzz_bounds(void) { + uint32_t state = UINT32_C(0x930ef217); + for (unsigned run = 0; run < 50000; ++run) { + unsigned payload = random_word(&state) % (PIA_MAX - PIA_OVERHEAD + 1); + size_t size = run % 3 ? random_word(&state) % 1501 : payload + PIA_OVERHEAD; + // A varying unaligned start plus an exact trailing allocation catches + // alignment assumptions and reads past even one-byte input buffers. + size_t prefix = run % 8; + unsigned char *allocation = malloc(prefix + (size ? size : 1)); CHECK(allocation != NULL); + unsigned char *packet = allocation + prefix; + for (size_t i = 0; i < size; ++i) packet[i] = (unsigned char)random_word(&state); + if (!(run % 3)) { + // Reach the footer checks on unaligned valid frames as well as + // testing random data that normally fails at the header. + pia_query(packet, payload, random_word(&state) & 1u); + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == DM_DISCOVERY_PIA); + switch ((run / 3) % 6) { + case 0: packet[0] = 1; break; + case 1: memset(packet + payload + 7, 0, 8); break; + case 2: packet[payload + 5] = 2; break; + case 3: packet[payload + 6] = 2; break; + case 4: be32(packet + 1, UINT32_MAX); break; + case 5: --size; break; + } + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == 0); + } + const unsigned ports[] = {PIA_PORT, LDN_PORT, 0, 65535, UINT_MAX}; + for (unsigned i = 0; i < sizeof ports / sizeof ports[0]; ++i) { + unsigned result = dm_discovery_query_protocol(ports[i], packet, size); + CHECK(result == 0 || result == DM_DISCOVERY_PIA || result == DM_DISCOVERY_LDN); + CHECK(!result || (result == DM_DISCOVERY_PIA ? ports[i] == PIA_PORT : ports[i] == LDN_PORT)); + } + // A guaranteed invalid type makes this an independent rejection test + // even if later random generation happens to resemble a valid envelope. + if (size) packet[0] = 0xff; + CHECK(dm_discovery_query_protocol(PIA_PORT, packet, size) == 0); + CHECK(dm_discovery_query_protocol(LDN_PORT, packet, size) == 0); + free(allocation); + } +} + +int main(void) { + valid_pia_lengths(); malformed_pia(); exact_ldn(); routing_scope(); fuzz_bounds(); + printf("discovery protocol: %u checks passed (synthetic Pia/LDN queries, scope, malformed input and fuzz bounds).\n", checks); + return 0; +} diff --git a/dm/host/tests/t_friends.c b/dm/host/tests/t_friends.c index 72128a1c6d..6d10bfc4c6 100644 --- a/dm/host/tests/t_friends.c +++ b/dm/host/tests/t_friends.c @@ -5,6 +5,9 @@ #include void hle_bind_system_event(void *g, int autoclear) { (void)g; (void)autoclear; } void hle_signal_system_event(void *g) { (void)g; } +// the local user here (t_nextendo_off.c has the offline Nextendo provider); the presence and key checks below use another Uid +static const uint8_t k_local[16] = {2}; +int dm_account_uid_exists(const void *uid) { return uid && !memcmp(uid, k_local, sizeof k_local); } extern const struct mach_header_64 _mh_execute_header; static int checks, fails; #define CHECK(c, s) do { checks++; int ok = !!(c); fails += !ok; printf("%s %s\n", ok ? "✓" : "✗", s); } while (0) @@ -19,6 +22,32 @@ static void *hook(const char *name) { CHECK(count == 1 && fn, name); return count == 1 ? fn : NULL; } +static void check_friend_ids(void) { // seedds's t_server_environment checks: the provider answers them offline as the cut there did + Result (*ids)(int *, void *, int, int, const void *) = hook("_ZN2nn7friends13GetFriendListEPiPNS_7account23NetworkServiceAccountIdEiiRKNS0_12FriendFilterE") ? h_fr_GetFriendIds : NULL; + Result (*ids_uid)(int *, void *, const void *, int, int, const void *) = hook("_ZN2nn7friends13GetFriendListEPiPNS_7account23NetworkServiceAccountIdERKNS2_3UidEiiRKNS0_12FriendFilterE") ? h_fr_GetFriendIdsUid : NULL; + const uint64_t before[] = {0x123456789abcdef0, 0xfedcba9876543210}; + uint64_t output[2]; + uint8_t uid[16] = {1}, filter[32] = {0}; + if (ids) { + int count = 7; + memcpy(output, before, sizeof output); + CHECK(ids(&count, output, 2, 2, filter) == RES_FAIL, "friend IDs without Uid remain unavailable offline"); + CHECK(count == 0, "unavailable ID list reports zero entries"); + CHECK(!memcmp(output, before, sizeof output), "unavailable ID list leaves client storage untouched"); + count = 7; + CHECK(ids(&count, NULL, 0, 0, filter) == RES_FAIL && count == 0, "zero-capacity ID query remains empty"); + } + if (ids_uid) { + int count = 7; + memcpy(output, before, sizeof output); + CHECK(ids_uid(&count, output, uid, 2, 2, filter) == RES_FAIL, "friend IDs with Uid remain unavailable offline"); + CHECK(count == 0, "unavailable per-user ID list reports zero entries"); + CHECK(!memcmp(output, before, sizeof output), "unavailable per-user ID list leaves client storage untouched"); + count = 7; + CHECK(ids_uid(&count, NULL, uid, 0, 0, filter) == RES_FAIL && count == 0, "zero-capacity per-user query remains empty"); + } +} + int main(void) { uint8_t presence[0x100] = {0}, uid[16] = {1}; CHECK(h_fr_UpInit(presence, uid) == RES_OK, "UserPresence::Initialize succeeds"); @@ -29,7 +58,8 @@ int main(void) { CHECK(h_fr_NqPop(presence, info) != RES_OK, "NotificationQueue::Pop finds no notification"); CHECK(h_fr_OpenSession(uid) == RES_FAIL, "DeclareOpenOnlinePlaySession still fails"); // Resolve the actual takeovers: a missing or misspelled overload would run the SDK's friends client instead (PR #2162, issue #3177). - Result (*key_uid)(void *, const void *, int) = hook("_ZN2nn7friends29GetPlayHistoryRegistrationKeyEPNS0_26PlayHistoryRegistrationKeyERKNS_7account3UidEb"); + // The Uid form is a wait entry (HLE_FORCE_WAIT): its table function is the gate into entry.S, which only a guest thread may enter, so the check calls the hook itself + Result (*key_uid)(void *, const void *, unsigned) = hook("_ZN2nn7friends29GetPlayHistoryRegistrationKeyEPNS0_26PlayHistoryRegistrationKeyERKNS_7account3UidEb") ? h_fr_GetPHKey : NULL; Result (*key_no_uid)(void *, int) = hook("_ZN2nn7friends29GetPlayHistoryRegistrationKeyEPNS0_26PlayHistoryRegistrationKeyEb"); uint8_t key[0x100], before[sizeof key]; memset(before, 0xa5, sizeof before); @@ -37,8 +67,9 @@ int main(void) { for (size_t i = 0; i < sizeof local_args / sizeof *local_args; i++) { if (key_uid) { memcpy(key, before, sizeof key); - CHECK(key_uid(key, uid, local_args[i]) == RES_FAIL, "play history key with Uid is unavailable"); - CHECK(!memcmp(key, before, sizeof key), "failed key query with Uid leaves output untouched"); + // The Uid form is the host's own key (hle_friends_history.c, t_friends_history): a Uid other than the local user's is refused and the key cleared + CHECK(key_uid(key, uid, local_args[i]) == DM_FRIENDS_HISTORY_INVALID_UID, "play history key for another Uid is refused"); + CHECK(!memcmp(key + DM_FRIENDS_HISTORY_KEY_SIZE, before + DM_FRIENDS_HISTORY_KEY_SIZE, sizeof key - DM_FRIENDS_HISTORY_KEY_SIZE), "the refusal writes only the key's 64 bytes"); } if (key_no_uid) { memcpy(key, before, sizeof key); @@ -46,13 +77,13 @@ int main(void) { CHECK(!memcmp(key, before, sizeof key), "failed key query without Uid leaves output untouched"); } } + check_friend_ids(); // Blocked-user list availability, no-Uid forms, and methods on cut objects (issue #3177). uint8_t ctx[0x40], obj[0x40], ids[16] = {2}; memset(ctx, 0x5a, sizeof ctx); memset(obj, 0x5a, sizeof obj); - Result (*ac_cancel)(void *) = hook("_ZN2nn7friends12AsyncContext6CancelEv"); - if (ac_cancel) CHECK(ac_cancel(ctx) == RES_OK, "AsyncContext::Cancel succeeds"); - Result (*up_init_nouid)(void *) = hook("_ZN2nn7friends12UserPresence10InitializeEv"); + // AsyncContext::Cancel is the Nextendo provider's (dm_nextendo_async_cancel), a wait entry: a context it never started does not cancel + Result (*up_init_nouid)(void *) = hook("_ZN2nn7friends12UserPresence10InitializeEv") ? h_fr_UpInitOpen : NULL; // a wait entry: the hook itself if (up_init_nouid) CHECK(up_init_nouid(presence) == RES_OK, "UserPresence::Initialize without Uid succeeds"); Result (*open_nouid)(void) = hook("_ZN2nn7friends28DeclareOpenOnlinePlaySessionEv"); Result (*close_nouid)(void) = hook("_ZN2nn7friends29DeclareCloseOnlinePlaySessionEv"); diff --git a/dm/host/tests/t_friends_history.c b/dm/host/tests/t_friends_history.c new file mode 100644 index 0000000000..526e50132d --- /dev/null +++ b/dm/host/tests/t_friends_history.c @@ -0,0 +1,134 @@ +// Only synthetic signing keys. This fixture neither reads the user's firmware +// nor creates an online identity. +#include "../hle.h" +#undef HLE_FORCE +#undef HLE_FORCE_WAIT +#define HLE_FORCE(name, why, ret, cname, ...) static ret cname(__VA_ARGS__) +#define HLE_FORCE_WAIT HLE_FORCE +#include "../hle_friends.c" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static unsigned checks; +#define CHECK(test) do { ++checks; if (!(test)) { fprintf(stderr, "failed line %d: %s\n", __LINE__, #test); abort(); } } while (0) +static const uint8_t local_uid[16] = {1}; +static _Thread_local int wait_depth; +static _Atomic unsigned begins, ends; +void dm_guest_host_wait_begin(void) { ++wait_depth; atomic_fetch_add(&begins, 1); } +void dm_guest_host_wait_end(void) { assert(wait_depth > 0); --wait_depth; atomic_fetch_add(&ends, 1); } +void hle_bind_system_event(void *p, int clear) { (void)p; (void)clear; } +void hle_signal_system_event(void *p) { (void)p; } +int dm_account_uid_exists(const void *uid) { return uid && !memcmp(uid, local_uid, sizeof local_uid); } +static bool unavailable(uint8_t keys[8][32]) { (void)keys; return false; } +static bool synthetic_keys(uint8_t keys[8][32]) { + for (unsigned i = 0; i < 8; ++i) for (unsigned j = 0; j < 32; ++j) keys[i][j] = (uint8_t)(32*i+j); + return true; +} +static void fixed_random(void *p, unsigned size) { memset(p, 0x22, size); } +static int all_zero(const uint8_t *p, unsigned n) { uint8_t any = 0; for (unsigned i = 0; i < n; ++i) any |= p[i]; return !any; } +static int valid_key(const uint8_t key[64], unsigned flag) { + if (key[0] != 1 || key[1] != 1 || key[2] > 7 || key[3] || key[4] != (flag&1) || !all_zero(key+5, 11) || + (key[22]&0xf0) != 0x40 || (key[24]&0xc0) != 0x80) return 0; + uint8_t keys[8][32], expected[32]; synthetic_keys(keys); + CCHmac(kCCHmacAlgSHA256, keys[key[2]], 32, key, 32, expected); + return !memcmp(expected, key+32, 32); +} +static void write_file(const char *path, const void *data, size_t size) { + int fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0600); assert(fd >= 0); assert(write(fd, data, size) == (ssize_t)size); assert(!close(fd)); +} +static unsigned fd_count(void) { unsigned n = 0; for (int fd = 0; fd < 512; ++fd) if (fcntl(fd, F_GETFD) >= 0) ++n; return n; } +static int cleanup(const char *path, const struct stat *st, int type, struct FTW *tree) { (void)st; (void)type; (void)tree; return remove(path); } +static void *parallel_keys(void *opaque) { + const uint8_t *uuid = opaque; uint8_t key[64]; + for (unsigned i = 0; i < 80; ++i) { + assert(dm_friends_history_key(key, local_uid, i) == 0 && valid_key(key, i) && !memcmp(key+16, uuid, 16)); + assert(wait_depth == 0); + } + return NULL; +} +int main(void) { + char root[] = "/tmp/nx-friends-history-XXXXXX"; CHECK(mkdtemp(root)); CHECK(!setenv("DM_ROOT", root, 1)); + CHECK(!unsetenv("DM_SYSTEM_DATA_DIR")); + uint8_t output[66], zero_uid[16] = {0}, other_uid[16] = {2}; + memset(output, 0x6a, sizeof output); + CHECK(h_fr_GetPHKey(NULL, local_uid, 1) == DM_FRIENDS_HISTORY_FAIL); + CHECK(h_fr_GetPHKey(output+1, zero_uid, 1) == DM_FRIENDS_HISTORY_INVALID_UID && all_zero(output+1, 64)); + CHECK(h_fr_GetPHKey(output+1, other_uid, 1) == DM_FRIENDS_HISTORY_INVALID_UID && all_zero(output+1, 64)); + CHECK(h_fr_GetPHKey(output+1, NULL, 1) == DM_FRIENDS_HISTORY_INVALID_UID); + CHECK(h_fr_GetPHKey(output+1, local_uid, 1) != 0 && all_zero(output+1, 64)); + CHECK(output[0] == 0x6a && output[65] == 0x6a && !wait_depth); + dm_friends_history_set_key_provider(unavailable); + CHECK(h_fr_GetPHKey(output+1, local_uid, 1) != 0 && all_zero(output+1, 64)); + dm_friends_history_set_key_provider(synthetic_keys); dm_friends_history_set_random_provider(fixed_random); + CHECK(h_fr_GetPHKey(output+1, local_uid, 0xffffffffu) == 0); + // Independently calculated with Python's hmac/hashlib over this specified + // synthetic body/key. It catches packing, source-key selection and coverage. + static const uint8_t known[64] = { + 1,1,2,0,1,0,0,0,0,0,0,0,0,0,0,0,0x22,0x22,0x22,0x22,0x22,0x22,0x42,0x22,0xa2,0x22,0x22,0x22,0x22,0x22,0x22,0x22, + 0xc6,0x2e,0x99,0x42,0x02,0xfb,0x56,0x65,0xc0,0x60,0x01,0x61,0x95,0x47,0xec,0x13, + 0x0d,0x8b,0x73,0x6c,0x55,0x79,0xc4,0xbb,0x27,0xe5,0x4f,0xa1,0x0a,0x14,0x6c,0x6b}; + CHECK(!memcmp(output+1, known, 64) && output[0] == 0x6a && output[65] == 0x6a); + uint8_t uuid[16]; memcpy(uuid, output+17, 16); + char directory[PATH_MAX], path[PATH_MAX], bad[PATH_MAX]; + snprintf(directory, sizeof directory, "%s/friends-history", root); + snprintf(path, sizeof path, "%s/01000000000000000000000000000000.uuid.bin", directory); + struct stat st; CHECK(!stat(directory, &st) && (st.st_mode&0777) == 0700); + CHECK(!stat(path, &st) && (st.st_mode&0777) == 0600 && st.st_size == 16); + CHECK(h_fr_GetPHKey(output+1, local_uid, 2) == 0 && valid_key(output+1, 0) && !memcmp(uuid, output+17, 16)); + CHECK(memcmp(output+33, known+32, 32)); + dm_friends_history_set_random_provider(NULL); + CHECK(dm_friends_history_key(output+1, other_uid, 1) == 0 && valid_key(output+1, 1) && memcmp(uuid, output+17, 16)); + unsigned before = fd_count(); pthread_t threads[8]; + for (unsigned i = 0; i < 8; ++i) CHECK(!pthread_create(threads+i, NULL, parallel_keys, uuid)); + for (unsigned i = 0; i < 8; ++i) CHECK(!pthread_join(threads[i], NULL)); + CHECK(before == fd_count() && atomic_load(&begins) == atomic_load(&ends)); + // Separate processes race the first creation. The persisted winner must be + // atomic and stable for every successful call, rather than overwriting UUIDs. + int pipefd[2]; CHECK(!pipe(pipefd)); pid_t children[8]; + for (unsigned i = 0; i < 8; ++i) { + children[i] = fork(); CHECK(children[i] >= 0); + if (!children[i]) { + close(pipefd[0]); uint8_t key[64], uid[16] = {3}; + if (dm_friends_history_key(key, uid, 1) || !valid_key(key, 1) || write(pipefd[1], key, 64) != 64) _exit(1); + close(pipefd[1]); _exit(0); + } + } + close(pipefd[1]); uint8_t results[8][64]; const size_t capacity = sizeof results; size_t have = 0; + while (have < capacity) { ssize_t n = read(pipefd[0], (char *)results+have, capacity-have); assert(n > 0); have += (size_t)n; } + close(pipefd[0]); + for (unsigned i = 0; i < 8; ++i) { int status; CHECK(waitpid(children[i], &status, 0) == children[i] && WIFEXITED(status) && !WEXITSTATUS(status)); CHECK(!memcmp(results[0]+16, results[i]+16, 16)); } + CHECK(!chmod(path, 0644)); CHECK(h_fr_GetPHKey(output+1, local_uid, 1) != 0 && all_zero(output+1, 64)); CHECK(!chmod(path, 0600)); + write_file(path, uuid, 15); CHECK(h_fr_GetPHKey(output+1, local_uid, 1) != 0); CHECK(!stat(path, &st) && st.st_size == 15); + uint8_t broken[16] = {0}; write_file(path, broken, 16); CHECK(h_fr_GetPHKey(output+1, local_uid, 1) != 0); + write_file(path, uuid, 16); + snprintf(bad, sizeof bad, "%s/uuid-target", root); CHECK(!rename(path, bad)); CHECK(!symlink(bad, path)); + CHECK(h_fr_GetPHKey(output+1, local_uid, 1) != 0 && all_zero(output+1, 64)); CHECK(!unlink(path)); CHECK(!rename(bad, path)); + CHECK(!chmod(directory, 0755)); CHECK(h_fr_GetPHKey(output+1, local_uid, 1) != 0); CHECK(!chmod(directory, 0700)); + // The default provider uses only the exact private firmware archive path. + char archive[PATH_MAX], files[PATH_MAX], keypath[PATH_MAX]; + snprintf(archive, sizeof archive, "%s/010000000000000e", root); CHECK(!mkdir(archive, 0700)); + snprintf(files, sizeof files, "%s/files", archive); CHECK(!mkdir(files, 0700)); + snprintf(keypath, sizeof keypath, "%s/play-history.keyring", files); + uint8_t keys[8][32]; synthetic_keys(keys); write_file(keypath, keys, sizeof keys); + dm_friends_history_set_key_provider(NULL); CHECK(!setenv("DM_SYSTEM_DATA_DIR", root, 1)); + CHECK(h_fr_GetPHKey(output+1, local_uid, 1) == 0 && valid_key(output+1, 1) && !memcmp(uuid, output+17, 16)); + write_file(keypath, keys, sizeof keys-1); CHECK(h_fr_GetPHKey(output+1, local_uid, 1) != 0 && all_zero(output+1, 64)); + write_file(keypath, keys, sizeof keys); snprintf(bad, sizeof bad, "%s/key-target", root); CHECK(!rename(keypath, bad)); CHECK(!symlink(bad, keypath)); + CHECK(h_fr_GetPHKey(output+1, local_uid, 1) != 0); CHECK(!unlink(keypath)); CHECK(!mkfifo(keypath, 0600)); + CHECK(h_fr_GetPHKey(output+1, local_uid, 1) != 0); CHECK(!unlink(keypath)); CHECK(!rename(bad, keypath)); + snprintf(bad, sizeof bad, "%s/archive-target", root); CHECK(!rename(archive, bad)); CHECK(!symlink(bad, archive)); + CHECK(h_fr_GetPHKey(output+1, local_uid, 1) != 0); CHECK(!unlink(archive)); CHECK(!rename(bad, archive)); + CHECK(!wait_depth && atomic_load(&begins) == atomic_load(&ends) && before == fd_count()); + CHECK(!nftw(root, cleanup, 32, FTW_DEPTH|FTW_PHYS)); + printf("Friends history: %u checks; known synthetic HMAC vector, flags, persistent UUID, process race, failures, symlinks and FD lifetime passed.\n", checks); + return 0; +} diff --git a/dm/host/tests/t_fs_case.c b/dm/host/tests/t_fs_case.c index 4d54d4bf88..924f8fd881 100644 --- a/dm/host/tests/t_fs_case.c +++ b/dm/host/tests/t_fs_case.c @@ -12,6 +12,7 @@ static int fake_setxattr(const char *p, const char *name, const void *v, size_t } #define setxattr fake_setxattr #include HLE_FS_SOURCE +#include "bcat_absent.h" // standalone fixture: no calendar provider is linked #undef setxattr struct dm_flags g_flag; uint64_t g_t0_ns; uint64_t now_ns(void) { return 0; } diff --git a/dm/host/tests/t_fs_commit_list.c b/dm/host/tests/t_fs_commit_list.c index 5c855ec288..4b348adbe6 100644 --- a/dm/host/tests/t_fs_commit_list.c +++ b/dm/host/tests/t_fs_commit_list.c @@ -56,7 +56,7 @@ static Result write_save(const char *path, const char *s) { h_fs_CloseFile(h); return r; } static int read_save(const char *path, char *out, size_t n) { - uint64_t h; size_t got = 0; if (h_fs_OpenFile(&h, path, MODE_READ)) return 0; + uint64_t h=0; size_t got = 0; if (!n || h_fs_OpenFile(&h, path, MODE_READ)) return 0; Result r = h_fs_ReadFile(&got, h, 0, out, n - 1); h_fs_CloseFile(h); out[got] = 0; return !r; } static pthread_mutex_t first_lock = PTHREAD_MUTEX_INITIALIZER; diff --git a/dm/host/tests/t_fs_stub.c b/dm/host/tests/t_fs_stub.c index 658bd904b1..06c6967f4b 100644 --- a/dm/host/tests/t_fs_stub.c +++ b/dm/host/tests/t_fs_stub.c @@ -17,3 +17,5 @@ int dm_game_imports(const char *prefix) { (void)prefix; return 0; } int dm_mii_standin(const char *dir) { (void)dir; return 0; } // the guest scheduler (hle_thread.c): no guest threads, so no handoff to leave void dm_thread_service_request(void) {} + +#include "bcat_absent.h" diff --git a/dm/host/tests/t_gate_fixture.h b/dm/host/tests/t_gate_fixture.h new file mode 100644 index 0000000000..fdc0c5a27f --- /dev/null +++ b/dm/host/tests/t_gate_fixture.h @@ -0,0 +1,29 @@ +// Actual per-thread gate stacks for component fixtures linking entry.S. +#pragma once +#include +#include +#include +#include +#include +#include +pthread_key_t g_keygate; +extern unsigned char dm_gate_stubs[]; +extern uintptr_t dm_gate_top[]; +static pthread_once_t fixture_gate_once = PTHREAD_ONCE_INIT; +static _Atomic unsigned fixture_gate_next; +static void fixture_gate_destroy(void *value) { + unsigned slot = (unsigned)((unsigned char *)value - dm_gate_stubs) / 16; + munmap((void *)(dm_gate_top[slot] - (1 << 20)), 1 << 20); dm_gate_top[slot] = 0; +} +static void fixture_gate_initialize(void) { assert(!pthread_key_create(&g_keygate, fixture_gate_destroy)); } +static void fixture_gate_prepare(void) { + pthread_once(&fixture_gate_once, fixture_gate_initialize); + if (pthread_getspecific(g_keygate)) return; + unsigned slot = atomic_fetch_add(&fixture_gate_next, 1); assert(slot < 1024); + void *memory = mmap(NULL, 1 << 20, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); assert(memory != MAP_FAILED); + dm_gate_top[slot] = (uintptr_t)memory + (1 << 20); + assert(!pthread_setspecific(g_keygate, dm_gate_stubs + slot * 16)); +} +void dm_gate_nested(uint64_t sp) { (void)sp; abort(); } +void dm_applet_enter(const char *name) { (void)name; } +void dm_applet_leave(void) {} diff --git a/dm/host/tests/t_hle_wait.S b/dm/host/tests/t_hle_wait.S new file mode 100644 index 0000000000..3289c82d8a --- /dev/null +++ b/dm/host/tests/t_hle_wait.S @@ -0,0 +1,124 @@ +// Assembly guest caller for t_hle_wait.c: load recognizable registers on an 8 KiB guest stack, call the real wrapper, snapshot its return, restore the host caller ABI. +.text +.p2align 2 +.globl _wait_test_invoke +_wait_test_invoke: + sub sp, sp, #176 + stp x19, x20, [sp, #0] + stp x21, x22, [sp, #16] + stp x23, x24, [sp, #32] + stp x25, x26, [sp, #48] + stp x27, x28, [sp, #64] + stp x29, x30, [sp, #80] + stp d8, d9, [sp, #96] + stp d10, d11, [sp, #112] + stp d12, d13, [sp, #128] + stp d14, d15, [sp, #144] + stp x0, x1, [sp, #160] + adrp x9, _g_wait_test_host_sp@PAGE + mov x10, sp + str x10, [x9, _g_wait_test_host_sp@PAGEOFF] + mov sp, x2 + mov x30, x0 + ldp q0, q1, [x30, #256] + ldp q2, q3, [x30, #288] + ldp q4, q5, [x30, #320] + ldp q6, q7, [x30, #352] + ldp q8, q9, [x30, #384] + ldp q10, q11, [x30, #416] + ldp q12, q13, [x30, #448] + ldp q14, q15, [x30, #480] + ldp q16, q17, [x30, #512] + ldp q18, q19, [x30, #544] + ldp q20, q21, [x30, #576] + ldp q22, q23, [x30, #608] + ldp q24, q25, [x30, #640] + ldp q26, q27, [x30, #672] + ldp q28, q29, [x30, #704] + ldp q30, q31, [x30, #736] + ldr x9, [x30, #768] + msr nzcv, x9 + ldr x9, [x30, #776] + msr fpsr, x9 + ldr x9, [x30, #784] + msr fpcr, x9 + ldp x0, x1, [x30, #0] + ldp x2, x3, [x30, #16] + ldp x4, x5, [x30, #32] + ldp x6, x7, [x30, #48] + ldp x8, x9, [x30, #64] + ldp x10, x11, [x30, #80] + ldp x12, x13, [x30, #96] + ldp x14, x15, [x30, #112] + ldp x16, x17, [x30, #128] + ldr x19, [x30, #152] + ldp x20, x21, [x30, #160] + ldp x22, x23, [x30, #176] + ldp x24, x25, [x30, #192] + ldp x26, x27, [x30, #208] + ldp x28, x29, [x30, #224] + bl _wait_probe_wait +.globl _wait_test_return +_wait_test_return: + sub sp, sp, #800 + stp x0, x1, [sp, #0] + stp x2, x3, [sp, #16] + stp x4, x5, [sp, #32] + stp x6, x7, [sp, #48] + stp x8, x9, [sp, #64] + stp x10, x11, [sp, #80] + stp x12, x13, [sp, #96] + stp x14, x15, [sp, #112] + stp x16, x17, [sp, #128] + stp x18, x19, [sp, #144] + stp x20, x21, [sp, #160] + stp x22, x23, [sp, #176] + stp x24, x25, [sp, #192] + stp x26, x27, [sp, #208] + stp x28, x29, [sp, #224] + str x30, [sp, #240] + add x9, sp, #800 + str x9, [sp, #248] + stp q0, q1, [sp, #256] + stp q2, q3, [sp, #288] + stp q4, q5, [sp, #320] + stp q6, q7, [sp, #352] + stp q8, q9, [sp, #384] + stp q10, q11, [sp, #416] + stp q12, q13, [sp, #448] + stp q14, q15, [sp, #480] + stp q16, q17, [sp, #512] + stp q18, q19, [sp, #544] + stp q20, q21, [sp, #576] + stp q22, q23, [sp, #608] + stp q24, q25, [sp, #640] + stp q26, q27, [sp, #672] + stp q28, q29, [sp, #704] + stp q30, q31, [sp, #736] + mrs x9, nzcv + str x9, [sp, #768] + mrs x9, fpsr + str x9, [sp, #776] + mrs x9, fpcr + str x9, [sp, #784] + adrp x9, _g_wait_test_host_sp@PAGE + ldr x9, [x9, _g_wait_test_host_sp@PAGEOFF] + ldr x0, [x9, #168] + mov x1, sp + mov x2, #800 + bl _memcpy + adrp x9, _g_wait_test_host_sp@PAGE + ldr x9, [x9, _g_wait_test_host_sp@PAGEOFF] + mov sp, x9 + ldp d8, d9, [sp, #96] + ldp d10, d11, [sp, #112] + ldp d12, d13, [sp, #128] + ldp d14, d15, [sp, #144] + ldp x19, x20, [sp, #0] + ldp x21, x22, [sp, #16] + ldp x23, x24, [sp, #32] + ldp x25, x26, [sp, #48] + ldp x27, x28, [sp, #64] + ldp x29, x30, [sp, #80] + add sp, sp, #176 + ret diff --git a/dm/host/tests/t_hle_wait.c b/dm/host/tests/t_hle_wait.c new file mode 100644 index 0000000000..8015dc0398 --- /dev/null +++ b/dm/host/tests/t_hle_wait.c @@ -0,0 +1,140 @@ +// Real blocking-hook assembly, big stack and thread pause/context SVCs. No game, socket, UI or device is used. +#include "../hle.h" +#include "../hle_thread.c" +#include +#include +struct dm_flags g_flag; +uint64_t g_t0_ns; +__thread _Atomic int dm_host_work; +pthread_key_t g_key18, g_keygate; +extern uint64_t dm_gate_top[1024]; +extern const unsigned char dm_gate_stubs[]; +void dm_gate_nested(uint64_t sp) { (void)sp; abort(); } +void guest_thread_set_id(uint64_t id) { (void)id; } +void guest_gate_stack(int own) { (void)own; } +void crash_thread_init(void) {} +void guest_thread_init(void) {} +void *guest_sym(const char *name) { (void)name; return NULL; } +module_t *module_of(const void *p) { (void)p; return NULL; } +uint64_t now_ns(void) { static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb); return mach_absolute_time() * tb.numer / tb.denom; } +uint64_t guest_ns(void) { return now_ns(); } +int dm_detclock_enabled(void) { return 0; } +__thread uint64_t dm_clock_reads; // guest clock reads per thread (hle_os.c in the host; thr_yield reads it) +void unimpl_c(void) { abort(); } +uint64_t gate_dispatch(uint64_t pc, uint64_t *registers) { (void)pc; (void)registers; abort(); } + +static uintptr_t guest_bottom, guest_top; +int dm_guest_as_contains(uintptr_t p) { return p >= guest_bottom && p < guest_top; } +uintptr_t g_wait_test_host_sp; // used only by the assembly worker before/after its simulated guest call +extern void wait_test_invoke(const uint64_t *, uint64_t *, uintptr_t); +extern const char wait_test_return[]; +static uint64_t before[100], after[100], arguments[8]; +static thr_t worker; +static pthread_mutex_t M = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t C = PTHREAD_COND_INITIALIZER; +static int entered, release_nested, nested_left, finish_body; +static _Atomic int body_returning, guest_progress, on_big_stack; +static uint64_t native_x18; +static const uint64_t result = UINT64_C(0xfedcba9876543210); +static void await_flag(int *flag) { + struct timespec deadline; clock_gettime(CLOCK_REALTIME, &deadline); deadline.tv_sec += 10; + pthread_mutex_lock(&M); + while (!*flag) assert(!pthread_cond_timedwait(&C, &M, &deadline)); + pthread_mutex_unlock(&M); +} +static void set_flag(int *flag) { pthread_mutex_lock(&M); *flag = 1; pthread_cond_broadcast(&C); pthread_mutex_unlock(&M); } + +HLE_FORCE_WAIT("test::Blocking", "exercise the production blocking hook boundary", uint64_t, wait_probe, + uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e, uint64_t f, uint64_t g, uint64_t h) { + // More than twice the whole guest stack: this must run on the production big stack. + volatile unsigned char heavy[20000]; heavy[0] = 19; heavy[sizeof heavy - 1] = 23; + atomic_store(&on_big_stack, !dm_guest_as_contains((uintptr_t)&heavy[0])); + uint64_t received[] = {a,b,c,d,e,f,g,h}; memcpy(arguments, received, sizeof arguments); + uint64_t nested[100] = {UINT64_C(0xbadbadbad)}; + thr_svc_enter(nested, UINT64_C(0xbad000)); + set_flag(&entered); await_flag(&release_nested); + thr_svc_leave(); // a nested exit must wait while paused, without unpublishing the outer guest frame + set_flag(&nested_left); await_flag(&finish_body); + assert(heavy[0] == 19 && heavy[sizeof heavy - 1] == 23); + atomic_store(&body_returning, 1); + // Exercise restoration even for SIMD registers the host's current libc happens not to use. + __asm__ volatile( + "movi v0.16b, #0\n movi v1.16b, #0\n movi v2.16b, #0\n movi v3.16b, #0\n" + "movi v4.16b, #0\n movi v5.16b, #0\n movi v6.16b, #0\n movi v7.16b, #0\n" + "movi v8.16b, #0\n movi v9.16b, #0\n movi v10.16b, #0\n movi v11.16b, #0\n" + "movi v12.16b, #0\n movi v13.16b, #0\n movi v14.16b, #0\n movi v15.16b, #0\n" + "movi v16.16b, #0\n movi v17.16b, #0\n movi v18.16b, #0\n movi v19.16b, #0\n" + "movi v20.16b, #0\n movi v21.16b, #0\n movi v22.16b, #0\n movi v23.16b, #0\n" + "movi v24.16b, #0\n movi v25.16b, #0\n movi v26.16b, #0\n movi v27.16b, #0\n" + "movi v28.16b, #0\n movi v29.16b, #0\n movi v30.16b, #0\n movi v31.16b, #0\n" + ::: "v0","v1","v2","v3","v4","v5","v6","v7","v8","v9","v10","v11","v12","v13","v14","v15", + "v16","v17","v18","v19","v20","v21","v22","v23","v24","v25","v26","v27","v28","v29","v30","v31"); + return result; +} +static void *run_worker(void *unused) { + (void)unused; + pthread_setspecific(g_keythr, &worker); + pthread_setspecific(g_key18, (void *)(uintptr_t)UINT64_C(0x1818181818181818)); + __asm__ volatile("mov %0, x18" : "=r"(native_x18)); + void *gate = mmap(NULL, 1 << 20, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); assert(gate != MAP_FAILED); + dm_gate_top[0] = (uintptr_t)gate + (1 << 20); + pthread_setspecific(g_keygate, dm_gate_stubs); + wait_test_invoke(before, after, guest_top); + munmap(gate, 1 << 20); + atomic_store(&guest_progress, 1); + return NULL; +} +static void activity(int paused) { uint64_t r[32] = {worker.handle, (uint64_t)paused}; assert(svc_thread(0x32, r) && !r[0]); } +static hz_ctx_t context(void) { + hz_ctx_t out; memset(&out, 0xcc, sizeof out); + uint64_t r[32] = {(uint64_t)&out, worker.handle}; assert(svc_thread(0x33, r) && !r[0]); return out; +} +static void check_context(const hz_ctx_t *c) { + for (int i = 0; i < 29; i++) assert(c->r[i] == (i == 18 ? UINT64_C(0x1818181818181818) : before[i])); + assert(c->fp == before[29] && c->lr == (uintptr_t)wait_test_return && c->pc == (uintptr_t)wait_test_return); + assert(c->sp == guest_top && c->pstate == before[96] && c->fpsr == before[97] && c->fpcr == before[98]); + assert(!memcmp(c->v, before + 32, sizeof c->v)); +} +int main(void) { + // A bounded test watchdog only; the implementation has no artificial timeout or forced resume. + alarm(20); + pthread_key_create(&g_key18, NULL); pthread_key_create(&g_keygate, NULL); svc_thread_main_init(); + size_t page = (size_t)sysconf(_SC_PAGESIZE); + unsigned char *memory = mmap(NULL, page * 2, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); assert(memory != MAP_FAILED); + assert(!mprotect(memory + page, page, PROT_READ | PROT_WRITE)); + memset(memory + page, 0xa5, page); + guest_bottom = (uintptr_t)memory + page; guest_top = guest_bottom + 8192; // exactly 8 KiB above the guard + for (int i = 0; i < 31; i++) before[i] = UINT64_C(0x1111000000000000) + i; + for (int i = 32; i < 96; i++) before[i] = UINT64_C(0x9999000000000000) + i; + before[96] = UINT64_C(0xa0000000); before[97] = 8; before[98] = UINT64_C(0x04000000); + pthread_cond_init(&worker.cv, NULL); pthread_cond_init(&worker.pcv, NULL); + worker.started = 1; worker.prio = 44; worker.core = 1; worker.mask = 2; + pthread_mutex_lock(&G); worker.handle = h_new(O_THREAD, &worker); worker.all = g_all; g_all = &worker; pthread_mutex_unlock(&G); + assert(!pthread_create(&worker.pt, NULL, run_worker, NULL)); + await_flag(&entered); + assert(atomic_load(&on_big_stack) && !memcmp(arguments, before, sizeof arguments)); + for (uintptr_t p = guest_bottom; p < guest_top - 32; p++) assert(*(unsigned char *)p == 0xa5); + activity(1); hz_ctx_t first = context(); check_context(&first); + pthread_mutex_lock(&G); assert(worker.svc_depth == 2 && atomic_load(&worker.svc_regs)); pthread_mutex_unlock(&G); + set_flag(&release_nested); usleep(20000); + pthread_mutex_lock(&M); assert(!nested_left); pthread_mutex_unlock(&M); + hz_ctx_t second = context(); assert(!memcmp(&first, &second, sizeof first)); + activity(0); await_flag(&nested_left); + activity(1); second = context(); check_context(&second); + set_flag(&finish_body); + while (!atomic_load(&body_returning)) sched_yield(); + usleep(20000); assert(!atomic_load(&guest_progress)); + second = context(); assert(!memcmp(&first, &second, sizeof first)); // returning x0 must not replace the captured first argument while paused + activity(0); assert(!pthread_join(worker.pt, NULL)); + assert(atomic_load(&guest_progress)); + assert(after[0] == result); + assert(after[18] == native_x18); // never write Apple's platform register; the guest's x18 is reported through its separate TSD slot + for (int i = 1; i < 30; i++) if (i != 18) assert(after[i] == before[i]); + assert(after[30] == (uintptr_t)wait_test_return && after[31] == guest_top); + assert(!memcmp(after + 32, before + 32, 64 * sizeof(uint64_t))); + assert(after[96] == before[96] && after[97] == before[97] && after[98] == before[98]); + assert(!worker.svc_depth && !atomic_load(&worker.svc_regs) && !atomic_load(&worker.svc_state)); + munmap(memory, page * 2); + puts("PASS: blocking hook context, nested pause/resume, immutable call roots, full register/SIMD ABI, 64-bit return and guarded 8 KiB guest stack"); + return 0; +} diff --git a/dm/host/tests/t_ldn.c b/dm/host/tests/t_ldn.c new file mode 100644 index 0000000000..d792541712 --- /dev/null +++ b/dm/host/tests/t_ldn.c @@ -0,0 +1,215 @@ +// Original protocol and service tests. The peer fixture uses loopback only; +// no broadcast, installed game, Switch, or external network is contacted. +#include "../hle_ldn.h" +#include +#ifdef DM_LDN_NET_TEST +#include "../net_socket.h" +void dm_guest_host_wait_begin(void) {} +void dm_guest_host_wait_end(void) {} +typedef struct { uint8_t len, family; uint16_t port; uint32_t ip; uint8_t reserved[8]; } guest_address; +static guest_address guest_addr(uint32_t ip, unsigned port) { return (guest_address){16,2,htons(port),ip,{0}}; } +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static unsigned checks; +#define CHECK(x) do { ++checks; if (!(x)) { fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #x); abort(); } } while (0) +static void pause_ms(unsigned ms) { usleep(ms * 1000); } +static dm_ldn_network_config config(void) { dm_ldn_network_config n = {0}; n.intent.local_id = 0x12345678; n.intent.scene = 17; n.max_nodes = 8; n.version = 5; return n; } +static dm_ldn_user user(const char *name) { dm_ldn_user u = {0}; snprintf(u.name, sizeof u.name, "%s", name); return u; } +static dm_ldn_security_config security(void) { dm_ldn_security_config s = {.mode = 1, .size = 16}; memset(s.passphrase, 42, 16); return s; } +static dm_ldn_network example(void) { + dm_ldn_network n = {0}; n.id.intent = config().intent; memset(n.id.session, 7, 16); n.common.ssid.len = 3; memcpy(n.common.ssid.text, "abc", 4); n.common.type = 2; n.common.channel = 6; n.max_nodes = 8; n.node_count = 1; + n.nodes[0].ip = 0x7f000001; n.nodes[0].mac[0] = 2; n.nodes[0].mac[5] = 1; n.nodes[0].connected = 1; n.nodes[0].version = 5; strcpy(n.nodes[0].name, "host"); return n; +} +static unsigned free_port(int type) { int fd = socket(AF_INET, type, 0); CHECK(fd >= 0); struct sockaddr_in a = {0}; a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); CHECK(!bind(fd, (struct sockaddr *)&a, sizeof a)); socklen_t len = sizeof a; CHECK(!getsockname(fd, (struct sockaddr *)&a, &len)); unsigned p = ntohs(a.sin_port); close(fd); return p; } +static dm_ldn_transport transport(unsigned port, unsigned host, int identity) { dm_ldn_transport t = {.address=htonl(INADDR_LOOPBACK), .mask=htonl(0xff000000), .discovery=htonl(INADDR_LOOPBACK), .bind_address=htonl(INADDR_LOOPBACK), .port=port, .discovery_port=host, .scan_ms=150, .connect_ms=1000}; t.mac[0] = 2; t.mac[5] = identity; return t; } +static int wait_nodes(dm_ldn_context *c, int count, dm_ldn_network *out) { for (int i = 0; i < 200; ++i) { if (!dm_ldn_get_network(c, out, NULL, 0) && out->node_count == count) return 1; pause_ms(5); } return 0; } +static void protocol(void) { + uint8_t packet[2048], changed[2048]; dm_ldn_network n = example(), out; unsigned type; + CHECK(dm_ldn_network_valid(&n)); CHECK(dm_ldn_packet_encode(packet, sizeof packet, 0, NULL, 0, 0) == 12); + CHECK(!memcmp(packet, "\0\x14\x45\x11\0\0\0\0\0\0\0\0", 12)); CHECK(dm_ldn_packet_decode(packet, 12, &type, NULL, 0) == 0 && type == 0); + for (unsigned p = 1; p <= 3; ++p) for (int compressed = 0; compressed <= 1; ++compressed) { + const void *data = p == 2 ? (void *)&n.nodes[0] : (void *)&n; unsigned size = p == 2 ? 64 : 1152; + int bytes = dm_ldn_packet_encode(packet, sizeof packet, p, data, size, compressed); CHECK(bytes > 12); CHECK(dm_ldn_packet_size(packet) == bytes); + CHECK(dm_ldn_packet_decode(packet, bytes, &type, &out, sizeof out) == (int)size && type == p); CHECK(!memcmp(&out, data, size)); + for (int i = 0; i < bytes; ++i) CHECK(dm_ldn_packet_decode(packet, i, &type, &out, sizeof out) < 0); + memcpy(changed, packet, bytes); changed[0] ^= 1; CHECK(dm_ldn_packet_decode(changed, bytes, &type, &out, sizeof out) < 0); + memcpy(changed, packet, bytes); changed[4] = 4; CHECK(dm_ldn_packet_decode(changed, bytes, &type, &out, sizeof out) < 0); + memcpy(changed, packet, bytes); changed[5] = 2; CHECK(dm_ldn_packet_decode(changed, bytes, &type, &out, sizeof out) < 0); + memcpy(changed, packet, bytes); changed[10] = 1; CHECK(dm_ldn_packet_decode(changed, bytes, &type, &out, sizeof out) < 0); + CHECK(dm_ldn_packet_decode(packet, bytes, &type, &out, size - 1) < 0); + } + // Exactly one zero run of 64 bytes is a valid compressed NodeInfo payload. + memset(packet, 0, sizeof packet); packet[1]=0x14; packet[2]=0x45; packet[3]=0x11; packet[4]=2; packet[5]=1; packet[6]=2; packet[8]=64; packet[13]=63; + CHECK(dm_ldn_packet_decode(packet, 14, &type, &out, sizeof out) == 64); + dm_ldn_node zeros = {0}; CHECK(dm_ldn_packet_encode(changed, sizeof changed, 2, &zeros, sizeof zeros, 1) == 14); CHECK(!memcmp(changed,packet,14)); + packet[13] = 64; CHECK(dm_ldn_packet_decode(packet, 14, &type, &out, sizeof out) < 0); packet[13] = 62; CHECK(dm_ldn_packet_decode(packet, 14, &type, &out, sizeof out) < 0); + packet[6] = 1; CHECK(dm_ldn_packet_decode(packet, 13, &type, &out, sizeof out) < 0); + CHECK(dm_ldn_packet_encode(packet, sizeof packet, 2, &n, 1152, 0) < 0); CHECK(dm_ldn_packet_encode(packet, 12, 1, &n, sizeof n, 0) < 0); + dm_ldn_filter f = {0}; CHECK(dm_ldn_filter_match(&n, &f, 0)); CHECK(!dm_ldn_filter_match(&n, &f, 1)); f.flags = 1; CHECK(!dm_ldn_filter_match(&n, &f, 0)); f.id.intent.local_id = n.id.intent.local_id; CHECK(dm_ldn_filter_match(&n, &f, 0)); + f.flags = 2; CHECK(!dm_ldn_filter_match(&n, &f, 0)); memcpy(f.id.session, n.id.session, 16); CHECK(dm_ldn_filter_match(&n, &f, 0)); + f.flags = 16; f.ssid = n.common.ssid; CHECK(dm_ldn_filter_match(&n, &f, 0)); f.ssid.text[0] = 'z'; CHECK(!dm_ldn_filter_match(&n, &f, 0)); + f.flags = 4; f.type = 3; f.ssid.len = 255; CHECK(dm_ldn_filter_match(&n,&f,0)); f.type = 1; CHECK(!dm_ldn_filter_match(&n,&f,0)); + f.flags = 64; CHECK(!dm_ldn_filter_match(&n, &f, 0)); n.node_count = 2; CHECK(!dm_ldn_network_valid(&n)); n = example(); n.advertise_size = 385; CHECK(!dm_ldn_network_valid(&n)); + n = example(); n.id.intent.local_id = -1; f = (dm_ldn_filter){.flags=1}; f.id.intent.local_id = -1; CHECK(dm_ldn_filter_match(&n,&f,0)); + // ldn_mitm deliberately preserves the caller's -1 communication ID. The + // Switch module compares this exact wire value, rather than NACP identity. + int encoded=dm_ldn_packet_encode(packet,sizeof packet,1,&n,sizeof n,1); CHECK(encoded>0); CHECK(dm_ldn_packet_decode(packet,encoded,&type,&out,sizeof out)==sizeof out && out.id.intent.local_id==-1); + // Malformed headers/runs and arbitrary bytes remain bounded under ASan. + uint32_t rng=0x12345678; for (int i=0;i<12000;++i) { memcpy(changed,packet,encoded); rng^=rng<<13; rng^=rng>>17; rng^=rng<<5; changed[rng%(unsigned)encoded]^=(uint8_t)(rng>>16); int result=dm_ldn_packet_decode(changed,encoded,&type,&out,sizeof out); CHECK(result<0 || result==sizeof out); } +} +static int raw_connect(unsigned port) { int fd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in a = {0}; a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); a.sin_port = htons(port); CHECK(fd >= 0 && !connect(fd, (struct sockaddr *)&a, sizeof a)); return fd; } +static int raw_read_frame(int fd, dm_ldn_network *out) { + uint8_t packet[2048]; size_t have = 0; int total = 12; + while (have < (size_t)total) { struct pollfd p = {fd, POLLIN, 0}; if (poll(&p, 1, 2000) <= 0) return -1; ssize_t n = recv(fd, packet + have, total - have, 0); if (n <= 0) return -1; have += n; if (have >= 12) { total = dm_ldn_packet_size(packet); if (total < 0) return -1; } } + unsigned type; return dm_ldn_packet_decode(packet, have, &type, out, sizeof *out) == sizeof *out && type == 3 ? 0 : -1; +} +static void local(void) { + unsigned port = free_port(SOCK_STREAM); dm_ldn_transport t = transport(port, port, 1); dm_ldn_context *host = dm_ldn_start(&t, NULL, NULL); CHECK(host); + CHECK(dm_ldn_state(host) == 1); CHECK(dm_ldn_open(host, 1) == 0); CHECK(dm_ldn_open(host, 0) != 0); + dm_ldn_network_config cfg = config(); dm_ldn_security_config sec = security(); dm_ldn_user u = user("host"); + CHECK(!dm_ldn_advertise(host, "initial", 7)); CHECK(!dm_ldn_create(host, &cfg, &sec, &u, NULL, 0, NULL)); CHECK(dm_ldn_state(host) == 3); + dm_ldn_network n; dm_ldn_update updates[8]; CHECK(!dm_ldn_get_network(host, &n, updates, 8)); CHECK(updates[0].change == 1); CHECK(n.advertise_size == 7 && !memcmp(n.advertise, "initial", 7)); + CHECK(!dm_ldn_get_network(host, &n, updates, 8)); CHECK(updates[0].change == 0); + // Split every byte of a compressed Connect frame across writes. A complete + // Sync follows only once the complete, valid peer announcement is received. + int fd = raw_connect(port); dm_ldn_node node = n.nodes[0]; strcpy(node.name, "raw peer"); node.mac[5] = 9; + uint8_t packet[2048]; int bytes = dm_ldn_packet_encode(packet, sizeof packet, 2, &node, sizeof node, 1); + for (int i = 0; i < bytes; ++i) CHECK(send(fd, packet+i, 1, 0) == 1); + CHECK(!raw_read_frame(fd, &n)); CHECK(n.node_count == 2 && n.nodes[1].id == 1); CHECK(!dm_ldn_get_network(host, &n, updates, 8)); CHECK(updates[1].change == 1); + CHECK(!dm_ldn_advertise(host, "actual bytes", 12)); CHECK(!raw_read_frame(fd, &n)); CHECK(n.advertise_size == 12 && !memcmp(n.advertise, "actual bytes", 12)); + close(fd); CHECK(wait_nodes(host, 1, &n)); CHECK(!dm_ldn_get_network(host, &n, updates, 8)); CHECK(updates[1].change == 2); + // Invalid TCP header / truncated connection must never publish a node. + fd = raw_connect(port); memset(packet, 0xff, 12); CHECK(send(fd, packet, 12, 0) == 12); struct pollfd p = {fd, POLLIN, 0}; CHECK(poll(&p, 1, 2000) > 0); CHECK(recv(fd, packet, 1, 0) <= 0); close(fd); CHECK(wait_nodes(host, 1, &n)); + fd = raw_connect(port); bytes = dm_ldn_packet_encode(packet, sizeof packet, 2, &node, sizeof node, 1); CHECK(send(fd, packet, bytes-1, 0) == bytes-1); close(fd); pause_ms(20); CHECK(wait_nodes(host, 1, &n)); + CHECK(dm_ldn_advertise(host, NULL, 1) != 0); CHECK(dm_ldn_advertise(host, packet, 385) != 0); CHECK(dm_ldn_policy(host, 4) != 0); + CHECK(!dm_ldn_policy(host, 1)); fd = raw_connect(port); p = (struct pollfd){fd,POLLIN,0}; CHECK(poll(&p,1,2000)>0); CHECK(recv(fd,packet,1,0)<=0); close(fd); + unsigned station_port=free_port(SOCK_DGRAM); dm_ldn_transport st=transport(station_port,port,2); dm_ldn_context *station=dm_ldn_start(&st,NULL,NULL); CHECK(station); CHECK(!dm_ldn_open(station,0)); + dm_ldn_filter f={.flags=1}; f.id.intent.local_id=123; dm_ldn_network rooms[24]; int count; CHECK(!dm_ldn_scan(station,rooms,&count,24,&f,0) && count==0); f.flags=0; CHECK(!dm_ldn_scan(station,rooms,&count,24,&f,0) && count==1); + dm_ldn_user su=user("policy station"); CHECK(dm_ldn_connect(station,rooms,&sec,&su,5,0)!=0); CHECK(dm_ldn_state(station)==4); + CHECK(!dm_ldn_policy(host,2)); CHECK(!dm_ldn_filter_add(host,st.mac)); CHECK(dm_ldn_connect(station,rooms,&sec,&su,5,0)!=0); CHECK(!dm_ldn_filter_clear(host)); + CHECK(!dm_ldn_connect(station,rooms,&sec,&su,5,0)); CHECK(wait_nodes(host,2,&n)); CHECK(!dm_ldn_reject(host,n.nodes[1].ip)); + int lost=0; for(int i=0;i<200;++i) { if(dm_ldn_state(station)==4) {lost=1;break;} pause_ms(5); } CHECK(lost); CHECK(wait_nodes(host,1,&n)); + CHECK(!dm_ldn_policy(host,3)); CHECK(dm_ldn_connect(station,rooms,&sec,&su,5,0)!=0); CHECK(!dm_ldn_filter_add(host,st.mac)); CHECK(!dm_ldn_connect(station,rooms,&sec,&su,5,0)); + CHECK(!dm_ldn_disconnect(host, 1)); CHECK(dm_ldn_state(host) == 2 && dm_ldn_reason(host) == 3); CHECK(!dm_ldn_close(host, 1)); CHECK(dm_ldn_state(host) == 1); + dm_ldn_stop(station); dm_ldn_stop(host); +} +static void peer_fixture(void) { + // Fork before creating either worker. Child and parent then own completely + // separate contexts, descriptors, locks and address-space snapshots. + int command[2], result[2]; CHECK(!pipe(command) && !pipe(result)); unsigned hp = free_port(SOCK_STREAM), sp = free_port(SOCK_DGRAM); + pid_t child = fork(); CHECK(child >= 0); + if (!child) { + close(command[1]); close(result[0]); dm_ldn_transport t = transport(hp,hp,1); dm_ldn_context *c = dm_ldn_start(&t,NULL,NULL); CHECK(c); CHECK(!dm_ldn_open(c,1)); dm_ldn_network_config cfg=config(); dm_ldn_security_config sec=security(); dm_ldn_user u=user("process host"); CHECK(!dm_ldn_create(c,&cfg,&sec,&u,NULL,0,NULL)); + CHECK(write(result[1],"R",1)==1); char b; + while (read(command[0],&b,1)==1) { + dm_ldn_network n; + if (b=='J') { CHECK(wait_nodes(c,2,&n)); CHECK(!strcmp(n.nodes[1].name,"process station")); CHECK(write(result[1],"J",1)==1); } + if (b=='A') { CHECK(!dm_ldn_advertise(c,"cross process",13)); CHECK(write(result[1],"A",1)==1); } +#ifdef DM_LDN_NET_TEST + if (b=='B') { + int data=dm_net_socket(2,2,0); CHECK(data>=0); guest_address a=guest_addr(htonl(INADDR_LOOPBACK),0); CHECK(!dm_net_bind(data,&a,sizeof a)); unsigned size=sizeof a; CHECK(!dm_net_name(data,&a,&size,0)); CHECK(write(result[1],&a.port,2)==2); + dm_net_pollfd ready={data,1,0}; CHECK(dm_net_poll(&ready,1,2000)==1); char payload[32]; guest_address from; size=sizeof from; + CHECK(dm_net_recv(data,payload,sizeof payload,0,&from,&size)==18 && !memcmp(payload,"guest game request",18)); CHECK(dm_net_send(data,"guest game reply",16,0,&from,size)==16); CHECK(!dm_net_close(data)); CHECK(write(result[1],"B",1)==1); + } +#endif + if (b=='D') { CHECK(wait_nodes(c,1,&n)); CHECK(write(result[1],"D",1)==1); } + if (b=='X') break; + } + dm_ldn_stop(c); close(command[0]); close(result[1]); _exit(0); + } + close(command[0]);close(result[1]); char b; CHECK(read(result[0],&b,1)==1 && b=='R'); dm_ldn_transport t=transport(sp,hp,2); dm_ldn_context *c=dm_ldn_start(&t,NULL,NULL); CHECK(c); CHECK(!dm_ldn_open(c,0)); + dm_ldn_filter f={.flags=33}; f.id.intent=config().intent; dm_ldn_network rooms[24], n; int count; CHECK(!dm_ldn_scan(c,rooms,&count,24,&f,0)); CHECK(count==1 && !strcmp(rooms[0].nodes[0].name,"process host")); + dm_ldn_security_config sec=security(); dm_ldn_user u=user("process station"); CHECK(dm_ldn_connect(c,&rooms[0],&sec,&u,4,0)!=0); CHECK(dm_ldn_state(c)==4); + CHECK(!dm_ldn_connect(c,&rooms[0],&sec,&u,5,0)); CHECK(dm_ldn_state(c)==5); CHECK(!dm_ldn_get_network(c,&n,NULL,0) && n.node_count==2); + CHECK(write(command[1],"J",1)==1); CHECK(read(result[0],&b,1)==1 && b=='J'); CHECK(write(command[1],"A",1)==1); CHECK(read(result[0],&b,1)==1 && b=='A'); + int synced=0; for(int i=0;i<200;++i) { if (!dm_ldn_get_network(c,&n,NULL,0) && n.advertise_size==13 && !memcmp(n.advertise,"cross process",13)) {synced=1;break;} pause_ms(5); } CHECK(synced); +#ifdef DM_LDN_NET_TEST + // After discovery/control, game datagrams traverse the actual Horizon + // socket translator, using the address learned from the remote NodeInfo. + CHECK(write(command[1],"B",1)==1); uint16_t port; CHECK(read(result[0],&port,2)==2); int data=dm_net_socket(2,2,0); CHECK(data>=0); + guest_address a=guest_addr(htonl(n.nodes[0].ip),ntohs(port)); CHECK(dm_net_send(data,"guest game request",18,0,&a,sizeof a)==18); + dm_net_pollfd ready={data,1,0}; CHECK(dm_net_poll(&ready,1,2000)==1); char payload[32]; CHECK(dm_net_recv(data,payload,sizeof payload,0,NULL,NULL)==16 && !memcmp(payload,"guest game reply",16)); CHECK(!dm_net_close(data)); CHECK(read(result[0],&b,1)==1 && b=='B'); +#endif + CHECK(!dm_ldn_disconnect(c,0)); CHECK(dm_ldn_state(c)==4 && dm_ldn_reason(c)==1); CHECK(write(command[1],"D",1)==1); CHECK(read(result[0],&b,1)==1 && b=='D'); + // Reconnect, then observe an actual EOF from the host worker shutting down. + CHECK(!dm_ldn_scan(c,rooms,&count,24,&f,0) && count==1); CHECK(!dm_ldn_connect(c,&rooms[0],&sec,&u,5,0)); CHECK(write(command[1],"X",1)==1); int status; CHECK(waitpid(child,&status,0)==child && WIFEXITED(status) && WEXITSTATUS(status)==0); + int lost=0; for(int i=0;i<200;++i) { if(dm_ldn_state(c)==4) {lost=1;break;} pause_ms(5); } CHECK(lost && dm_ldn_reason(c)==6); CHECK(dm_ldn_get_network(c,&n,NULL,0)!=0); + dm_ldn_stop(c); close(command[1]);close(result[0]); +} +#ifdef DM_NET_TEST +static _Atomic unsigned ldn_discovery_calls; +static unsigned ldn_discovery_error_at; +static long ldn_host_down(int fd,const void *bytes,size_t size,int flags,uint32_t address,uint16_t port) { + (void)address;unsigned call=atomic_fetch_add(&ldn_discovery_calls,1); + if(call==ldn_discovery_error_at) { errno=EHOSTDOWN;return -1; } + struct sockaddr_in to={.sin_len=sizeof to,.sin_family=AF_INET,.sin_port=port,.sin_addr={htonl(INADDR_LOOPBACK)}}; + return sendto(fd,bytes,size,flags,(struct sockaddr *)&to,sizeof to); +} +static void automatic_discovery(void) { + dm_net_set_multicast_allowed(0); unsetenv("DM_NET_DISCOVERY_PEER"); + // The only reachable loopback neighbor is 127.0.0.1. The validated adapter + // fixture's /24 makes the worker send the unchanged scan via unicast. + dm_net_test_interface adapter={htonl(0x7f000002),htonl(0xffffff00),if_nametoindex("lo0"),IFF_UP|IFF_BROADCAST,1}; + CHECK(adapter.index); dm_net_test_set_interface(&adapter); + unsigned hp=free_port(SOCK_DGRAM),sp=free_port(SOCK_DGRAM); + dm_ldn_transport ht=transport(hp,hp,1),st=transport(sp,hp,2); + st.address=adapter.address;st.mask=adapter.mask;st.discovery=st.address|~st.mask; + dm_ldn_context *host=dm_ldn_start(&ht,NULL,NULL),*station=dm_ldn_start(&st,NULL,NULL); CHECK(host && station); + CHECK(!dm_ldn_open(host,1) && !dm_ldn_open(station,0)); + dm_ldn_network_config cfg=config();dm_ldn_security_config sec=security();dm_ldn_user owner=user("auto host"); + CHECK(!dm_ldn_create(host,&cfg,&sec,&owner,NULL,0,NULL)); + dm_ldn_filter filter={0};dm_ldn_network rooms[24];int count=0; + CHECK(!dm_ldn_scan(station,rooms,&count,24,&filter,0)); + CHECK(count==1 && !strcmp(rooms[0].nodes[0].name,"auto host") && rooms[0].nodes[0].ip==INADDR_LOOPBACK); + dm_ldn_stop(station); + // Destination-specific EHOSTDOWN must be skipped both at the first + // neighbor and after a successful send in the worker's sweep. + for(unsigned fault=0;fault<2;++fault) { + dm_net_set_multicast_allowed(0);station=dm_ldn_start(&st,NULL,NULL);CHECK(station);CHECK(!dm_ldn_open(station,0)); + ldn_discovery_error_at=fault;atomic_store(&ldn_discovery_calls,0);dm_net_test_set_discovery_sender(ldn_host_down); + CHECK(!dm_ldn_scan(station,rooms,&count,24,&filter,0)&&count==1&&atomic_load(&ldn_discovery_calls)>fault+1); + dm_net_test_set_discovery_sender(NULL);dm_ldn_stop(station); + } + // A capable native sender keeps its original destination and also probes + // restricted peers. The logical loopback broadcast itself reaches no peer; + // finding this real host therefore requires the complementary unicast. + dm_net_set_multicast_allowed(1);station=dm_ldn_start(&st,NULL,NULL);CHECK(station);CHECK(!dm_ldn_open(station,0)); + CHECK(!dm_ldn_scan(station,rooms,&count,24,&filter,0));CHECK(count==1&&dm_net_multicast_allowed()==1); + dm_ldn_stop(station); + // The same error on the original native broadcast remains visible and + // must not launch a complementary sweep to the reachable host. + station=dm_ldn_start(&st,NULL,NULL);CHECK(station);CHECK(!dm_ldn_open(station,0)); + ldn_discovery_error_at=0;atomic_store(&ldn_discovery_calls,0);dm_net_test_set_discovery_sender(ldn_host_down); + CHECK(dm_ldn_scan(station,rooms,&count,24,&filter,0)!=0&&count==0&&atomic_load(&ldn_discovery_calls)==1); + dm_net_test_set_discovery_sender(NULL);dm_ldn_stop(station); + // Create the actual native socket without SO_BROADCAST, then simulate a + // claimed capability. The kernel refuses native broadcast: supplemental + // unicast must not hide that error by discovering the otherwise reachable host. + dm_net_set_multicast_allowed(0);st.discovery=htonl(UINT32_MAX);station=dm_ldn_start(&st,NULL,NULL);CHECK(station);CHECK(!dm_ldn_open(station,0)); + dm_net_set_multicast_allowed(1);CHECK(dm_ldn_scan(station,rooms,&count,24,&filter,0)!=0&&count==0); + dm_ldn_stop(station);dm_ldn_stop(host);dm_net_test_set_interface(NULL);dm_net_set_multicast_allowed(1); +} +#endif +int main(void) { +#ifdef DM_LDN_NET_TEST + setenv("DM_NETWORK","ldn",1); CHECK(dm_net_enabled()); +#endif + protocol(); local(); peer_fixture(); +#ifdef DM_NET_TEST + automatic_discovery(); +#endif + printf("LDN: %u checks passed (protocol, malformed streams, real two-process discovery/session).\n",checks); return 0; +} diff --git a/dm/host/tests/t_ldn_events.c b/dm/host/tests/t_ldn_events.c new file mode 100644 index 0000000000..56f386b93d --- /dev/null +++ b/dm/host/tests/t_ldn_events.c @@ -0,0 +1,69 @@ +// Test the production LDN event/lifetime bodies. Only the AArch64 registration +// stubs are replaced with direct C calls (their ABI is covered by t_hle_wait). +// No socket is opened; the kernel-event binding fixture models close/reuse. +#include "../hle.h" +#undef HLE_FORCE +#undef HLE_FORCE_WAIT +#define HLE_FORCE(name, why, ret, cname, ...) static ret cname(__VA_ARGS__) +#define HLE_FORCE_WAIT HLE_FORCE +#include "../hle_ldn.c" +#include +#include + +typedef struct { void *address; uint64_t id; unsigned signals; int active; } test_event; +static test_event events[80]; +static unsigned count; +static __thread int waits; +static _Atomic unsigned wait_entries; +void dm_guest_host_wait_begin(void) { ++waits; atomic_fetch_add(&wait_entries,1); } +void dm_guest_host_wait_end(void) { --waits; assert(waits >= 0); } +void hle_bind_system_event(void *address, int autoclear) { + assert(autoclear == 1); + for (unsigned i = 0; i < count; ++i) if (events[i].address == address && events[i].active) return; + assert(count < 80); events[count] = (test_event){address, count + 1, 0, 1}; ++count; +} +uint64_t hle_system_event_binding(void *address) { for (unsigned i = count; i-- > 0;) if (events[i].address == address && events[i].active) return events[i].id; return 0; } +int hle_signal_system_event_binding(uint64_t id) { for (unsigned i = 0; i < count; ++i) if (events[i].id == id && events[i].active) { ++events[i].signals; return 1; } return 0; } +int dm_net_ipconfig(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e) { (void)a;(void)b;(void)c;(void)d;(void)e; return -1; } +int dm_net_discovery_target(uint32_t broadcast, uint32_t *target) { *target=broadcast; return 0; } +int dm_net_discovery_prepare(uint32_t destination, dm_net_discovery_plan *plan) { *plan=(dm_net_discovery_plan){.target=destination,.count=1}; return 0; } +int dm_net_discovery_supplement(uint32_t destination,dm_net_discovery_plan *plan) { (void)destination;memset(plan,0,sizeof *plan);return 0; } +long dm_net_discovery_send_native(int fd,const void *bytes,size_t size,int flags,uint32_t address,uint16_t port) { + struct sockaddr_in to={.sin_len=sizeof to,.sin_family=AF_INET,.sin_addr={address},.sin_port=port};return sendto(fd,bytes,size,flags,(struct sockaddr *)&to,sizeof to); +} +int dm_net_errno(void) { return 13; } +int dm_net_multicast_allowed(void) { return 0; } +static void *read_during_finalize(void *argument) { + int which=(int)(uintptr_t)argument; Result r; + if(which) { dm_ldn_security_parameter out; r=h_ldn_Security(&out); } + else { dm_ldn_network_config out; r=h_ldn_Config(&out); } + assert(r!=0 && waits==0);return NULL; +} +static void getter_lifetime(int which) { + // Hold Finalize's writer lock and the native context mutex. A getter must + // request the lifetime reader lock before it can touch the native mutex. + // Then remove the context exactly as Finalize does; the getter resumes + // with an unavailable result, without dereferencing freed memory. + dm_ldn_context *c=calloc(1,sizeof *c);assert(c);pthread_mutex_init(&c->lock,NULL);c->state=LDN_CREATED; + pthread_rwlock_wrlock(&g_ldn_lock);pthread_mutex_lock(&c->lock);g_ldn=c;atomic_store(&wait_entries,0); + pthread_t thread;assert(!pthread_create(&thread,NULL,read_during_finalize,(void *)(uintptr_t)which)); + for(int i=0;i<400 && !atomic_load(&wait_entries);++i)usleep(5000); + assert(atomic_load(&wait_entries)>0);g_ldn=NULL;pthread_mutex_unlock(&c->lock);pthread_mutex_destroy(&c->lock);free(c); + pthread_rwlock_unlock(&g_ldn_lock);assert(!pthread_join(thread,NULL)); +} + +int main(void) { + uint8_t storage[3][128]; + h_ldn_Attach(storage[0]); h_ldn_Attach(storage[1]); h_ldn_Attach(storage[0]); + assert(count == 2); ldn_event(NULL); assert(events[0].signals == 1 && events[1].signals == 1); + events[0].active = 0; h_ldn_Attach(storage[0]); assert(count == 3); + ldn_event(NULL); assert(events[0].signals == 1 && events[1].signals == 2 && events[2].signals == 1); + // An event attached after Finalize receives a fresh binding lifetime; + // previously attached still-open kernel objects are no longer producers. + h_ldn_Fini(); assert(!waits); ldn_event(NULL); assert(events[1].signals == 2 && events[2].signals == 1); + h_ldn_Attach(storage[2]); ldn_event(NULL); assert(events[3].signals == 1 && events[1].signals == 2); + getter_lifetime(0);getter_lifetime(1); + setenv("DM_NETWORK", "offline", 1); assert(h_ldn_Init() == LDN_ERROR(22)); assert(h_ldn_State() == 0 && waits == 0); + setenv("DM_NETWORK", "auto", 1); assert(ldn_enabled()); + puts("LDN event close/reuse, observers, concurrent getter/Finalize and offline state passed."); return 0; +} diff --git a/dm/host/tests/t_mii_sysdata.c b/dm/host/tests/t_mii_sysdata.c index e4593567f9..65cec8cd59 100644 --- a/dm/host/tests/t_mii_sysdata.c +++ b/dm/host/tests/t_mii_sysdata.c @@ -3,6 +3,7 @@ // MiiResource: and, refused, crashed later reading a texture file's part sizes through a null pointer. Expectations are written from the games' readers, not from this code #include "../hle_fs.c" #include "../hle_mii.c" +#include "bcat_absent.h" // hle_fs.c weak-imports the BCAT provider (nextendo_bcat.h), which this test does not link #include #include struct dm_flags g_flag; uint64_t g_t0_ns; diff --git a/dm/host/tests/t_net.c b/dm/host/tests/t_net.c new file mode 100644 index 0000000000..a5e0c60f2a --- /dev/null +++ b/dm/host/tests/t_net.c @@ -0,0 +1,353 @@ +// Exercise the actual guest-facing HLE_FORCE entries, with real Darwin sockets as the peer. +// Link hle_net.c, hle_offline.c, hle_net_backend.c, hle_bigstack.c and entry.S with a generated game_profile.h include path. +#include "../hle.h" +#include "../net_socket.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +__thread _Atomic int dm_host_work; // dm.h: hle_net.c's local service takes its lock with dm_host_mutex_lock, as the other socket tests define it + +pthread_key_t g_keygate; +extern uint64_t dm_gate_top[1024]; +extern const unsigned char dm_gate_stubs[]; +void dm_gate_nested(uint64_t sp) { (void)sp; abort(); } +static _Atomic unsigned test_gate_next; +static void *test_gate_stack(void) { + unsigned slot = atomic_fetch_add(&test_gate_next, 1); assert(slot < 1024); + void *stack = mmap(NULL, 1 << 20, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + assert(stack != MAP_FAILED); + dm_gate_top[slot] = (uintptr_t)stack + (1 << 20); + pthread_setspecific(g_keygate, dm_gate_stubs + 16 * slot); + return stack; +} +__attribute__((constructor)) static void test_gate_key(void) { pthread_key_create(&g_keygate, NULL); (void)test_gate_stack(); } +struct test_start { void *(*fn)(void *); void *arg; }; +static void *test_thread_start(void *p) { + struct test_start start = *(struct test_start *)p; free(p); + void *stack = test_gate_stack(), *value = start.fn(start.arg); + munmap(stack, 1 << 20); return value; +} +static int test_pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*fn)(void *), void *arg) { + struct test_start *start = malloc(sizeof *start); assert(start); *start = (struct test_start){fn,arg}; + int status = pthread_create(thread, attr, test_thread_start, start); if (status) free(start); return status; +} +#define pthread_create test_pthread_create +static int checks, failures; +static _Atomic int waits, wait_balance; +static _Atomic int contexts_entered, contexts_left, invalid_contexts; +static __thread int context_depth; +static volatile sig_atomic_t sigpipe_count; +static int resolver_abi; +static void sigpipe(int signal) { (void)signal; sigpipe_count++; } +#define CHECK(c, message) do { checks++; if (!(c)) { failures++; fprintf(stderr, "FAIL line %d: %s (guest errno=%d host errno=%d)\n", __LINE__, message, dm_net_errno(), errno); abort(); } } while (0) +void dm_guest_host_wait_begin(void) { atomic_fetch_add(&waits, 1); atomic_fetch_add(&wait_balance, 1); } +void dm_guest_host_wait_end(void) { atomic_fetch_sub(&wait_balance, 1); } +uint64_t now_ns(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000000000 + t.tv_nsec; } +void dm_guest_sleep_ns(int64_t ns) { struct timespec t = {ns / 1000000000, ns % 1000000000}; dm_guest_host_wait_begin(); nanosleep(&t, NULL); dm_guest_host_wait_end(); } +// The offline EventFd waits in hle_net.c (hle_thread.c and hle_os.c in the host) +void dm_guest_cond_wait_ns(pthread_cond_t *c, pthread_mutex_t *m, int64_t ns) { struct timespec t = {ns / 1000000000, ns % 1000000000}; dm_guest_host_wait_begin(); pthread_cond_timedwait_relative_np(c, m, &t); dm_guest_host_wait_end(); } +uint64_t guest_ns(void) { return now_ns(); } +int dm_detclock_enabled(void) { return 0; } +void hle_bind_system_event(void *p, int clear) { (void)p; (void)clear; } +void hle_signal_system_event(void *p) { (void)p; } +void dm_applet_enter(const char *name) { (void)name; } +void dm_applet_leave(void) {} +void thr_svc_enter(uint64_t *registers, uint64_t pc) { if (!registers || !pc || context_depth) atomic_fetch_add(&invalid_contexts, 1); context_depth++; atomic_fetch_add(&contexts_entered, 1); } +void thr_svc_leave(void) { if (context_depth != 1) atomic_fetch_add(&invalid_contexts, 1); context_depth--; atomic_fetch_add(&contexts_left, 1); } +int dm_guest_as_contains(uintptr_t address) { (void)address; return 0; } +uint64_t gate_dispatch(uint64_t ret, uint64_t *registers) { (void)ret; (void)registers; abort(); } +uint64_t unimpl_c(unsigned index, uint64_t *registers) { (void)index; (void)registers; abort(); } +void dm_thread_returned(void) { abort(); } +static int guest_errno; // the game's own errno (its C library's __errno_location), which a failed socket call sets as Horizon's nn::socket does +static int *guest_errno_location(void) { return &guest_errno; } +void *guest_sym(const char *name) { + if (!strcmp(name, "__errno_location")) return (void *)guest_errno_location; + if (strstr(name, "GetAddrInfoEPKcS2_PK8addrinfoPPS3_")) return resolver_abi != 1 ? (void *)1 : NULL; + if (strstr(name, "GetAddrInfoEPKcS2_PKNS0_8AddrInfoEPPS3_")) return resolver_abi != 0 ? (void *)1 : NULL; + return NULL; +} + +static void *hook(const char *name) { + unsigned long bytes; const hle_force_ent *p = (const hle_force_ent *)getsectiondata(&_mh_execute_header, "__DATA", "swforce", &bytes); + for (unsigned long i = 0; p && i < bytes / sizeof *p; i++) if (!strcmp(p[i].name, name)) return p[i].fn; + fprintf(stderr, "Missing hook: %s\n", name); abort(); +} +typedef int (*fn_socket)(int, int, int); +typedef int (*fn_bind)(int, const void *, unsigned); +typedef int (*fn_name)(int, void *, unsigned *); +typedef int (*fn_int)(int); +typedef int (*fn_fcntl)(int, int, int); +typedef long (*fn_sendto)(int, const void *, unsigned long, int, const void *, unsigned); +typedef long (*fn_recvfrom)(int, void *, unsigned long, int, void *, unsigned *); +typedef int (*fn_option)(int, int, int, const void *, unsigned); +typedef int (*fn_getoption)(int, int, int, void *, unsigned *); +typedef int (*fn_poll)(void *, unsigned long, int); +typedef int (*fn_select)(int, void *, void *, void *, void *); +typedef int (*fn_void)(void); +typedef void (*fn_vvoid)(void); +typedef struct { uint8_t len, family; uint16_t port; uint32_t ip; uint8_t padding[8]; } address; +#define GET(type, symbol) ((type)hook(symbol)) +#define SOCKET GET(fn_socket, "_ZN2nn6socket6SocketEiii") +#define BIND GET(fn_bind, "_ZN2nn6socket4BindEiPK8sockaddrj") +#define NAME GET(fn_name, "_ZN2nn6socket11GetSockNameEiP8sockaddrPj") +#define PEER GET(fn_name, "_ZN2nn6socket11GetPeerNameEiP8sockaddrPj") +#define CLOSE GET(fn_int, "_ZN2nn6socket5CloseEi") +#define FCNTL GET(fn_fcntl, "_ZN2nn6socket5FcntlEiiz") +#define SEND GET(fn_sendto, "_ZN2nn6socket6SendToEiPKvmiPK8sockaddrj") +#define RECV GET(fn_recvfrom, "_ZN2nn6socket8RecvFromEiPvmiP8sockaddrPj") +#define SETOPT GET(fn_option, "_ZN2nn6socket10SetSockOptEiiiPKvj") +#define GETOPT GET(fn_getoption, "_ZN2nn6socket10GetSockOptEiiiPvPj") +#define POLL GET(fn_poll, "_ZN2nn6socket4PollEP6pollfdmi") +#define SELECT GET(fn_select, "_ZN2nn6socket6SelectEiP6fd_setS2_S2_P7timeval") +static address addr(uint32_t ip, uint16_t port) { return (address){16, 2, htons(port), ip, {0}}; } +static int native_udp(address *a) { + int fd = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in in = {.sin_len = sizeof in, .sin_family = AF_INET, .sin_addr.s_addr = a->ip, .sin_port = a->port}; + CHECK(fd >= 0 && bind(fd, (struct sockaddr *)&in, sizeof in) == 0, "native UDP peer bound"); + socklen_t n = sizeof in; CHECK(getsockname(fd, (struct sockaddr *)&in, &n) == 0, "native peer port"); a->port = in.sin_port; return fd; +} +static void offline(void) { + unsetenv("DM_NETWORK"); + CHECK(!dm_net_enabled() && SOCKET(2, 1, 6) == -1, "offline remains the default, no TCP socket created (UDP is the local service, t_net_loopback)"); + CHECK(GET(fn_void, "_ZN2nn6socket12GetLastErrnoEv")() == 100, "offline reports actual Horizon ENETDOWN"); + CHECK(GET(fn_void, "_ZN2nn4nifm18IsNetworkAvailableEv")() == 0, "offline NIFM unavailable"); + fn_void on_hold = GET(fn_void, "_ZN2nn4nifm22IsNetworkRequestOnHoldEv"); on_hold(); + GET(fn_vvoid, "_ZN2nn4nifm20SubmitNetworkRequestEv")(); + CHECK(on_hold() == 1, "offline retains asynchronous request hold"); + dm_guest_sleep_ns(60000000); + CHECK(GET(fn_void, "_ZN2nn4nifm22IsNetworkRequestOnHoldEv")() == 0 && !dm_nifm_available(), "offline request settles as unavailable"); + CHECK(POLL(NULL, 0, 2) == 0, "offline idle poll remains a timed wait"); + pid_t child = fork(); + if (child == 0) { POLL(NULL, 0, -1); _exit(91); } + CHECK(child > 0, "start infinite offline poll in isolated child"); + if (child > 0) { dm_guest_sleep_ns(150000000); int status = 0; CHECK(waitpid(child, &status, WNOHANG) == 0, "infinite offline poll never returns a fabricated100ms timeout"); kill(child, SIGTERM); CHECK(waitpid(child, &status, 0) == child && WIFSIGNALED(status), "external process shutdown ends the infinite wait"); } +} +static void nifm(void) { + setenv("DM_NETWORK", "auto", 1); setenv("DM_NETWORK_INTERFACE", "lo0", 1); + GET(fn_vvoid, "_ZN2nn4nifm27SubmitNetworkRequestAndWaitEv")(); + CHECK(dm_nifm_available(), "NIFM automatic request completes with real up interface"); + uint32_t ip = 0, mask = 0, router = 1, dns1 = 0, dns2 = 0; + CHECK(dm_net_ipconfig(&ip, &mask, &router, &dns1, &dns2) == 0 && ip == htonl(0x7f000001) && mask == htonl(0xff000000) && router == 0, "actual loopback IP/mask and no invented router"); + setenv("DM_NETWORK_INTERFACE", "no-such-interface", 1); + CHECK(dm_net_ipconfig(&ip, NULL, NULL, NULL, NULL) < 0 && ip == 0 && !dm_nifm_available(), "missing interface does not claim connectivity"); + setenv("DM_NETWORK_INTERFACE", "lo0", 1); + GET(fn_vvoid, "_ZN2nn4nifm20CancelNetworkRequestEv")(); CHECK(!dm_nifm_available(), "cancel clears the request state"); + uint8_t proxy[0xac]; memset(proxy, 0x5a, sizeof proxy); + CHECK(GET(uint32_t (*)(void *), "_ZN2nn4nifm22GetCurrentProxySettingEPNS0_12ProxySettingE")(proxy) == 0 && !proxy[0] && !proxy[0xa9] && proxy[0xaa] == 0x5a, + "a network mode answers the proxy setting as a console without a proxy: 0xaa zero bytes, nothing past them"); +} +static void udp(void) { + int guest = SOCKET(2, 2, 17); address local = addr(htonl(0x7f000001), 0), peer = local; + CHECK(guest >= 0 && BIND(guest, &local, sizeof local) == 0, "guest UDP socket binds"); + unsigned n = sizeof local; CHECK(NAME(guest, &local, &n) == 0 && n == 16 && local.port != 0, "guest UDP actual bound address"); + struct { uint8_t bytes[3], guard; } short_address = {{0}, 0xa5}; n = 3; + CHECK(NAME(guest, &short_address, &n) == 0 && n == 16 && short_address.guard == 0xa5, "truncated sockaddr writes only the caller capacity and reports full length"); + int native = native_udp(&peer); + CHECK(SEND(guest, "guest", 5, 0, &peer, 16) == 5, "guest UDP transmits to a native socket"); + char bytes[32] = {0}; struct sockaddr_in sender; socklen_t size = sizeof sender; + CHECK(recvfrom(native, bytes, sizeof bytes, 0, (struct sockaddr *)&sender, &size) == 5 && !memcmp(bytes, "guest", 5), "native peer received exact guest bytes"); + CHECK(sendto(native, "host", 4, 0, (struct sockaddr *)&sender, size) == 4, "native peer replies"); + dm_net_pollfd p = {guest, 1, 0}; CHECK(POLL(&p, 1, 1000) == 1 && (p.revents & 1), "poll translates readable event"); + address from = {0}; n = sizeof from; CHECK(RECV(guest, bytes, sizeof bytes, 2, &from, &n) == 4 && from.port == peer.port, "peek returns source without consuming"); + CHECK(RECV(guest, bytes, sizeof bytes, 0, NULL, NULL) == 4 && !memcmp(bytes, "host", 4), "guest consumes native datagram"); + CHECK(FCNTL(guest, 4, 0x800) == 0 && FCNTL(guest, 3, 0) == 0x800, "nonblock flag translated from Horizon0x800"); + CHECK(FCNTL(guest, 4, 0x802) == 0 && FCNTL(guest, 3, 0) == 0x800, "NEX read/write access bits do not invalidate F_SETFL"); + CHECK(RECV(guest, bytes, sizeof bytes, 0, NULL, NULL) < 0 && dm_net_errno() == 11, "nonblock recv reports Horizon EAGAIN11"); + CHECK(FCNTL(guest, 4, 2) == 0 && FCNTL(guest, 3, 0) == 0, "read/write bits alone restore blocking mode without changing native ownership"); + CHECK(RECV(guest, bytes, sizeof bytes, 0x80, NULL, NULL) < 0 && dm_net_errno() == 11, "per-call DONTWAIT0x80 translated"); + uint32_t timeout = 25; CHECK(SETOPT(guest, 0xffff, 0x1006, &timeout, 4) == 0, "receive timeout milliseconds accepted"); + uint64_t start = now_ns(); CHECK(RECV(guest, bytes, sizeof bytes, 0, NULL, NULL) < 0 && dm_net_errno() == 11 && now_ns() - start >= 20000000, "blocking recv timeout waits and reports EAGAIN"); + timeout = 0; CHECK(SETOPT(guest, 0xffff, 0x1006, &timeout, 4) == 0, "timeout cleared"); + timeout = 123; n = 4; CHECK(GETOPT(guest, 0xffff, 0x1006, &timeout, &n) == 0 && timeout == 0, "zero timeout roundtrips as infinite, never uint32 minus one"); + int one = 1, value = 0; n = 4; CHECK(SETOPT(guest, 0xffff, 0x20, &one, 4) == 0 && GETOPT(guest, 0xffff, 0x20, &value, &n) == 0 && value, "broadcast option is real"); + uint64_t read[16] = {0}, write[16] = {0}; read[guest >> 6] |= 1ull << (guest & 63); write[guest >> 6] |= 1ull << (guest & 63); int64_t tv[2] = {0, 0}; + CHECK(SELECT(guest + 1, read, write, NULL, tv) == 1 && !read[guest >> 6] && write[guest >> 6], "select fd_set layout and output bits translated"); + // gRPC's reads and writes: SendMsg gathers its iovecs into one datagram, RecvMsg scatters one into its iovecs and reports the sender (Horizon's 0x30-byte msghdr) + typedef struct { void *base; uint64_t len; } iovec_h; typedef struct { void *name; uint32_t namelen, pad0; iovec_h *iov; int32_t iovlen, pad1; void *control; uint32_t controllen; int32_t flags; } msghdr_h; + typedef long (*fn_msg)(int, void *, int); + iovec_h out_iov[2] = {{"abc", 3}, {"defg", 4}}; msghdr_h out_msg = {&peer, 16, 0, out_iov, 2, 0, NULL, 0, 0}; + CHECK(GET(fn_msg, "nnsocketSendMsg")(guest, &out_msg, 0) == 7, "SendMsg gathers two iovecs"); + size = sizeof sender; CHECK(recvfrom(native, bytes, sizeof bytes, 0, (struct sockaddr *)&sender, &size) == 7 && !memcmp(bytes, "abcdefg", 7), "native peer received the gathered bytes in order"); + CHECK(sendto(native, "scatter", 7, 0, (struct sockaddr *)&sender, size) == 7, "native peer replies for RecvMsg"); + char head[3] = {0}, tail[10] = {0}; iovec_h in_iov[2] = {{head, 3}, {tail, 10}}; address src = {0}; uint8_t control[8]; + msghdr_h in_msg = {&src, sizeof src, 0, in_iov, 2, 0, control, sizeof control, 0x55}; + CHECK(GET(fn_msg, "nnsocketRecvMsg")(guest, &in_msg, 0) == 7 && !memcmp(head, "sca", 3) && !memcmp(tail, "tter", 4) && in_msg.namelen == 16 && src.port == peer.port && !in_msg.controllen && !in_msg.flags, + "RecvMsg scatters one datagram, reports its sender and no ancillary data"); + out_msg.control = control; out_msg.controllen = sizeof control; CHECK(GET(fn_msg, "nnsocketSendMsg")(guest, &out_msg, 0) < 0 && dm_net_errno() == 95, "SendMsg refuses ancillary data rather than drop it"); + out_msg.control = NULL; out_msg.controllen = 0; out_msg.iovlen = -1; CHECK(GET(fn_msg, "nnsocketSendMsg")(guest, &out_msg, 0) < 0 && dm_net_errno() == 22, "SendMsg rejects a negative iovec count"); + out_msg.iovlen = 2; out_iov[1].len = 1ull << 40; + CHECK(GET(fn_msg, "nnsocketSendMsg")(guest, &out_msg, 0) < 0 && dm_net_errno() == 40, "a datagram over the message limit fails with EMSGSIZE before its iovecs are read"); out_iov[1].len = 4; + CHECK(sendto(native, "truncated", 9, 0, (struct sockaddr *)&sender, size) == 9, "native peer sends a datagram longer than the iovecs"); + char small[4] = {0}; iovec_h small_iov = {small, 4}; msghdr_h cut = {NULL, 0, 0, &small_iov, 1, 0, NULL, 0, 0}; + CHECK(GET(fn_msg, "nnsocketRecvMsg")(guest, &cut, 0) == 4 && !memcmp(small, "trun", 4) && cut.flags == 0x10, "a datagram longer than the iovecs is cut to them and reports MSG_TRUNC"); + int first_close = CLOSE(guest), repeated_close = CLOSE(guest); + CHECK(first_close == 0 && repeated_close < 0 && dm_net_errno() == 9, "close owns guest socket only, second close EBADF"); + close(native); +} +typedef struct { int socket; int result; int error; } blocked_call; +static void *blocked_recv(void *opaque) { blocked_call *c = opaque; char byte; c->result = (int)RECV(c->socket, &byte, 1, 0, NULL, NULL); c->error = dm_net_errno(); return NULL; } +typedef int (*fn_efd)(unsigned long, int); +typedef int (*fn_efd_read)(int, unsigned long *); +typedef int (*fn_efd_write)(int, unsigned long); +#define EFD GET(fn_efd, "_ZN2nn6socket7EventFdEmNS0_12EventFdFlagsE") +#define EFD_READ GET(fn_efd_read, "_ZN2nn6socket11EventFdReadEiPm") +#define EFD_WRITE GET(fn_efd_write, "_ZN2nn6socket12EventFdWriteEim") +static void *blocked_efd_read(void *opaque) { blocked_call *c = opaque; unsigned long v = 0; c->result = EFD_READ(c->socket, &v) == 0 ? (int)v : -1; c->error = dm_net_errno(); return NULL; } +// A network mode's event descriptors are slots of the transport's socket table (dm_net_eventfd): one numbering, and Poll and Select see sockets and event descriptors together +static void eventfd_net(void) { + int udp = SOCKET(2, 2, 17), efd = EFD(0, 6); + CHECK(udp >= 0 && efd >= 0 && efd != udp && efd < 1024, "a network-mode event descriptor takes a number of the socket table"); + dm_net_pollfd p[2] = {{udp, 1, 0}, {efd, 1 | 4, 0}}; + CHECK(POLL(p, 2, 0) == 1 && !p[0].revents && p[1].revents == 4, "an unsignaled event descriptor is writable, not readable, beside a quiet socket"); + unsigned long v = 0; + CHECK(EFD_READ(efd, &v) < 0 && dm_net_errno() == 11, "a nonblocking read of a zero counter is EAGAIN"); + guest_errno = 0; CHECK(EFD_READ(efd, &v) < 0 && guest_errno == 11, "a failed event read sets the game's own errno too (gRPC checks errno for EAGAIN after its wakeup read)"); + CHECK(EFD_WRITE(efd, 2) == 0 && EFD_WRITE(efd, 3) == 0, "writes add to the counter"); + p[0].revents = p[1].revents = 0; + CHECK(POLL(p, 2, 1000) == 1 && (p[1].revents & 1) && !p[0].revents, "a written counter wakes Poll, the quiet socket stays quiet"); + uint64_t read[16] = {0}; read[efd >> 6] |= 1ull << (efd & 63); read[udp >> 6] |= 1ull << (udp & 63); int64_t tv[2] = {0, 0}; int top = (efd > udp ? efd : udp) + 1; + CHECK(SELECT(top, read, NULL, NULL, tv) == 1 && (read[efd >> 6] >> (efd & 63) & 1) && !(read[udp >> 6] >> (udp & 63) & 1), "Select sees the event descriptor beside the socket"); + CHECK(EFD_READ(efd, &v) == 0 && v == 5, "a counter read takes the whole count"); + p[1].revents = 0; CHECK(POLL(&p[1], 1, 0) == 1 && !(p[1].revents & 1), "a drained counter is no longer readable"); + CHECK(SEND(efd, "x", 1, 0, NULL, 0) < 0 && dm_net_errno() == 88, "a socket operation on an event descriptor fails with ENOTSOCK"); + CHECK(CLOSE(efd) == 0 && EFD_WRITE(efd, 1) < 0 && dm_net_errno() == 9, "close frees the event descriptor"); + int sem = EFD(2, 1); + CHECK(sem >= 0 && EFD_READ(sem, &v) == 0 && v == 1 && EFD_READ(sem, &v) == 0 && v == 1, "a semaphore descriptor reads one at a time"); + blocked_call call = {.socket = sem}; pthread_t t; CHECK(pthread_create(&t, NULL, blocked_efd_read, &call) == 0, "start a blocked event read"); + dm_guest_sleep_ns(30000000); CHECK(EFD_WRITE(sem, 1) == 0, "write while a reader waits"); + CHECK(pthread_join(t, NULL) == 0 && call.result == 1, "the blocked read wakes with the written count"); + call = (blocked_call){.socket = sem}; CHECK(pthread_create(&t, NULL, blocked_efd_read, &call) == 0, "start a second blocked event read"); + dm_guest_sleep_ns(30000000); CHECK(CLOSE(sem) == 0, "close while a reader waits"); + CHECK(pthread_join(t, NULL) == 0 && call.result < 0 && call.error == 9, "the reader of a closed event descriptor fails with EBADF"); + CHECK(CLOSE(udp) == 0, "the socket beside them closes"); +} +static void concurrency(void) { + int guest = SOCKET(2, 2, 17); address a = addr(htonl(0x7f000001), 0); CHECK(BIND(guest, &a, 16) == 0, "blocking socket bound"); + blocked_call call = {.socket = guest}; pthread_t t; CHECK(pthread_create(&t, NULL, blocked_recv, &call) == 0, "start blocked guest recv"); + dm_guest_sleep_ns(30000000); CHECK(CLOSE(guest) == 0, "concurrent close removes the slot"); + int reused = SOCKET(2, 2, 17); CHECK(reused == guest, "guest slot reused"); + CHECK(pthread_join(t, NULL) == 0 && call.result < 0 && call.error == 9, "old waiter cancels with EBADF and never reads reused socket"); + CHECK(CLOSE(reused) == 0, "reused socket remains intact"); +} +typedef struct { int fd; } writer_args; +static void *split_writer(void *opaque) { writer_args *a = opaque; send(a->fd, "12", 2, 0); dm_guest_sleep_ns(25000000); send(a->fd, "34", 2, 0); return NULL; } +static void tcp(void) { + int server = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in a = {.sin_len = sizeof a, .sin_family = AF_INET, .sin_addr.s_addr = htonl(0x7f000001)}; + CHECK(server >= 0 && bind(server, (struct sockaddr *)&a, sizeof a) == 0 && listen(server, 1) == 0, "native TCP listener"); + socklen_t size = sizeof a; getsockname(server, (struct sockaddr *)&a, &size); address destination = addr(a.sin_addr.s_addr, 0); destination.port = a.sin_port; + int guest = SOCKET(2, 1, 6); CHECK(GET(fn_bind, "_ZN2nn6socket7ConnectEiPK8sockaddrj")(guest, &destination, 16) == 0, "guest blocking connect completes on readiness"); + int native = accept(server, NULL, NULL); CHECK(native >= 0, "native accepts guest connection"); + address remote; unsigned n = 16; CHECK(PEER(guest, &remote, &n) == 0 && remote.port == destination.port, "guest peer address translated"); + writer_args args = {native}; pthread_t t; pthread_create(&t, NULL, split_writer, &args); char bytes[8] = {0}; + CHECK(RECV(guest, bytes, 4, 0x40, NULL, NULL) == 4 && !memcmp(bytes, "1234", 4), "WAITALL gathers partial TCP arrivals"); pthread_join(t, NULL); + CHECK(SEND(guest, "ok", 2, 0, NULL, 0) == 2 && recv(native, bytes, sizeof bytes, 0) == 2 && !memcmp(bytes, "ok", 2), "guest TCP send to native peer"); + close(native); CHECK(RECV(guest, bytes, 4, 0, NULL, NULL) == 0, "TCP orderly EOF"); + CHECK(GET(int (*)(int,int), "_ZN2nn6socket8ShutdownEii")(guest, 1) == 0, "guest shutdown translates write direction"); + CHECK(SEND(guest, "closed", 6, 0, NULL, 0) < 0 && dm_net_errno() == 32 && !sigpipe_count, "send after shutdown reports EPIPE without raising host SIGPIPE"); CLOSE(guest); + guest = SOCKET(2, 1, 6); CHECK(FCNTL(guest, 4, 0x802) == 0, "TCP set nonblock with actual NEX F_SETFL flags"); + int connected = GET(fn_bind, "_ZN2nn6socket7ConnectEiPK8sockaddrj")(guest, &destination, 16); + CHECK(connected == 0 || (connected < 0 && dm_net_errno() == 115), "nonblocking connect reports Horizon EINPROGRESS115"); + dm_net_pollfd pending = {guest, 4, 0}; CHECK(POLL(&pending, 1, 1000) == 1 && (pending.revents & 4), "nonblocking connect becomes writable"); + int error = -1; n = 4; CHECK(GETOPT(guest, 0xffff, 0x1007, &error, &n) == 0 && error == 0, "SO_ERROR completes nonblocking connect"); + native = accept(server, NULL, NULL); CHECK(native >= 0, "native accepts nonblocking client"); close(native); CLOSE(guest); close(server); + int listener = SOCKET(2, 1, 6); address local = addr(htonl(0x7f000001), 0); n = 16; + CHECK(BIND(listener, &local, 16) == 0 && NAME(listener, &local, &n) == 0 && GET(int (*)(int,int), "_ZN2nn6socket6ListenEii")(listener, 1) == 0, "guest TCP listener"); + int client = socket(AF_INET, SOCK_STREAM, 0); CHECK(client >= 0, "native client socket"); a.sin_port = local.port; CHECK(connect(client, (struct sockaddr *)&a, sizeof a) == 0, "native connects guest listener"); + n = 16; int accepted = GET(fn_name, "_ZN2nn6socket6AcceptEiP8sockaddrPj")(listener, &remote, &n); CHECK(accepted >= 0 && accepted != listener && remote.ip == htonl(0x7f000001), "guest accept allocates a separate owned descriptor"); + close(client); CLOSE(accepted); CLOSE(listener); +} +static void errors_and_resolver(void) { + CHECK(SOCKET(28, 2, 17) < 0 && dm_net_errno() == 97, "IPv6 rejected with correct family error"); + guest_errno = 0; CHECK(SOCKET(28, 2, 17) < 0 && guest_errno == 97, "a failed socket call sets the game's own errno, as Horizon's errno is the C library's"); + guest_errno = 115; CHECK(GET(int (*)(void), "_ZN2nn6socket12GetLastErrnoEv")() == 115, "GetLastErrno reads the game's errno, as detail::GetLastErrno does"); + CHECK(SOCKET(2, 3, 0) < 0 && dm_net_errno() == 94, "raw socket rejected"); + CHECK(SOCKET(2, 1, 17) < 0 && dm_net_errno() == 93, "protocol mismatch rejected"); + int guest = SOCKET(2, 2, 17); address a = addr(htonl(0x7f000001), 0); + CHECK(BIND(guest, &a, 3) < 0 && dm_net_errno() == 22, "short sockaddr rejected"); + CHECK(BIND(guest, NULL, 16) < 0 && dm_net_errno() == 14, "null sockaddr rejected"); + CHECK(FCNTL(guest, 4, 4) < 0 && dm_net_errno() == 22, "Darwin nonblock numeric flag not accidentally accepted"); + int one = 1; CHECK(SETOPT(guest, 0xffff, 0x7777, &one, 4) < 0 && dm_net_errno() == 92, "unsupported option fails honestly"); + dm_net_pollfd bad = {999, 1, 0}; CHECK(POLL(&bad, 1, 0) == 1 && bad.revents == 32, "poll invalid guest descriptor returns NVAL"); + int saved = fcntl(0, F_GETFD); dm_net_pollfd malformed[3] = {{guest, 0x4000, 0}, {guest, 1, 0}, {guest, 1, 0}}; + CHECK(POLL(malformed, 3, 0) < 0 && fcntl(0, F_GETFD) == saved, "poll validation never closes unborrowed host descriptors"); + CHECK(POLL(NULL, 1, 0) < 0 && dm_net_errno() == 14 && POLL(NULL, UINT64_MAX, 0) < 0, "poll null/overflow rejected"); + int64_t badtime[2] = {0, 1000000}; CHECK(SELECT(1, NULL, NULL, NULL, badtime) < 0 && dm_net_errno() == 22, "select invalid timeval rejected"); + CLOSE(guest); + typedef int (*fn_gai)(const char *, const char *, const void *, void **); + dm_net_addrinfo hints = {.family = 2, .type = 2, .flags = 4 | 8}; void *out = NULL; + CHECK(GET(fn_gai, "_ZN2nn6socket11GetAddrInfoEPKcS2_PK8addrinfoPPS3_")("127.0.0.1", "12345", &hints, &out) == 0 && out, "numeric getaddrinfo through guest hook"); + if (out) { dm_net_addrinfo_legacy *p = out; CHECK(p->family == 2 && p->type == 2 && p->addrlen == 16 && ((address *)p->addr)->port == htons(12345), "SDK4 addrinfo address pointer at32, wire port and address correct"); p->next = (void *)0xdeadbeef; dm_net_freeaddrinfo(out); dm_net_freeaddrinfo(out); CHECK(dm_net_errno() == 22, "resolver free uses owned allocations, ignores corrupted guest next and double free"); } + CHECK(GET(fn_gai, "_ZN2nn6socket11GetAddrInfoEPKcS2_PKNS0_8AddrInfoEPPS3_")("127.0.0.1", "12345", &hints, &out) == 0 && out, "modern named AddrInfo uses its separate hook"); + if (out) { dm_net_addrinfo *p = out; CHECK(p->family == 2 && p->addrlen == 16 && ((address *)p->addr)->port == htons(12345), "modern AddrInfo address pointer at24 translated separately"); dm_net_freeaddrinfo(out); } + resolver_abi = 0; + CHECK(GET(fn_gai, "nnsocketGetAddrInfo")("127.0.0.1", "1", &hints, &out) == 0 && out && ((dm_net_addrinfo_legacy *)out)->addr, "C resolver selects the exported legacy SDK ABI"); dm_net_freeaddrinfo(out); + resolver_abi = 1; + CHECK(GET(fn_gai, "nnsocketGetAddrInfo")("127.0.0.1", "1", &hints, &out) == 0 && out && ((dm_net_addrinfo *)out)->addr, "C resolver selects the exported modern SDK ABI"); dm_net_freeaddrinfo(out); + resolver_abi = 2; + CHECK(GET(fn_gai, "nnsocketGetAddrInfo")("127.0.0.1", "1", &hints, &out) == 0 && out && ((dm_net_addrinfo_legacy *)out)->addr, "C resolver takes the C struct addrinfo layout when an SDK exports both (Wonder 1.2.1)"); dm_net_freeaddrinfo(out); resolver_abi = 0; + CHECK(dm_net_getaddrinfo("127.0.0.1", "1", &(dm_net_addrinfo){.family = 28}, &out) == 5 && !out, "unsupported resolver family returns EAI_FAMILY"); + CHECK(GET(void *(*)(const char *), "_ZN2nn6socket13GetHostByNameEPKc")("127.0.0.1") != NULL, "automatic mode resolves a real numeric LAN peer through legacy hostent"); + CHECK(GET(void *(*)(const char *), "_ZN2nn6socket13GetHostByNameEPKc")("localhost") != NULL, "local mode resolves the host loopback name without an online provider"); +} +static void broadcast(void) { + unsetenv("DM_NETWORK_INTERFACE"); uint32_t ip, mask; + if (dm_net_ipconfig(&ip, &mask, NULL, NULL, NULL)) { CHECK(0, "broadcast requires an up real network interface"); return; } + address destination = addr(0, 0); int native = native_udp(&destination); destination.ip = htonl(0xffffffff); + int guest = SOCKET(2, 2, 17), one = 1; CHECK(SETOPT(guest, 0xffff, 0x20, &one, 4) == 0, "broadcast enabled"); + address source = addr(ip, 0); CHECK(BIND(guest, &source, sizeof source) == 0, "broadcast sender uses the actual NIFM interface"); + const char message[] = "nxnative LAN transport test"; + CHECK(SEND(guest, message, sizeof message, 0, &destination, sizeof destination) == sizeof message, "guest sends real limited broadcast"); + struct pollfd p = {native, POLLIN, 0}; CHECK(poll(&p, 1, 1000) == 1, "native peer receives guest limited broadcast"); + if (p.revents & POLLIN) { char bytes[64]; CHECK(recv(native, bytes, sizeof bytes, 0) == sizeof message && !memcmp(bytes, message, sizeof message), "broadcast payload preserved"); } + CLOSE(guest); close(native); setenv("DM_NETWORK_INTERFACE", "lo0", 1); +} +static void discovery_peer(void) { + address peer = addr(htonl(0x7f000001), 0); + int native = native_udp(&peer), guest = SOCKET(2, 2, 17); + char bytes[16]; + dm_net_set_multicast_allowed(0); + address discovery = peer; discovery.ip = htonl(UINT32_MAX); + unsetenv("DM_NET_DISCOVERY_PEER"); + CHECK(SEND(guest, "blocked", 7, 0, &discovery, 16) == -1 && dm_net_errno() == 99, + "a loopback-only adapter cannot trigger an automatic LAN sweep"); + setenv("DM_NET_DISCOVERY_PEER", "127.0.0.1", 1); + CHECK(SEND(guest, "discovery", 9, 0, &discovery, 16) == 9, + "explicit unicast discovery works without multicast entitlement"); + struct pollfd ready = {native, POLLIN, 0}; + CHECK(poll(&ready, 1, 1000) == 1 && recv(native, bytes, sizeof bytes, 0) == 9 && !memcmp(bytes, "discovery", 9), + "actual unicast peer receives unchanged discovery bytes"); + setenv("DM_NET_DISCOVERY_PEER", "invalid", 1); + CHECK(SEND(guest, "invalid", 7, 0, &discovery, 16) == -1 && dm_net_errno() == 22, + "malformed discovery peer fails explicitly"); + CHECK(SEND(guest, "ordinary", 8, 0, &peer, 16) == 8, + "ordinary unicast ignores discovery override"); + CHECK(poll(&ready, 1, 1000) == 1 && recv(native, bytes, sizeof bytes, 0) == 8 && !memcmp(bytes, "ordinary", 8), + "ordinary unicast keeps original destination and bytes"); + setenv("DM_NET_DISCOVERY_PEER", "224.0.0.1", 1); + CHECK(SEND(guest, "invalid", 7, 0, &discovery, 16) == -1 && dm_net_errno() == 22, + "multicast address cannot masquerade as explicit unicast peer"); + uint32_t target; + unsetenv("DM_NET_DISCOVERY_PEER"); + dm_net_set_multicast_allowed(1); + CHECK(dm_net_discovery_target(discovery.ip, &target) == 0 && target == discovery.ip, + "capable host retains native discovery destination"); + CLOSE(guest); close(native); +} +int main(int argc, char **argv) { + struct sigaction sa = {.sa_handler = sigpipe}; sigemptyset(&sa.sa_mask); sigaction(SIGPIPE, &sa, NULL); + offline(); nifm(); udp(); eventfd_net(); concurrency(); tcp(); errors_and_resolver(); discovery_peer(); + if (argc == 2 && !strcmp(argv[1], "--no-broadcast")) puts("broadcast test skipped explicitly (requires local-network permission for this test executable)"); else broadcast(); + GET(fn_vvoid, "_ZN2nn6socket8FinalizeEv")(); + CHECK(atomic_load(&waits) > 0 && atomic_load(&wait_balance) == 0, "all host waits yield and restore guest execution"); + CHECK(atomic_load(&contexts_entered) > 0 && atomic_load(&contexts_entered) == atomic_load(&contexts_left) && !atomic_load(&invalid_contexts), "blocking guest hooks publish and leave balanced register contexts"); + printf("network hooks: %d checks, %d failures\n", checks, failures); return failures ? 1 : 0; +} diff --git a/dm/host/tests/t_net_discovery.c b/dm/host/tests/t_net_discovery.c new file mode 100644 index 0000000000..79729eb9d8 --- /dev/null +++ b/dm/host/tests/t_net_discovery.c @@ -0,0 +1,232 @@ +// Real UDP discovery/reply traffic through the production socket translator. +// The adapter fixture is confined to 127/8. No LAN is scanned or broadcast sent. +#include "../net_socket.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static unsigned checks; +#define CHECK(c) do { ++checks; if (!(c)) { fprintf(stderr,"FAIL %d: %s (guest errno %d)\n",__LINE__,#c,dm_net_errno()); abort(); } } while (0) +void dm_guest_host_wait_begin(void) {} +void dm_guest_host_wait_end(void) {} +void dm_guest_sleep_ns(int64_t ns) { struct timespec t={ns/1000000000,ns%1000000000}; nanosleep(&t,NULL); } +static uint64_t ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC,&t); return (uint64_t)t.tv_sec*1000+t.tv_nsec/1000000; } +static _Atomic unsigned injected_calls; +static _Atomic int injected_bad_target; +static int injected_error; +static unsigned injected_at; +static long first_unreachable(int fd,const void *bytes,size_t size,int flags,uint32_t ip,uint16_t port) { + unsigned call=atomic_fetch_add(&injected_calls,1); + if(call==injected_at) { + atomic_store(&injected_bad_target,ip!=htonl(injected_at?0x7f000003:INADDR_LOOPBACK)); + errno=injected_error;return -1; + } + // Darwin has only 127.0.0.1 assigned: map the next logical neighbor to it. + // Actual UDP delivery, original fd/source port and bytes remain real. + struct sockaddr_in to={.sin_len=sizeof to,.sin_family=AF_INET,.sin_port=port,.sin_addr={htonl(INADDR_LOOPBACK)}}; + return sendto(fd,bytes,size,flags,(struct sockaddr *)&to,sizeof to); +} +typedef struct { uint8_t len,family; uint16_t port; uint32_t ip; uint8_t zero[8]; } address; +static address endpoint(uint32_t ip,unsigned port) { return (address){16,2,htons(port),htonl(ip),{0}}; } +static dm_net_test_interface adapter(uint32_t mask) { return (dm_net_test_interface){htonl(0x7f000002),htonl(mask),if_nametoindex("lo0"),IFF_UP|IFF_BROADCAST,1}; } +static int receiver(unsigned *port) { + int fd=socket(AF_INET,SOCK_DGRAM,0); CHECK(fd>=0); + struct sockaddr_in a={.sin_len=sizeof a,.sin_family=AF_INET,.sin_addr={htonl(INADDR_LOOPBACK)}}; + CHECK(!bind(fd,(struct sockaddr *)&a,sizeof a)); socklen_t n=sizeof a; CHECK(!getsockname(fd,(struct sockaddr *)&a,&n)); *port=ntohs(a.sin_port); return fd; +} +static ssize_t read_packet(int fd,void *bytes,size_t size,struct sockaddr_in *from) { + struct pollfd p={fd,POLLIN,0}; if(poll(&p,1,1000)!=1)return -1; + socklen_t n=sizeof *from; return recvfrom(fd,bytes,size,0,(struct sockaddr *)from,&n); +} +static void ranges(void) { + dm_net_discovery_plan p; uint32_t ip; + CHECK(!dm_net_discovery_subnet(&p,htonl(0xc0a80819),htonl(0xffffff00)) && p.count==253); + unsigned n=0; while(dm_net_discovery_next(&p,&ip)) { CHECK(ntohl(ip)>0xc0a80800 && ntohl(ip)<0xc0a808ff && ntohl(ip)!=0xc0a80819); ++n; } CHECK(n==253); + CHECK(!dm_net_discovery_subnet(&p,htonl(0xac101911),htonl(0xfffff000)) && p.count==4093 && dm_net_discovery_duration(&p)==1024); + n=0; while(dm_net_discovery_next(&p,&ip)) { CHECK(ntohl(ip)>0xac101000 && ntohl(ip)<0xac101fff && ntohl(ip)!=0xac101911); ++n; } CHECK(n==4093); + const uint32_t masks[]={0,0xffff0000,0xffff00ff,0xfffffffe,0xffffffff}; + for(unsigned i=0;i=0); + address own=endpoint(INADDR_LOOPBACK,0); CHECK(!dm_net_bind(guest,&own,sizeof own)); unsigned n=sizeof own; CHECK(!dm_net_name(guest,&own,&n,0)); + CHECK(!dm_net_fcntl(guest,4,0x800)); // nonblocking guest SendTo stays nonblocking + address destination=endpoint(UINT32_MAX,port); + const unsigned char query[]={0x80,0x34,0,0xff,'L','A','N',0,1,2,3}; + uint64_t start=ms(); CHECK(dm_net_send(guest,query,sizeof query,0,&destination,sizeof destination)==sizeof query); CHECK(ms()-start<100); + unsigned char bytes[64]; struct sockaddr_in from; + CHECK(read_packet(native,bytes,sizeof bytes,&from)==sizeof query && !memcmp(bytes,query,sizeof query)); + CHECK(from.sin_port==own.port && ntohl(from.sin_addr.s_addr)==INADDR_LOOPBACK); + CHECK(sendto(native,"answer",6,0,(struct sockaddr *)&from,sizeof from)==6); + dm_net_pollfd ready={guest,1,0}; CHECK(dm_net_poll(&ready,1,1000)==1); + address peer; n=sizeof peer; CHECK(dm_net_recv(guest,bytes,sizeof bytes,0,&peer,&n)==6 && !memcmp(bytes,"answer",6)); + CHECK(peer.ip==htonl(INADDR_LOOPBACK) && peer.port==htons(port)); + // Directed subnet broadcast enters exactly the same unicast route. + destination.ip=htonl(0x7f000003); + // A distinct nonce tests this route independently: an identical outstanding + // query may legitimately be coalesced with the first subnet sweep. + unsigned char directed[sizeof query]; memcpy(directed,query,sizeof directed); directed[sizeof directed-1]^=1; + CHECK(dm_net_send(guest,directed,sizeof directed,0,&destination,sizeof destination)==sizeof directed); + CHECK(read_packet(native,bytes,sizeof bytes,&from)==sizeof directed && !memcmp(bytes,directed,sizeof directed)); + // A broken optional override cannot interfere with ordinary peer traffic. + setenv("DM_NET_DISCOVERY_PEER","invalid",1); destination.ip=htonl(INADDR_LOOPBACK); + CHECK(dm_net_send(guest,"ordinary",8,0,&destination,sizeof destination)==8); + CHECK(read_packet(native,bytes,sizeof bytes,&from)==8 && !memcmp(bytes,"ordinary",8)); + destination.ip=htonl(UINT32_MAX); CHECK(dm_net_send(guest,query,sizeof query,0,&destination,sizeof destination)<0 && dm_net_errno()==22); + unsetenv("DM_NET_DISCOVERY_PEER"); CHECK(!dm_net_close(guest)); close(native); +} +static void bounds_and_lifetime(void) { + dm_net_test_interface a=adapter(0xfffff000); dm_net_test_set_interface(&a); + unsigned port; int native=receiver(&port),guest=dm_net_socket(2,2,0); CHECK(guest>=0); + address destination=endpoint(UINT32_MAX,port); + uint64_t start=ms(); + CHECK(dm_net_send(guest,"nonce1",6,0,&destination,sizeof destination)==6); + for(unsigned i=0;i<100;++i) CHECK(dm_net_send(guest,"nonce1",6,0,&destination,sizeof destination)==6); + CHECK(ms()-start<100 && dm_net_test_discovery_pending()==1); + usleep(20000); CHECK(dm_net_test_discovery_pending()==1); // the /20 sweep is paced, not one burst + CHECK(dm_net_send(guest,"nonce2",6,0,&destination,sizeof destination)==6); + CHECK(dm_net_send(guest,"nonce3",6,0,&destination,sizeof destination)<0 && dm_net_errno()==105); + CHECK(dm_net_test_discovery_pending()==2); + unsigned char bytes[16]; struct sockaddr_in from; + CHECK(read_packet(native,bytes,sizeof bytes,&from)==6 && !memcmp(bytes,"nonce1",6)); + CHECK(read_packet(native,bytes,sizeof bytes,&from)==6 && !memcmp(bytes,"nonce2",6)); + CHECK(!dm_net_close(guest) && !dm_net_test_discovery_pending()); + int reused=dm_net_socket(2,2,0); CHECK(reused==guest); destination.ip=htonl(INADDR_LOOPBACK); + CHECK(dm_net_send(reused,"reused",6,0,&destination,sizeof destination)==6); + CHECK(read_packet(native,bytes,sizeof bytes,&from)==6 && !memcmp(bytes,"reused",6)); + CHECK(!dm_net_close(reused)); close(native); + // The global queue has a real bound even across distinct guest sockets. + native=receiver(&port); destination=endpoint(UINT32_MAX,port); int sockets[17]; + for(unsigned i=0;i<17;++i) { + sockets[i]=dm_net_socket(2,2,0); CHECK(sockets[i]>=0); + long result=dm_net_send(sockets[i],"bounded",7,0,&destination,sizeof destination); + CHECK(i<16 ? result==7 : result<0 && dm_net_errno()==105); + } + CHECK(dm_net_test_discovery_pending()==16); + for(unsigned i=0;i<17;++i) CHECK(!dm_net_close(sockets[i])); + CHECK(!dm_net_test_discovery_pending()); close(native); + dm_net_discovery_plan plan; + a=adapter(0xffff0000); dm_net_test_set_interface(&a); CHECK(dm_net_discovery_prepare(htonl(UINT32_MAX),&plan)<0 && dm_net_errno()==95); + const unsigned flags[]={IFF_UP,IFF_BROADCAST,IFF_UP|IFF_BROADCAST|IFF_POINTOPOINT,IFF_UP|IFF_BROADCAST|IFF_LOOPBACK}; + for(unsigned i=0;i=0);CHECK(!dm_net_fcntl(guest,4,0x800)); + injected_error=errors[i];injected_at=0;atomic_store(&injected_bad_target,0);atomic_store(&injected_calls,0);dm_net_test_set_discovery_sender(first_unreachable); + uint64_t start=ms();long result=dm_net_send(guest,"later neighbor",14,0,&destination,sizeof destination); + if(i<3) { + CHECK(result==14 && ms()-start<100 && atomic_load(&injected_calls)>=2); + char bytes[32];struct sockaddr_in from;CHECK(read_packet(native,bytes,sizeof bytes,&from)==14 && !memcmp(bytes,"later neighbor",14)); + } else CHECK(result<0 && dm_net_errno()==(i==3?13:100) && atomic_load(&injected_calls)==1); + CHECK(!atomic_load(&injected_bad_target)); + CHECK(!dm_net_close(guest));dm_net_test_set_discovery_sender(NULL); + struct pollfd ready={native,POLLIN,0};char drain[32];while(poll(&ready,1,0)>0)recv(native,drain,sizeof drain,0); + } + // The first send succeeds; a later worker neighbor reports EHOSTDOWN. + // The worker must skip it and still deliver to the following neighbor. + int guest=dm_net_socket(2,2,0);CHECK(guest>=0);injected_error=EHOSTDOWN;injected_at=1; + atomic_store(&injected_calls,0);atomic_store(&injected_bad_target,0);dm_net_test_set_discovery_sender(first_unreachable); + CHECK(dm_net_send(guest,"worker neighbor",15,0,&destination,sizeof destination)==15); + char bytes[32];struct sockaddr_in from; + CHECK(read_packet(native,bytes,sizeof bytes,&from)==15&&!memcmp(bytes,"worker neighbor",15)); + CHECK(read_packet(native,bytes,sizeof bytes,&from)==15&&!memcmp(bytes,"worker neighbor",15)); + CHECK(atomic_load(&injected_calls)>=3&&!atomic_load(&injected_bad_target));CHECK(!dm_net_close(guest));dm_net_test_set_discovery_sender(NULL);injected_at=0; + close(native); +} +static _Atomic unsigned hybrid_native,hybrid_unicast; +static unsigned hybrid_native_port,hybrid_phone_port; +static int hybrid_failure; +static long hybrid_sender(int fd,const void *bytes,size_t size,int flags,uint32_t ip,uint16_t port) { + (void)port;unsigned destination; + if(ntohl(ip)==UINT32_MAX) { + atomic_fetch_add(&hybrid_native,1); + if(hybrid_failure) { errno=hybrid_failure;return -1; } + destination=hybrid_native_port; + } else { atomic_fetch_add(&hybrid_unicast,1);destination=hybrid_phone_port; } + struct sockaddr_in to={.sin_len=sizeof to,.sin_family=AF_INET,.sin_port=htons((uint16_t)destination),.sin_addr={htonl(INADDR_LOOPBACK)}}; + return sendto(fd,bytes,size,flags,(struct sockaddr *)&to,sizeof to); +} +static void hybrid_reset(void) { atomic_store(&hybrid_native,0);atomic_store(&hybrid_unicast,0);hybrid_failure=0; } +static void drain(int fd) { struct pollfd p={fd,POLLIN,0};char bytes[2048];while(poll(&p,1,0)>0)recv(fd,bytes,sizeof bytes,0); } +static void supplemental_queries(void) { + dm_net_test_interface a=adapter(0xfffffffc);dm_net_test_set_interface(&a);dm_net_set_multicast_allowed(1); + int native=receiver(&hybrid_native_port),phone=receiver(&hybrid_phone_port);dm_net_test_set_discovery_sender(hybrid_sender); + unsigned char pia[0x12f]={0};pia[5]=1;pia[14]=1; + const unsigned char ldn[12]={0,0x14,0x45,0x11}; + for(unsigned protocol=0;protocol<2;++protocol) { + const void *query=protocol?(const void *)ldn:(const void *)pia;size_t size=protocol?sizeof ldn:sizeof pia; + int guest=dm_net_socket(2,2,0);CHECK(guest>=0);address own=endpoint(INADDR_LOOPBACK,0);CHECK(!dm_net_bind(guest,&own,sizeof own));unsigned length=sizeof own;CHECK(!dm_net_name(guest,&own,&length,0)); + address destination=endpoint(UINT32_MAX,protocol?11452:30000);hybrid_reset();dm_net_set_errno(777); + CHECK(dm_net_send(guest,query,size,0,&destination,sizeof destination)==(long)size&&dm_net_errno()==777); + unsigned char bytes[1024];struct sockaddr_in from; + CHECK(read_packet(native,bytes,sizeof bytes,&from)==(ssize_t)size&&!memcmp(bytes,query,size)&&from.sin_port==own.port); + CHECK(read_packet(phone,bytes,sizeof bytes,&from)==(ssize_t)size&&!memcmp(bytes,query,size)&&from.sin_port==own.port); + CHECK(atomic_load(&hybrid_native)==1&&atomic_load(&hybrid_unicast)==1&&dm_net_multicast_allowed()==1); + CHECK(sendto(phone,"phone reply",11,0,(struct sockaddr *)&from,sizeof from)==11); + dm_net_pollfd ready={guest,1,0};CHECK(dm_net_poll(&ready,1,1000)==1);CHECK(dm_net_recv(guest,bytes,sizeof bytes,0,NULL,NULL)==11&&!memcmp(bytes,"phone reply",11)); + CHECK(!dm_net_close(guest)); + } + // Native errors remain errors and never trigger supplemental traffic. + const int failures[]={EACCES,EHOSTUNREACH,ENETDOWN,EHOSTDOWN},expected[]={13,113,100,112}; + address destination=endpoint(UINT32_MAX,30000); + for(unsigned i=0;i<4;++i) { + int guest=dm_net_socket(2,2,0);CHECK(guest>=0);hybrid_reset();hybrid_failure=failures[i]; + CHECK(dm_net_send(guest,pia,sizeof pia,0,&destination,sizeof destination)<0&&dm_net_errno()==expected[i]); + CHECK(atomic_load(&hybrid_native)==1&&!atomic_load(&hybrid_unicast)&&!dm_net_test_discovery_pending());CHECK(!dm_net_close(guest)); + } + // Unknown game data, replies and ports retain the sole native send. + for(unsigned i=0;i<4;++i) { + int guest=dm_net_socket(2,2,0);CHECK(guest>=0);hybrid_reset();unsigned char packet[0x12f];memcpy(packet,pia,sizeof packet); + size_t packet_size=sizeof packet; + if(i==0) { packet[0]=1;packet[14]=17;packet_size=0x3f; } // valid host response, not a query + if(i==1)packet[5]=2;if(i==3) { memcpy(packet,"gameplay",8);packet_size=8; } + destination=endpoint(UINT32_MAX,i==2?30001:30000); + CHECK(dm_net_send(guest,packet,packet_size,0,&destination,sizeof destination)==(long)packet_size); + CHECK(atomic_load(&hybrid_native)==1&&!atomic_load(&hybrid_unicast)&&!dm_net_test_discovery_pending());CHECK(!dm_net_close(guest)); + } + drain(native);drain(phone); + int guest=dm_net_socket(2,2,0);CHECK(guest>=0);destination=endpoint(INADDR_LOOPBACK,30000);hybrid_reset(); + CHECK(dm_net_send(guest,pia,sizeof pia,0,&destination,sizeof destination)==sizeof pia);CHECK(!atomic_load(&hybrid_native)&&atomic_load(&hybrid_unicast)==1&&!dm_net_test_discovery_pending());CHECK(!dm_net_close(guest)); + // A user-selected peer stays a single unicast, with no additional sweep. + guest=dm_net_socket(2,2,0);CHECK(guest>=0);setenv("DM_NET_DISCOVERY_PEER","127.0.0.1",1);destination=endpoint(UINT32_MAX,30000);hybrid_reset(); + CHECK(dm_net_send(guest,pia,sizeof pia,0,&destination,sizeof destination)==sizeof pia);CHECK(!atomic_load(&hybrid_native)&&atomic_load(&hybrid_unicast)==1&&!dm_net_test_discovery_pending());CHECK(!dm_net_close(guest));unsetenv("DM_NET_DISCOVERY_PEER"); + // A /16 cannot be swept, but its accepted native broadcast still succeeds. + a=adapter(0xffff0000);dm_net_test_set_interface(&a);guest=dm_net_socket(2,2,0);CHECK(guest>=0);hybrid_reset();dm_net_set_errno(777); + CHECK(dm_net_send(guest,pia,sizeof pia,0,&destination,sizeof destination)==sizeof pia&&dm_net_errno()==777);CHECK(atomic_load(&hybrid_native)==1&&!atomic_load(&hybrid_unicast));CHECK(!dm_net_close(guest)); + // Cap0 remains unicast-only, preserving the current phone path. + a=adapter(0xfffffffc);dm_net_test_set_interface(&a);dm_net_set_multicast_allowed(0);guest=dm_net_socket(2,2,0);CHECK(guest>=0);hybrid_reset(); + CHECK(dm_net_send(guest,pia,sizeof pia,0,&destination,sizeof destination)==sizeof pia);CHECK(!atomic_load(&hybrid_native)&&atomic_load(&hybrid_unicast)==1);CHECK(!dm_net_close(guest)); + // Extra queue pressure must not change the accepted native result. + a=adapter(0xfffff000);dm_net_test_set_interface(&a);dm_net_set_multicast_allowed(1);guest=dm_net_socket(2,2,0);CHECK(guest>=0);hybrid_reset(); + pia[14]=1;for(unsigned repeat=0;repeat<3;++repeat) { dm_net_set_errno(777);CHECK(dm_net_send(guest,pia,sizeof pia,0,&destination,sizeof destination)==sizeof pia&&dm_net_errno()==777); } + CHECK(atomic_load(&hybrid_native)==3&&dm_net_test_discovery_pending()==1); // native retries stay native; extra sweep coalesces + for(unsigned i=2;i<=3;++i) { pia[14]=(unsigned char)i;dm_net_set_errno(777);CHECK(dm_net_send(guest,pia,sizeof pia,0,&destination,sizeof destination)==sizeof pia&&dm_net_errno()==777); } + CHECK(atomic_load(&hybrid_native)==5&&dm_net_test_discovery_pending()==2);CHECK(!dm_net_close(guest)&&!dm_net_test_discovery_pending()); + unsigned sent=atomic_load(&hybrid_unicast);usleep(20000);CHECK(atomic_load(&hybrid_unicast)==sent);drain(phone); + int reused=dm_net_socket(2,2,0);CHECK(reused==guest);destination=endpoint(INADDR_LOOPBACK,30000);CHECK(dm_net_send(reused,"ordinary",8,0,&destination,sizeof destination)==8);CHECK(!dm_net_test_discovery_pending());CHECK(!dm_net_close(reused)); + dm_net_test_set_discovery_sender(NULL);dm_net_set_multicast_allowed(0);close(native);close(phone); +} +int main(void) { + setenv("DM_NETWORK","auto",1); unsetenv("DM_NET_DISCOVERY_PEER"); dm_net_set_multicast_allowed(0); + ranges(); traffic(); unreachable_neighbor(); supplemental_queries(); bounds_and_lifetime(); dm_net_test_set_interface(NULL); + printf("automatic discovery: %u checks passed (real UDP reply, ranges, bounded queue, close/reuse).\n",checks); return 0; +} diff --git a/dm/host/tests/t_net_eventfd.c b/dm/host/tests/t_net_eventfd.c index f0ba531d6c..33d9bc8cf9 100644 --- a/dm/host/tests/t_net_eventfd.c +++ b/dm/host/tests/t_net_eventfd.c @@ -10,6 +10,12 @@ void dm_guest_sleep_ns(int64_t ns) { struct timespec ts = {ns / 1000000000, ns % void dm_guest_cond_wait_ns(pthread_cond_t *c, pthread_mutex_t *m, int64_t ns) { struct timespec ts = {ns / 1000000000, ns % 1000000000}; pthread_cond_timedwait_relative_np(c, m, &ts); } uint64_t guest_ns(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000000000u + (uint64_t)ts.tv_nsec; } int dm_detclock_enabled(void) { return 0; } +void *guest_sym(const char *name) { (void)name; return NULL; } // no game: a failed socket call keeps only the host's errno (hle_net.c dm_net_guest_errno) +// hle_net.c sits on the socket backend (hle_net_backend.c, which brackets its host waits) and its HLE_FORCE_WAIT entries branch to entry.S's +// dm_hle_wait_enter. The test calls the hooks directly, offline, so the backend's waits need no guest bookkeeping and no guest call reaches the entry. +void dm_guest_host_wait_begin(void) {} +void dm_guest_host_wait_end(void) {} +void dm_hle_wait_enter(void) { abort(); } static void *writer(void *fd) { dm_guest_sleep_ns(20000000); assert(h_sk_EventFdWrite((int)(intptr_t)fd, 1) == 0); return NULL; } static void *closer(void *fd) { dm_guest_sleep_ns(20000000); assert(h_sk_Close((int)(intptr_t)fd) == 0); return NULL; } diff --git a/dm/host/tests/t_net_loopback.c b/dm/host/tests/t_net_loopback.c index f3f8e86f07..18d3402809 100644 --- a/dm/host/tests/t_net_loopback.c +++ b/dm/host/tests/t_net_loopback.c @@ -9,6 +9,11 @@ void dm_guest_sleep_ns(int64_t ns) { struct timespec ts = {ns / 1000000000, ns % void dm_guest_cond_wait_ns(pthread_cond_t *c, pthread_mutex_t *m, int64_t ns) { struct timespec ts = {ns / 1000000000, ns % 1000000000}; pthread_cond_timedwait_relative_np(c, m, &ts); } uint64_t guest_ns(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000000000u + (uint64_t)ts.tv_nsec; } int dm_detclock_enabled(void) { return 0; } +void *guest_sym(const char *name) { (void)name; return NULL; } // no game: a failed socket call keeps only the host's errno (hle_net.c dm_net_guest_errno) +// As t_net_eventfd.c: hle_net.c sits on the socket backend, whose host waits need no guest bookkeeping here, and no guest call reaches entry.S's dm_hle_wait_enter +void dm_guest_host_wait_begin(void) {} +void dm_guest_host_wait_end(void) {} +void dm_hle_wait_enter(void) { abort(); } static void address(uint8_t out[16], uint32_t ip, unsigned port) { uint8_t b[16] = {16, 2, (uint8_t)(port >> 8), (uint8_t)port, (uint8_t)(ip >> 24), (uint8_t)(ip >> 16), (uint8_t)(ip >> 8), (uint8_t)ip}; memcpy(out, b, sizeof b); diff --git a/dm/host/tests/t_net_off.c b/dm/host/tests/t_net_off.c new file mode 100644 index 0000000000..17bef0bc06 --- /dev/null +++ b/dm/host/tests/t_net_off.c @@ -0,0 +1,33 @@ +// The network transport as it is offline, for a host unit test that compiles hle_offline.c without the transport (t_server_environment): DM_NETWORK is +// offline, so hle_offline.c's socket calls go to the local service (dm_sk_*) and none of these is reached; each fails if one is. Weak, so a test's own wins. +#include "../hle.h" +#include "../net_socket.h" +#include "../hle_net.h" +#define W __attribute__((weak)) +W dm_net_mode_t dm_net_mode(void) { return DM_NET_OFFLINE; } +W int dm_net_enabled(void) { return 0; } +W void *guest_sym(const char *name) { (void)name; return NULL; } +W void dm_hle_wait_enter(void) { abort(); } // the HLE_FORCE_WAIT gate's entry (entry.S); no wait hook is called here +W void dm_nifm_submit_wait(void) {} +W int dm_sk_unavailable(void) { return -1; } +W int dm_net_accept(int fd, void *addr, unsigned *len) { (void)fd; (void)addr; (void)len; return -1; } +W int dm_net_bind(int fd, const void *addr, unsigned len) { (void)fd; (void)addr; (void)len; return -1; } +W int dm_net_connect(int fd, const void *addr, unsigned len) { (void)fd; (void)addr; (void)len; return -1; } +W int dm_net_fcntl(int fd, int cmd, int flags) { (void)fd; (void)cmd; (void)flags; return -1; } +W void dm_net_finalize(void) {} +W void dm_net_freeaddrinfo(void *result) { (void)result; } +W int dm_net_getaddrinfo(const char *host, const char *service, const void *hints, void **result) { (void)host; (void)service; (void)hints; if (result) *result = NULL; return -1; } +W int dm_net_getaddrinfo_legacy(const char *host, const char *service, const void *hints, void **result) { (void)host; (void)service; (void)hints; if (result) *result = NULL; return -1; } +W void *dm_net_gethostbyname(const char *name) { (void)name; return NULL; } +W long dm_net_guest_errno(long r) { return r; } +W int dm_net_guest_errno_get(void) { return 0; } +W int dm_net_ipconfig(uint32_t *address, uint32_t *mask, uint32_t *gateway, uint32_t *dns1, uint32_t *dns2) { (void)address; (void)mask; (void)gateway; (void)dns1; (void)dns2; return -1; } +W int dm_net_listen(int fd, int backlog) { (void)fd; (void)backlog; return -1; } +W int dm_net_name(int fd, void *addr, unsigned *len, int peer) { (void)fd; (void)addr; (void)len; (void)peer; return -1; } +W long dm_net_recv(int fd, void *buf, unsigned long len, int flags, void *addr, unsigned *addrlen) { (void)fd; (void)buf; (void)len; (void)flags; (void)addr; (void)addrlen; return -1; } +W long dm_net_send(int fd, const void *buf, unsigned long len, int flags, const void *addr, unsigned addrlen) { (void)fd; (void)buf; (void)len; (void)flags; (void)addr; (void)addrlen; return -1; } +W void dm_net_set_errno(int e) { (void)e; } +W int dm_net_shutdown(int fd, int how) { (void)fd; (void)how; return -1; } +W int dm_net_socket(int family, int type, int protocol) { (void)family; (void)type; (void)protocol; return -1; } +W int dm_net_socket_type(int fd) { (void)fd; return 0; } +W int dm_net_sockopt(int fd, int level, int option, void *value, unsigned *len, int set) { (void)fd; (void)level; (void)option; (void)value; (void)len; (void)set; return -1; } diff --git a/dm/host/tests/t_net_write_prepare.c b/dm/host/tests/t_net_write_prepare.c new file mode 100644 index 0000000000..5896ae5507 --- /dev/null +++ b/dm/host/tests/t_net_write_prepare.c @@ -0,0 +1,124 @@ +// Original socket-copyout fixture with the real dirty-page tracker; no GPU, game or external peer. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../../gfx/nvn/nvn_dirty.h" +static void (*prepare_hook)(void*,size_t);static unsigned preps,checks,failures; +static void *last_prep;static size_t last_len; +void dm_fault_hook_register(int (*fn)(void*,int,void*)) {(void)fn;} +void dm_guest_write_prep_register(void (*fn)(void*,size_t)) {assert(fn&&!prepare_hook);prepare_hook=fn;} +void dm_guest_write_prepare(void *p,size_t n) {++preps;last_prep=p;last_len=n;if(prepare_hook)prepare_hook(p,n);} +void dm_guest_host_wait_begin(void) {} void dm_guest_host_wait_end(void) {} +static int wait_sender=-1;static void *wait_destination;static size_t wait_size;static int wait_hits; +static struct sockaddr_in wait_address;static int wait_udp; +static const char *wait_bytes="DATA";static size_t wait_count=4; +static int fixture_poll(struct pollfd *p,nfds_t n,int ms) { + if(wait_sender>=0){int s=wait_sender;wait_sender=-1;++wait_hits;nvn_dirty_protect(wait_destination,wait_size); + ssize_t sent=wait_udp?sendto(s,wait_bytes,wait_count,0,(void*)&wait_address,16):send(s,wait_bytes,wait_count,0);assert(sent==(ssize_t)wait_count);} + return poll(p,n,ms); +} +#define poll fixture_poll +#include "../hle_net_backend.c" +#undef poll +#define CHECK(x) do{++checks;if(!(x)){++failures;fprintf(stderr,"FAIL %d: %s (guest errno%d)\n",__LINE__,#x,dm_net_errno());}}while(0) +static nx_addr address(uint16_t port){return (nx_addr){.len=16,.family=2,.port=port,.address=htonl(INADDR_LOOPBACK)};} +static void udp_pair(int *guest,int *peer,struct sockaddr_in *back) { + *guest=dm_net_socket(2,2,17);assert(*guest>=0);nx_addr a=address(0);assert(!dm_net_bind(*guest,&a,16));unsigned len=16;assert(!dm_net_name(*guest,&a,&len,0)); + *peer=socket(AF_INET,SOCK_DGRAM,0);assert(*peer>=0);*back=(struct sockaddr_in){.sin_len=16,.sin_family=AF_INET,.sin_port=a.port,.sin_addr={htonl(INADDR_LOOPBACK)}}; +} +static void tcp_pair(int *guest,int *peer) { + int server=socket(AF_INET,SOCK_STREAM,0);assert(server>=0);struct sockaddr_in a={.sin_len=16,.sin_family=AF_INET,.sin_addr={htonl(INADDR_LOOPBACK)}};assert(!bind(server,(void*)&a,16)&&!listen(server,1));socklen_t z=16;assert(!getsockname(server,(void*)&a,&z)); + *guest=dm_net_socket(2,1,6);assert(*guest>=0);nx_addr n=address(a.sin_port);assert(!dm_net_connect(*guest,&n,16));*peer=accept(server,NULL,NULL);assert(*peer>=0);close(server); +} +static void trial(int udp,int delayed,int invalid) { + size_t page=(size_t)getpagesize();void *dst=mmap(NULL,page,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0);assert(dst!=MAP_FAILED);memset(dst,0xa5,page); + if(!invalid)nvn_dirty_add_range(dst,page); + if(invalid)assert(!mprotect(dst,page,PROT_NONE));else nvn_dirty_protect(dst,page); + uint64_t stamp=nvn_dirty_now();unsigned before=preps;int guest,peer;struct sockaddr_in back; + if(udp)udp_pair(&guest,&peer,&back);else tcp_pair(&guest,&peer); + if(delayed){wait_sender=peer;wait_destination=dst;wait_size=page;wait_udp=udp;if(udp)wait_address=back;} + else {ssize_t sent=udp?sendto(peer,"DATA",4,0,(void*)&back,16):send(peer,"DATA",4,0);assert(sent==4);} + dm_net_set_errno(77);long result=dm_net_recv(guest,dst,4,0,NULL,NULL); + if(invalid)CHECK(result==-1&&dm_net_errno()==14&&!nvn_dirty_tracked(dst,page)); + else {CHECK(result==4&&dm_net_errno()==77);if(result==4)CHECK(!memcmp(dst,"DATA",4));CHECK(nvn_dirty_since(dst,page,stamp));} + printf("%s %s %s: result%ld errno%d preps%u\n",udp?"UDP":"TCP",delayed?"reprotected during wait":"already protected",invalid?"invalid":"tracked",result,dm_net_errno(),preps-before); + if(delayed)CHECK(wait_sender==-1&&wait_hits>0); + if(!invalid)nvn_dirty_remove_range(dst);CHECK(!munmap(dst,page));CHECK(!dm_net_close(guest));close(peer); +} +static void stream_partial(void); +static void invalid_and_empty(void); +static void socket_options(void); +int main(void) {setenv("DM_NETWORK","auto",1); + for(int udp=0;udp<=1;++udp){trial(udp,0,0);trial(udp,1,0);trial(udp,0,1);} + stream_partial();invalid_and_empty();socket_options(); + printf("socket write prepare: %u checks,%u failed\n",checks,failures);return failures!=0; +} +static void stream_partial(void) { + size_t page=(size_t)getpagesize();void *dst=mmap(NULL,page,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0);assert(dst!=MAP_FAILED);nvn_dirty_add_range(dst,page);nvn_dirty_protect(dst,page); + int guest,peer;tcp_pair(&guest,&peer);assert(send(peer,"AB",2,0)==2);int native=dm_net_dup_native(guest);struct pollfd ready={native,POLLIN,0};assert(poll(&ready,1,100)==1);close(native); + wait_sender=peer;wait_destination=dst;wait_size=page;wait_udp=0;wait_bytes="CD";wait_count=2;unsigned before=preps;dm_net_set_errno(77); + CHECK(dm_net_recv(guest,dst,4,0x40,NULL,NULL)==4&&dm_net_errno()==77);CHECK(!memcmp(dst,"ABCD",4));CHECK(preps>=before+3&&last_prep==(char*)dst+2&&last_len==2);CHECK(wait_sender==-1); + nvn_dirty_remove_range(dst);CHECK(!munmap(dst,page));CHECK(!dm_net_close(guest));close(peer);wait_bytes="DATA";wait_count=4; +} +static void invalid_and_empty(void) { + size_t page=(size_t)getpagesize();void *ro=mmap(NULL,page,PROT_READ,MAP_PRIVATE|MAP_ANON,-1,0);assert(ro!=MAP_FAILED); + int guest,peer;struct sockaddr_in back;udp_pair(&guest,&peer,&back);assert(sendto(peer,"DATA",4,0,(void*)&back,16)==4);unsigned before=preps; + CHECK(dm_net_recv(guest,ro,4,0,NULL,NULL)==-1&&dm_net_errno()==14&&!nvn_dirty_tracked(ro,page));CHECK(preps>before);CHECK(!munmap(ro,page)); + before=preps;CHECK(dm_net_recv(guest,NULL,1,0,NULL,NULL)==-1&&dm_net_errno()==14&&preps==before); + CHECK(dm_net_recv(guest,(void*)1,4,0x10000,NULL,NULL)==-1&&dm_net_errno()==95&&preps==before); + CHECK(dm_net_recv(-1,(void*)1,4,0,NULL,NULL)==-1&&dm_net_errno()==9&&preps==before); + assert(sendto(peer,"DATA",4,0,(void*)&back,16)==4);CHECK(dm_net_recv(guest,(void*)1,4,0,NULL,NULL)==-1&&dm_net_errno()==14&&!nvn_dirty_tracked((void*)1,4)); + char drain[8];while(dm_net_recv(guest,drain,sizeof drain,0x80,NULL,NULL)>=0){} + assert(sendto(peer,NULL,0,0,(void*)&back,16)==0);CHECK(dm_net_recv(guest,NULL,0,0,NULL,NULL)==0); + CHECK(!dm_net_close(guest));close(peer); +} + +// A getsockopt copyout is not a CPU write fault either. Exercise the exact +// validated option span, including a result crossing two protected pages. +static void socket_option_output(int kind) { + size_t page=(size_t)getpagesize();uint8_t *mem=mmap(NULL,page*2,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0);assert(mem!=MAP_FAILED);memset(mem,0xa5,page*2); + nvn_dirty_add_range(mem,page*2);nvn_dirty_protect(mem,page*2);uint64_t stamp=nvn_dirty_now(); + unsigned size=kind==2?8:4,option=kind==0?0x1008:kind==1?0x1007:128; + uint8_t *value=kind==2?mem+page-4:mem+32;unsigned len=32,before=preps; + int guest=dm_net_socket(2,kind==0?2:1,kind==0?17:6);assert(guest>=0);dm_net_set_errno(77); + int result=dm_net_sockopt(guest,0xffff,option,value,&len,0); + CHECK(result==0&&dm_net_errno()==77);CHECK(len==size);CHECK(preps==before+1&&last_prep==value&&last_len==size); + int expected[2]={kind==0?SOCK_DGRAM:0,0};CHECK(!memcmp(value,expected,size));CHECK(value[-1]==0xa5&&value[size]==0xa5); + CHECK(nvn_dirty_since(value,size,stamp)); + if(kind!=2)CHECK(!nvn_dirty_since(mem+page,page,stamp)); + else CHECK(nvn_dirty_since(mem,page,stamp)&&nvn_dirty_since(mem+page,page,stamp)); + printf("getsockopt kind%d: result%d errno%d preps%u\n",kind,result,dm_net_errno(),preps-before); + nvn_dirty_remove_range(mem);CHECK(!munmap(mem,page*2));CHECK(!dm_net_close(guest)); +} +static void socket_option_invalid(void) { + size_t page=(size_t)getpagesize();int guest=dm_net_socket(2,1,6);assert(guest>=0); + for(int inaccessible=0;inaccessible<2;inaccessible++) { + void *mem=mmap(NULL,page,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0);assert(mem!=MAP_FAILED);assert(!mprotect(mem,page,inaccessible?PROT_NONE:PROT_READ)); + unsigned len=4;CHECK(dm_net_sockopt(guest,0xffff,0x1008,mem,&len,0)==-1&&dm_net_errno()==14); + CHECK(len==4&&!nvn_dirty_tracked(mem,page));CHECK(!munmap(mem,page)); + } + unsigned len=4;CHECK(dm_net_sockopt(guest,0xffff,0x1008,(void*)1,&len,0)==-1&&dm_net_errno()==14&&!nvn_dirty_tracked((void*)1,4)); + unsigned before=preps;CHECK(dm_net_sockopt(guest,0xffff,0x1008,NULL,&len,0)==-1&&dm_net_errno()==14&&preps==before); + CHECK(dm_net_sockopt(guest,0xffff,0x1008,(void*)1,NULL,0)==-1&&dm_net_errno()==14&&preps==before); + CHECK(dm_net_sockopt(-1,0xffff,0x1008,(void*)1,&len,0)==-1&&dm_net_errno()==9&&preps==before); + CHECK(dm_net_sockopt(guest,0xffff,0x9999,(void*)1,&len,0)==-1&&dm_net_errno()==92&&preps==before); + len=2;CHECK(dm_net_sockopt(guest,0xffff,0x1008,(void*)1,&len,0)==-1&&dm_net_errno()==22&&preps==before);CHECK(!dm_net_close(guest)); +} +static void socket_option_input(void) { + size_t page=(size_t)getpagesize();int *value=mmap(NULL,page,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0);assert(value!=MAP_FAILED);*value=1; + nvn_dirty_add_range(value,page);nvn_dirty_protect(value,page);uint64_t stamp=nvn_dirty_now(); + int guest=dm_net_socket(2,1,6);assert(guest>=0);unsigned len=4,before=preps;dm_net_set_errno(77); + CHECK(dm_net_sockopt(guest,6,1,value,&len,1)==0&&dm_net_errno()==77);CHECK(preps==before&&!nvn_dirty_since(value,page,stamp)&&*value==1); + nvn_dirty_remove_range(value);CHECK(!munmap(value,page));CHECK(!dm_net_close(guest)); +} +static void socket_options(void) { + for(int kind=0;kind<3;kind++)socket_option_output(kind); + socket_option_invalid();socket_option_input(); +} diff --git a/dm/host/tests/t_net_write_stub.c b/dm/host/tests/t_net_write_stub.c new file mode 100644 index 0000000000..28a530bb07 --- /dev/null +++ b/dm/host/tests/t_net_write_stub.c @@ -0,0 +1,4 @@ +// Ordinary-buffer network fixtures have no guest dirty tracker. The dedicated +// t_net_write_prepare fixture supplies a dispatcher into the real tracker. +#include +void dm_guest_write_prepare(void *address, size_t size) { (void)address; (void)size; } diff --git a/dm/host/tests/t_network_clock.c b/dm/host/tests/t_network_clock.c new file mode 100644 index 0000000000..2ab94fd047 --- /dev/null +++ b/dm/host/tests/t_network_clock.c @@ -0,0 +1,228 @@ +// Kernel-state injection plus real host event bindings and SVC handle lifetimes. +#include +static int fixture_ntp_gettime(struct ntptimeval *out); +#define ntp_gettime fixture_ntp_gettime +#include "../hle_network_clock.c" +#undef ntp_gettime +#include "../hle_thread.c" +#include +#include + +struct dm_flags g_flag; +module_t *g_mod; +int g_nmod; +uint64_t g_t0_ns; +__thread _Atomic int dm_host_work; +pthread_key_t g_key18; +void crash_thread_init(void) {} +void guest_thread_init(void) {} +void guest_thread_set_id(uint64_t id) { (void)id; } +void guest_gate_stack(int own_stack) { (void)own_stack; } +void dm_thread_enter(uint64_t entry, uint64_t arg, uint64_t sp) { (void)entry; (void)arg; (void)sp; abort(); } +uint64_t now_ns(void) { return clock_gettime_nsec_np(CLOCK_MONOTONIC); } +uint64_t guest_ns(void) { return now_ns(); } +int dm_detclock_enabled(void) { return 0; } +__thread uint64_t dm_clock_reads; // guest clock reads per thread (hle_os.c in the host; thr_yield reads it) +module_t *module_of(const void *p) { (void)p; return NULL; } +void dm_backtrace(uint64_t fp) { (void)fp; } + +typedef struct { uint32_t wh, rh; int mode; } fixture_event; +static unsigned created, destroyed, reads, checks, failures; +static uint32_t callback_signal; +static _Atomic int callback_payload; +static thr_t *callback_peer; +static struct ntptimeval sample; +static int sample_status; +#define CHECK(c, message) do { checks++; if (!(c)) { failures++; fprintf(stderr, "FAIL: %s\n", message); } } while (0) +static int fixture_ntp_gettime(struct ntptimeval *out) { reads++; *out = sample; errno = EIO; return sample_status; } +static void synced_sample(void) { + sample = (struct ntptimeval){.time = {1700000000, 123456789}, .time_state = TIME_OK, .maxerror = 150000, .esterror = 500000}; + sample_status = TIME_OK; +} +// The tiny SDK adapters use the production SVC layer; they do not mock binding, +// lifetime lookup, signal, clear, close or kernel-handle reuse. +static uint32_t create_event(void *p, int mode, int interprocess) { + CHECK(interprocess == 1, "event is an interprocess SystemEvent"); + uint64_t r[32] = {0}; CHECK(svc_thread(0x45, r) && !r[0], "create kernel event"); + fixture_event *event = p; event->wh = (uint32_t)r[1]; event->rh = (uint32_t)r[2]; event->mode = mode; created++; + if (callback_signal) { + // A real SDK/SVC callback can wake a higher-priority pinned caller + // while Init holds its service lock. The handoff must end when that + // caller blocks on the lock, allowing Init to return and unlock it. + r[0] = callback_signal; CHECK(svc_thread(0x11,r) && !r[0], "SDK callback wakes pinned peer"); + pthread_mutex_lock(&G); int waiting = callback_peer->native_wait; pthread_mutex_unlock(&G); + CHECK(waiting && atomic_load(&callback_payload) == 1, "contended task caller is not guest-runnable during the SDK handoff"); + } + return 0; +} +static uint32_t writable_event(const void *p) { return ((const fixture_event *)p)->wh; } +static void destroy_event(void *p) { + fixture_event *event = p; + uint64_t r[32] = {event->wh}; CHECK(svc_thread(0x16, r) && !r[0], "close event write handle"); + r[0] = event->rh; CHECK(svc_thread(0x16, r) && !r[0], "close event read handle"); + event->wh = event->rh = 0; destroyed++; +} +void *guest_sym(const char *name) { + if (!strcmp(name, "_ZN2nn2os17CreateSystemEventEPNS0_15SystemEventTypeENS0_14EventClearModeEb")) return create_event; + if (!strcmp(name, "_ZN2nn2os30GetWritableHandleOfSystemEventEPKNS0_15SystemEventTypeE")) return writable_event; + if (!strcmp(name, "_ZN2nn2os18DestroySystemEventEPNS0_15SystemEventTypeE")) return destroy_event; + CHECK(0, "unexpected SDK callback"); return NULL; +} +static int try_event(fixture_event *event) { + uint32_t handle = event->rh; + uint64_t r[32] = {0, (uintptr_t)&handle, 1, 0}; + CHECK(svc_thread(0x18, r), "try-wait kernel event"); + if (r[0]) { CHECK(r[0] == R_TIMEOUT, "unsignaled event times out"); return 0; } + if (event->mode) { r[0] = event->rh; CHECK(svc_thread(0x17, r) && !r[0], "auto-clear resets observed event"); } + return 1; +} +extern const struct mach_header_64 _mh_execute_header; +static void *hook(const char *name) { + unsigned long bytes = 0; void *fn = NULL; unsigned count = 0; + const hle_force_ent *entries = (const hle_force_ent *)getsectiondata(&_mh_execute_header, "__DATA", "swforce", &bytes); + for (size_t i = 0; entries && i < bytes / sizeof *entries; i++) if (!strcmp(entries[i].name, name)) { count++; fn = entries[i].fn; } + CHECK(count == 1 && fn, name); return fn; +} +#define CLOCK_SYMBOL(suffix) "_ZN2nn4time39AsyncEnsureNetworkClockAvailabilityTask" suffix +static void *repeat_start(void *object) { + for (unsigned i = 0; i < 100; i++) if (h_time_NcStart(object) != RES_OK) return (void *)1; + return NULL; +} +static uint32_t callback_wait_handle; +static void *callback_object; +static void *callback_worker(void *unused) { + (void)unused; pthread_setspecific(g_keythr,callback_peer); + uint32_t handle = callback_wait_handle; + uint64_t r[32] = {0,(uintptr_t)&handle,1,(uint64_t)-1}; svc_thread(0x18,r); + if (r[0]) { atomic_store(&callback_payload,-1); thread_exit(callback_peer); return NULL; } + atomic_store(&callback_payload,1); + Result result = h_time_NcResult(callback_object); + atomic_store(&callback_payload,result != RES_OK ? 2 : -2); + thread_exit(callback_peer); return NULL; +} +static void callback_handoff(void) { + uint64_t key = 0; + h_time_NcCtor(&key); callback_object = &key; + uint64_t r[32] = {0}; CHECK(svc_thread(0x45,r) && !r[0], "create callback handoff event"); + uint32_t write_handle = (uint32_t)r[1]; + callback_signal = write_handle; callback_wait_handle = (uint32_t)r[2]; + thr_t *self = cur(); uint64_t saved_mask = self->mask; int saved_core = self->core, saved_priority = self->prio; + self->mask = 1; self->core = 0; self->prio = 44; + callback_peer = calloc(1,sizeof *callback_peer); + if (!callback_peer) abort(); + pthread_cond_init(&callback_peer->cv,NULL); pthread_cond_init(&callback_peer->pcv,NULL); + callback_peer->started = 1; callback_peer->prio = 30; callback_peer->core = 0; callback_peer->mask = 1; + pthread_mutex_lock(&G); callback_peer->handle = h_new(O_THREAD,callback_peer); callback_peer->all = g_all; g_all = callback_peer; pthread_mutex_unlock(&G); + pthread_t thread; int error = pthread_create(&thread,NULL,callback_worker,NULL); + CHECK(!error,"start pinned guest peer"); + if (!error) { + alarm(5); + for (;;) { pthread_mutex_lock(&G); int waiting = callback_peer->wkind == 4; pthread_mutex_unlock(&G); if (waiting) break; usleep(100); } + // Plain pthread_mutex_lock in the production registry makes this exact + // callback deadlock. The alarm bounds a failed regression run. + CHECK(h_time_NcInit(&key,0) == RES_OK,"initialization returns from its real scheduler handoff"); + alarm(0); callback_signal = 0; + pthread_join(thread,NULL); + CHECK(atomic_load(&callback_payload) == 2,"peer resumes after initialization releases the lock"); + } + callback_signal = 0; + h_time_NcDtor(&key); + r[0] = callback_wait_handle; CHECK(svc_thread(0x16,r) && !r[0],"close callback read handle"); + r[0] = write_handle; CHECK(svc_thread(0x16,r) && !r[0],"close callback write handle"); + pthread_mutex_lock(&G); + for (thr_t **p = &g_all; *p; p = &(*p)->all) if (*p == callback_peer) { *p = callback_peer->all; break; } + g_h[callback_peer->handle - 0x1000].type = O_FREE; g_h[callback_peer->handle - 0x1000].obj = NULL; + pthread_mutex_unlock(&G); + pthread_cond_destroy(&callback_peer->cv); pthread_cond_destroy(&callback_peer->pcv); + free(callback_peer); callback_peer = NULL; + self->mask = saved_mask; self->core = saved_core; self->prio = saved_priority; +} +int main(void) { + svc_thread_main_init(); synced_sample(); + unsigned (*accurate)(void) = hook("_ZN2nn4time26StandardNetworkSystemClock20IsAccuracySufficientEv"); + void (*ctor)(void *) = hook(CLOCK_SYMBOL("C1Ev")); + void (*dtor)(void *) = hook(CLOCK_SYMBOL("D1Ev")); + Result (*init)(void *, int) = hook(CLOCK_SYMBOL("10InitializeENS_2os14EventClearModeE")); + Result (*start)(void *) = hook(CLOCK_SYMBOL("9StartTaskEv")); + void *(*event)(void *) = hook(CLOCK_SYMBOL("14GetFinishEventEv")); + Result (*result)(void *) = hook(CLOCK_SYMBOL("9GetResultEv")); + if (!accurate || !ctor || !dtor || !init || !start || !event || !result) return 1; + unsigned before; + // GetCurrentTime is hle_time.c's (the host clock, t_time); here only whether the kernel says the clock is synchronized + errno = EDOM; + CHECK(accurate() && errno == EDOM, "a synchronized kernel clock is accurate, and the query preserves errno"); + setenv("DM_FIXED_TIME", "1", 1); setenv("DM_NETWORK", "offline", 1); + CHECK(accurate(), "accuracy does not use fixed/user time or launcher protocol selection"); + for (int test = 0; test < 9; test++) { + synced_sample(); + switch (test) { + case 0: sample_status = -1; break; + case 1: sample_status = TIME_ERROR; sample.time_state = TIME_ERROR; break; + case 2: sample.time_state = TIME_ERROR; break; + case 3: sample.maxerror = 1000001; break; + case 4: sample.esterror = 1000001; break; + case 5: sample.maxerror = -1; break; + case 6: sample.esterror = -1; break; + case 7: sample.time.tv_sec = 0; break; + default: sample.time.tv_nsec = 1000000000; break; + } + errno = EDOM; + CHECK(!accurate(), "bad kernel status/precision/structure fails closed"); + CHECK(errno == EDOM, "failed query preserves errno"); + } + synced_sample(); sample.time.tv_nsec = -1; + CHECK(!accurate(), "negative fractional time fails"); + synced_sample(); sample.maxerror = sample.esterror = 1000000; + CHECK(accurate(), "exactly one second error bound is accepted"); + sample_status = TIME_INS; sample.time_state = TIME_INS; + CHECK(!accurate(), "leap-warning state fails conservatively"); + synced_sample(); + uint64_t a[3] = {0xabc,0xdef,0x123}, b[3] = {0xabc,0xdef,0x123}; + CHECK(start(a) != 0 && !event(a) && result(a) != 0, "unconstructed task cannot complete"); + ctor(a); ctor(b); before = reads; + CHECK(!event(a) && result(a) != 0 && start(a) != 0 && reads == before, "constructor does not create completion or read time"); + CHECK(init(a, 2) != 0 && !event(a), "invalid clear mode creates no event"); + CHECK(init(a, 0) == 0 && init(b, 1) == 0, "two clear modes initialize independently"); + fixture_event *ae = event(a), *be = event(b); + CHECK(ae && be && ae != be && ae->mode == 0 && be->mode == 1, "each task owns its SDK event with the requested mode"); + CHECK(!try_event(ae) && !try_event(be) && result(a) != 0, "GetFinishEvent does not signal before StartTask"); + before = reads; CHECK(start(a) == 0 && reads == before + 1 && result(a) == 0, "StartTask performs one real query before publishing its result"); + CHECK(try_event(ae) && try_event(ae) && !try_event(be), "manual completion stays signaled without completing the other task"); + sample_status = TIME_ERROR; sample.time_state = TIME_ERROR; + CHECK(start(b) == 0 && result(b) != 0 && try_event(be) && !try_event(be), "unsynchronized task completes with failure and auto-clear event"); + CHECK(result(a) == 0, "another task's failure does not replace the first result"); + CHECK(start(a) == 0 && result(a) != 0 && try_event(ae), "restarting a completed task uses a new query and replaces stale success"); + synced_sample(); CHECK(start(b) == 0 && result(b) == 0 && try_event(be) && !try_event(be), "a later actual synchronization can recover with a fresh completion"); + before = created; CHECK(init(a, 0) == 0 && init(a, 1) != 0 && created == before, "reinitialize is idempotent only for the same clear mode"); + uint64_t old_binding = hle_system_event_binding(ae); uint32_t old_handle = ae->wh; + dtor(a); CHECK(result(a) != 0 && start(a) != 0 && !event(a), "destroyed task is unavailable"); + ctor(a); CHECK(init(a, 0) == 0, "object storage can be reused"); ae = event(a); + CHECK(ae->wh == old_handle && hle_system_event_binding(ae) != old_binding, "reused handle has a new binding lifetime"); + CHECK(!hle_signal_system_event_binding(old_binding) && !try_event(ae), "stale completion cannot signal the replacement event"); + CHECK(a[0] == 0xabc && a[1] == 0xdef && a[2] == 0x123 && !memcmp(a,b,sizeof a), "SDK-private task storage stays untouched"); + dtor(a); dtor(a); dtor(b); ctor(NULL); dtor(NULL); + CHECK(clock_task_count == 0 && g_nse == 0 && created == destroyed, "all events and registry entries retire exactly once"); + // Capacity failure is recoverable, not a borrowed event from another task. + uint8_t keys[NETWORK_CLOCK_MAX_TASKS + 1]; + for (unsigned i = 0; i < sizeof keys; i++) ctor(&keys[i]); + CHECK(clock_task_count == NETWORK_CLOCK_MAX_TASKS && init(&keys[NETWORK_CLOCK_MAX_TASKS],0) != 0, "registry capacity fails closed"); + for (unsigned i = 0; i < sizeof keys; i++) dtor(&keys[i]); + CHECK(clock_task_count == 0, "bounded registry capacity is reusable"); + // Completed tasks can be queried/restarted independently on different + // callers; signaling uses the real host kernel lock and captured lifetime. + ctor(a); ctor(b); CHECK(!init(a,0) && !init(b,1), "prepare concurrent tasks"); + pthread_t threads[2]; + int first = pthread_create(&threads[0],NULL,repeat_start,a); + int second = pthread_create(&threads[1],NULL,repeat_start,b); + CHECK(!first && !second, "start concurrent task callers"); + void *first_result = (void *)1, *second_result = (void *)1; + if (!first) pthread_join(threads[0], &first_result); + if (!second) pthread_join(threads[1], &second_result); + CHECK(!first_result && !second_result && !result(a) && !result(b), "concurrent completed results remain independent"); + dtor(a); dtor(b); + CHECK(clock_task_count == 0 && g_nse == 0 && created == destroyed, "concurrent task cleanup leaks no events"); + callback_handoff(); + CHECK(clock_task_count == 0 && g_nse == 0 && created == destroyed,"SDK handoff cleanup retires the clock event"); + printf("network clock: %u checks, %u failed\n", checks, failures); + return failures != 0; +} diff --git a/dm/host/tests/t_nextendo_account.m b/dm/host/tests/t_nextendo_account.m new file mode 100644 index 0000000000..51f31ef920 --- /dev/null +++ b/dm/host/tests/t_nextendo_account.m @@ -0,0 +1,262 @@ +// Exact account HLE hooks with synthetic proof metadata only. The test provider +// prevents every Keychain/document read; no fixture can authenticate to Nextendo. +#import +#import +#include "../hle.h" +#include "t_gate_fixture.h" +#include "../nextendo_account.h" +#include "../net_socket.h" +#include "../account_users.h" +#include "../front.h" +#include +#include +#include +#include +#include +#import "../nextendo_login_apple.inc" // the sign-in (hle_nextendo_login_apple.m): its record must pass this decoder +#import "../nextendo_api_apple.h" + +static int checks, failures; +static _Atomic int entered, left, waits, providerCalls; +static dm_net_mode_t mode = DM_NET_NEXTENDO; +static NSData *fixture; +static pthread_mutex_t providerLock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t providerCondition = PTHREAD_COND_INITIALIZER; +static bool blockProvider, providerWaiting; +static char contextA[64], contextB[64]; +typedef struct { uint64_t id; bool signaled; } TestEvent; +static TestEvent *events[32]; static unsigned eventCount; static uint64_t nextEvent; +static unsigned deletes; +#define CHECK(value, message) do { checks++; if (!(value)) { failures++; fprintf(stderr, "FAIL line %d: %s\n", __LINE__, message); } } while (0) +dm_net_mode_t dm_net_mode(void) { return mode; } +void dm_guest_host_wait_begin(void) { atomic_fetch_add(&waits, 1); } +void dm_guest_host_wait_end(void) {} +// The account file's local user selector (seedds's multi-user accounts): never opened here. t_gate_fixture.h has the applet bookkeeping +void dm_thread_native_wait(int entering) { (void)entering; } +int front_user_select(const front_user *users, int n, int create, int skip) { (void)users; (void)n; (void)create; (void)skip; abort(); } +void thr_svc_enter(uint64_t *regs, uint64_t pc) { (void)regs; (void)pc; atomic_fetch_add(&entered, 1); } +void thr_svc_leave(void) { atomic_fetch_add(&left, 1); } +int dm_guest_as_contains(uintptr_t address) { (void)address; return 0; } +uint64_t gate_dispatch(uint64_t ret, uint64_t *regs) { (void)ret; (void)regs; abort(); } +uint64_t unimpl_c(unsigned index, uint64_t *regs) { (void)index; (void)regs; abort(); } +void dm_thread_returned(void) { abort(); } +static void guest_delete(void *pointer) { deletes++; free(pointer); } +void *guest_sym(const char *name) { return !strcmp(name, "_ZdlPv") ? guest_delete : NULL; } +void hle_bind_system_event(void *pointer, int clear) { (void)clear; TestEvent *event = pointer; if (!event->id) { event->id = ++nextEvent; event->signaled = false; events[eventCount++] = event; } } +uint64_t hle_system_event_binding(void *pointer) { return ((TestEvent *)pointer)->id; } +int hle_signal_system_event_binding(uint64_t binding) { for (unsigned i = 0; i < eventCount; i++) if (events[i] && events[i]->id == binding) { events[i]->signaled = true; return 1; } return 0; } +void hle_signal_system_event(void *pointer) { hle_bind_system_event(pointer, 0); hle_signal_system_event_binding(hle_system_event_binding(pointer)); } +static void close_event(TestEvent *event) { for (unsigned i = 0; i < eventCount; i++) if (events[i] == event) events[i] = NULL; event->id = 0; event->signaled = false; } +static void *hook(const char *name) { + fixture_gate_prepare(); + unsigned long size; const hle_force_ent *table = (const hle_force_ent *)getsectiondata(&_mh_execute_header, "__DATA", "swforce", &size); + for (unsigned long i = 0; table && i < size / sizeof *table; i++) if (!strcmp(table[i].name, name)) return table[i].fn; + fprintf(stderr, "Missing account hook: %s\n", name); abort(); +} +#define H(type, name) ((type)hook(name)) +static bool provider(uint8_t *buffer, size_t capacity, size_t *size) { + atomic_fetch_add(&providerCalls, 1); pthread_mutex_lock(&providerLock); providerWaiting = true; pthread_cond_broadcast(&providerCondition); + while (blockProvider) pthread_cond_wait(&providerCondition, &providerLock); + NSData *data = fixture; bool okay = data && data.length <= capacity; if (okay) { memcpy(buffer, data.bytes, data.length); *size = data.length; } pthread_mutex_unlock(&providerLock); return okay; +} +static NSString *b64(NSData *data) { NSString *s = [[data base64EncodedStringWithOptions:0] stringByReplacingOccurrencesOfString:@"+" withString:@"-"]; return [[s stringByReplacingOccurrencesOfString:@"/" withString:@"_"] stringByReplacingOccurrencesOfString:@"=" withString:@""]; } +static NSData *unb64(NSString *s) { NSString *n = [[s stringByReplacingOccurrencesOfString:@"-" withString:@"+"] stringByReplacingOccurrencesOfString:@"_" withString:@"/"]; n = [n stringByPaddingToLength:(n.length + 3) & ~(NSUInteger)3 withString:@"=" startingAtIndex:0]; return [[NSData alloc] initWithBase64EncodedString:n options:0]; } +static NSMutableDictionary *valid_record(void) { + uint64_t expiry = (uint64_t)NSDate.date.timeIntervalSince1970 + 3600; NSString *payload = [NSString stringWithFormat:@"1800000042.synthetic_user.%llu", expiry]; + uint8_t invalidHmac[32] = {0}; NSString *token = [NSString stringWithFormat:@"nx2.%@.%@", b64([payload dataUsingEncoding:NSUTF8StringEncoding]), b64([NSData dataWithBytes:invalidHmac length:32])]; + return [@{@"schema_version":@1, @"token_kind":@"nex", @"token":token, @"identity":@{@"pid":@1800000042ull, @"username":@"synthetic_user", @"friend_code":@"test-only"}, @"scopes":@[@"identity"], @"created_at":@((uint64_t)NSDate.date.timeIntervalSince1970 - 30), @"expires_at":@(expiry)} mutableCopy]; +} +static void set_record(NSDictionary *record) { pthread_mutex_lock(&providerLock); fixture = record ? [NSJSONSerialization dataWithJSONObject:record options:0 error:nil] : nil; pthread_mutex_unlock(&providerLock); } +static void identity_tests(void) { + NSMutableDictionary *record = valid_record(); set_record(record); uint64_t pid = 0; uint8_t available = 0; + CHECK(dm_nextendo_account_available(&available) == 0 && available && dm_nextendo_account_id(&pid) == 0 && pid == 1800000042ull, "real metadata PID is returned without a fabricated fallback"); + char name[33] = "x", nick[33]; + CHECK(dm_nextendo_account_username(name) == 0 && !strcmp(name, "synthetic_user"), "the username is the signed-in record's"); + const uint64_t launch_uid[2] = {DM_UID0, DM_UID1}; // user 1, registered without a save store (hle_account_users.c) + unsetenv("DM_NICK"); + CHECK(H(uint32_t (*)(char *, const void *), "_ZN2nn7account11GetNicknameEPNS0_8NicknameERKNS0_3UidE")(nick, launch_uid) == 0 && !strcmp(nick, "Player"), "before the game opens a user, no user is the Nextendo account's"); + uint64_t opened[3]; CHECK(H(uint32_t (*)(void *), "_ZN2nn7account19OpenPreselectedUserEPNS0_10UserHandleE")(opened) == 0, "the game opens the launch user: it becomes the active user"); + CHECK(H(uint32_t (*)(char *, const void *), "_ZN2nn7account11GetNicknameEPNS0_8NicknameERKNS0_3UidE")(nick, launch_uid) == 0 && !strcmp(nick, "synthetic_user"), "Nextendo mode: the nickname is the account's username"); + int calls = atomic_load(&providerCalls); + for (unsigned i = 0; i < 3; i++) { mode = (dm_net_mode_t)i; available = 9; pid = 9; CHECK(dm_nextendo_account_available(&available) == 0 && !available && dm_nextendo_account_id(&pid) != 0 && !pid && dm_nextendo_account_ensure() != 0, "offline/LAN/LDN never load an online credential"); } + CHECK(atomic_load(&providerCalls) == calls, "disabled modes do not query credentials"); mode = DM_NET_AUTO; + NSArray *bad = @[@{@"token_kind":@"oauth"}, @{@"schema_version":@1.5}, @{@"schema_version":@YES}, @{@"expires_at":@1}, @{@"expires_at":@1e20}, @{@"created_at":@1e20}, @{@"scopes":@"identity"}, @{@"identity":@{@"pid":@1800000043ull,@"username":@"synthetic_user"}}, @{@"identity":@{@"pid":@1800000042ull,@"username":@"someone_else"}}, @{@"token":@"nx2.invalid.invalid"}, @{@"token":@"oauth-access-token"}, @{@"token":@"nx2. .invalid"}]; + for (NSDictionary *changes in bad) { NSMutableDictionary *wrong = record.mutableCopy; [wrong addEntriesFromDictionary:changes]; set_record(wrong); available = 9; pid = 9; CHECK(dm_nextendo_account_available(&available) == 0 && !available && dm_nextendo_account_id(&pid) != 0 && !pid, "malformed/OAuth/expired/incoherent data never enables NSA"); } + set_record(nil); CHECK(dm_nextendo_account_ensure() != 0, "missing credential fails honestly"); set_record(record); +} +static uint64_t user[3]; +static void token_tests(void) { + CHECK(H(uint32_t (*)(void *), "_ZN2nn7account19OpenPreselectedUserEPNS0_10UserHandleE")(user) == 0, "actual UserHandle issued by host"); + uint64_t pid = 0; CHECK(H(uint32_t (*)(uint64_t *, const void *), "_ZN2nn7account26GetNetworkServiceAccountIdEPNS0_23NetworkServiceAccountIdERKNS0_10UserHandleE")(&pid, user) == 0 && pid == 1800000042ull, "SDK4/19 NSA output is exactly one UInt64"); + uint64_t wrong[3] = {user[0] ^ 1, user[1], user[2]}; pid = 9; + CHECK(H(uint32_t (*)(uint64_t *, const void *), "_ZN2nn7account26GetNetworkServiceAccountIdEPNS0_23NetworkServiceAccountIdERKNS0_10UserHandleE")(&pid, wrong) != 0 && !pid, "only the linked local user can obtain the online PID"); + dm_nextendo_set_game_version("3.0.5"); uint64_t size = 0; char bytes[8193]; memset(bytes, 0x6a, sizeof bytes); + typedef uint32_t (*Load)(uint64_t *, char *, uint64_t, const void *); + Load load = H(Load, "_ZN2nn7account37LoadNetworkServiceAccountIdTokenCacheEPmPcmRKNS0_10UserHandleE"); + CHECK(load(&size, bytes, 16, user) != 0 && size > 16 && bytes[0] == 0x6a, "short cache buffer reports needed length without overwriting it"); + CHECK(load(&size, bytes, 8192, user) == 0 && size < 3072 && bytes[size] == 0 && bytes[8192] == 0x6a, "token cache is bounded and NUL-terminated; reported size excludes NUL"); + NSString *jwt = [[NSString alloc] initWithBytes:bytes length:(NSUInteger)size encoding:NSASCIIStringEncoding]; NSArray *segments = [jwt componentsSeparatedByString:@"."]; CHECK(segments.count == 3, "compact signed envelope contains three segments"); + if (segments.count != 3) return; + NSData *headerBytes=unb64(segments[0]), *claimBytes=unb64(segments[1]); + CHECK(headerBytes && claimBytes,"synthetic envelope JSON segments decode before parsing"); + if (!headerBytes || !claimBytes) return; + NSDictionary *header = [NSJSONSerialization JSONObjectWithData:headerBytes options:0 error:nil], *claims = [NSJSONSerialization JSONObjectWithData:claimBytes options:0 error:nil]; + NSDictionary *original = [NSJSONSerialization JSONObjectWithData:fixture options:0 error:nil]; + CHECK([header[@"alg"] isEqual:@"RS256"] && [header[@"typ"] isEqual:@"id_token"] && [header[@"kid"] isEqual:@"nextendo-baas-key-1"] && [claims[@"nnex"] isEqual:original[@"token"]] && [claims[@"tv"] isEqual:@"3.0.5"], "Nextendo clients' BaaS header, untouched NEX proof and original game version"); + CHECK([claims[@"iss"] isEqual:@"https://e0d67c509fb203858ebcb2fe3f88c2aa.baas.nintendo.com"] && [claims[@"aud"] isEqual:@"ed9e2f05d286f7b8"] && [claims[@"hm"] isEqual:@YES] && [claims[@"sub"] length] == 32 && [claims[@"bs:did"] length] == 32 && !claims[@"country"] && !claims[@"app_id"], + "the claims Ryujinx-Nextendo and Mush8 send (issuer, audience, membership, random IDs), no country and no app_id for this game"); + CHECK([claims[@"exp"] doubleValue] <= [original[@"expires_at"] doubleValue] && [claims[@"nbf"] isEqual:claims[@"iat"]], "expiry bounded by the proof"); + uint8_t publicKeyBytes[1024]; uint64_t keySize = 0; CHECK(dm_nextendo_copy_public_signing_key(publicKeyBytes, sizeof publicKeyBytes, &keySize) == 0 && keySize, "only the ephemeral public key is exported for verification"); + NSData *keyData = [NSData dataWithBytes:publicKeyBytes length:(NSUInteger)keySize]; SecKeyRef key = SecKeyCreateWithData((__bridge CFDataRef)keyData, (__bridge CFDictionaryRef)@{(__bridge id)kSecAttrKeyType:(__bridge id)kSecAttrKeyTypeRSA, (__bridge id)kSecAttrKeyClass:(__bridge id)kSecAttrKeyClassPublic}, NULL); + NSData *signedBytes = [[NSString stringWithFormat:@"%@.%@", segments[0], segments[1]] dataUsingEncoding:NSASCIIStringEncoding]; + CHECK(key && SecKeyVerifySignature(key, kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA256, (__bridge CFDataRef)signedBytes, (__bridge CFDataRef)unb64(segments[2]), NULL), "envelope signature verifies with the process's own public key"); if (key) CFRelease(key); + char second[8192]; uint64_t again = 0; CHECK(load(&again, second, sizeof second, user) == 0 && again == size && !memcmp(second, bytes, (size_t)size), "unchanged proof/version uses the cache without reminting a token"); + dm_nextendo_set_game_version("3.0.6"); CHECK(load(&again, second, sizeof second, user) == 0 && memcmp(second, bytes, (size_t)MIN(again, size)), "actual game-version change invalidates token cache"); dm_nextendo_set_game_version("3.0.5"); + NSMutableDictionary *oauth = valid_record(); oauth[@"token_kind"] = @"oauth"; set_record(oauth); again = 99; + CHECK(load(&again, second, sizeof second, user) != 0 && !again, "a cached game token cannot survive replacement by an OAuth social session"); set_record(valid_record()); +} +typedef struct { void *context; uint32_t result; } Worker; +static void *ensure_worker(void *pointer) { Worker *worker = pointer; worker->result = H(uint32_t (*)(void *, const void *), "_ZN2nn7account44EnsureNetworkServiceAccountIdTokenCacheAsyncEPNS0_12AsyncContextERKNS0_10UserHandleE")(worker->context, user); return NULL; } +static pthread_t pending(Worker *worker) { + pthread_mutex_lock(&providerLock); blockProvider = true; providerWaiting = false; pthread_mutex_unlock(&providerLock); + pthread_t thread; CHECK(pthread_create(&thread, NULL, ensure_worker, worker) == 0, "start real concurrent token request"); + pthread_mutex_lock(&providerLock); while (!providerWaiting) pthread_cond_wait(&providerCondition, &providerLock); pthread_mutex_unlock(&providerLock); return thread; +} +static void release_provider(pthread_t thread) { pthread_mutex_lock(&providerLock); blockProvider = false; pthread_cond_broadcast(&providerCondition); pthread_mutex_unlock(&providerLock); CHECK(pthread_join(thread, NULL) == 0, "credential operation returned"); } +static uint32_t service_operation(const void *value) { return *(const uint32_t *)value; } +// The SDK's own constructor builds an AsyncContext (hle_account.c leaves it alone): it writes guest memory the host never reads, so here it writes nothing either +static void sdk_ctor(void *self) { (void)self; } +static void async_tests(void) { + typedef void (*Ctor)(void *); typedef uint32_t (*Object)(void *); typedef uint32_t (*Event)(void *, void *); + Ctor ctor = sdk_ctor, dtor = H(Ctor, "_ZN2nn7account12AsyncContextD1Ev"); + Object result = H(Object, "_ZN2nn7account12AsyncContext9GetResultEv"); Event event = H(Event, "_ZN2nn7account12AsyncContext14GetSystemEventEPNS_2os11SystemEventE"); + memset(contextA, 0xa5, sizeof contextA); memset(contextB, 0x5a, sizeof contextB); ctor(contextA); TestEvent completion = {0}; uint8_t done = 9; + CHECK(result(contextA) != 0 && event(contextA, &completion) != 0 && !completion.id, "empty context has no invented completion request"); + Worker work = {contextA, 99}; pthread_t thread = pending(&work); + CHECK(dm_nextendo_async_done(contextA, &done) == 0 && !done && event(contextA, &completion) == 0 && !completion.signaled, "pending operation exposes an unsignaled real event binding"); + release_provider(thread); CHECK(work.result == 0 && completion.signaled && result(contextA) == 0, "success and completion event publish only after actual token creation"); + typedef uint32_t (*Kind)(void *); Kind kind = H(Kind, "_ZN2nn7account37AsyncNetworkServiceLicenseInfoContext28GetNetworkServiceLicenseKindEv"); + CHECK(kind(contextA) == 1 && kind(contextB) == 0, "membership reads subscribed only for a completed successful request"); + CHECK(H(Object, "_ZN2nn7account12AsyncContext6CancelEv")(contextA) == 0 && result(contextA) == 0, "cancel after completion does not rewrite a completed success"); + CHECK(contextA[0] == (char)0xa5 && contextB[0] == 0x5a, "SDK4/19 private object memory remains untouched"); close_event(&completion); dtor(contextA); + ctor(contextA); work = (Worker){contextA,99}; thread = pending(&work); CHECK(event(contextA, &completion) == 0, "attach cancel completion event"); + CHECK(H(Object, "_ZN2nn7account12AsyncContext6CancelEv")(contextA) == 0 && completion.signaled && result(contextA) != 0, "cancel publishes failure and signals completion"); + release_provider(thread); CHECK(result(contextA) != 0, "late success cannot overwrite cancellation"); close_event(&completion); dtor(contextA); + ctor(contextA); ctor(contextB); work = (Worker){contextA,99}; thread = pending(&work); uint64_t lifetime = dm_nextendo_async_lifetime(contextA); + CHECK(H(void *(*)(void *,void *), "_ZN2nn7account12AsyncContextaSEOS1_")(contextB,contextA) == contextB && !dm_nextendo_async_valid(contextA) && dm_nextendo_async_lifetime(contextB) == lifetime, "move preserves pending state and empties its source"); + CHECK(event(contextB, &completion) == 0, "attach event after moving a pending request"); release_provider(thread); + CHECK(completion.signaled && H(Object, "_ZNK2nn7account12AsyncContext9GetResultEv")(contextB) == 0, "SDK19 const result observes completion after move"); close_event(&completion); dtor(contextA); dtor(contextB); + ctor(contextA); CHECK(dm_nextendo_async_ensure(contextA) == 0 && result(contextA) == 0, "initial request before output-context reuse"); lifetime = dm_nextendo_async_lifetime(contextA); + CHECK(dm_nextendo_async_ensure(contextA) == 0 && result(contextA) == 0 && dm_nextendo_async_lifetime(contextA) != lifetime, "completed output context can receive a fresh request lifetime"); + ctor(contextB); H(void (*)(void *, void *), "_ZN2nn7account12AsyncContext4SwapERS1_")(contextA, contextB); + CHECK(result(contextA) != 0 && result(contextB) == 0, "swap exchanges completed state and an empty context"); dtor(contextA); dtor(contextB); + NSMutableDictionary *oauth = valid_record(); oauth[@"token_kind"] = @"oauth"; set_record(oauth); ctor(contextA); + CHECK(dm_nextendo_async_ensure(contextA) == 0 && result(contextA) != 0 && dm_nextendo_async_done(contextA, &done) == 0 && done, "queued OAuth-only cache request completes with failure, never game authentication"); dtor(contextA); set_record(valid_record()); + ctor(contextA); work = (Worker){contextA,99}; thread = pending(&work); CHECK(event(contextA, &completion) == 0, "attach event before destruction"); + dtor(contextA); close_event(&completion); hle_bind_system_event(&completion, 0); uint64_t fresh = completion.id; ctor(contextA); release_provider(thread); + CHECK(completion.id == fresh && !completion.signaled && result(contextA) != 0, "late work cannot signal a reused event or publish into a reconstructed context"); close_event(&completion); dtor(contextA); + void *heap_context = malloc(64); ctor(heap_context); H(Ctor, "_ZN2nn7account12AsyncContextD0Ev")(heap_context); + CHECK(deletes == 1 && !dm_nextendo_async_valid(heap_context), "deleting destructor releases host state and calls the guest's allocator exactly once"); + ctor(contextA); uint32_t service_result=0x1234; + CHECK(dm_nextendo_async_execute(contextA,service_operation,&service_result)==0 && result(contextA)==service_result && !dm_nextendo_async_done(contextA,&done) && done, "service operation preserves its real failure result and completed state"); + service_result=0; CHECK(dm_nextendo_async_execute(contextA,service_operation,&service_result)==0 && !result(contextA), "a later service request has its own real completion"); + mode=DM_NET_LAN; CHECK(dm_nextendo_async_execute(contextA,service_operation,&service_result)!=0, "local modes do not execute a provider service operation"); mode=DM_NET_NEXTENDO; dtor(contextA); + // A move constructor builds the object, so it writes the SDK's vtable (taken from the source) and a null IPC pointer at +0x18, and moves the request state + ctor(contextA); CHECK(dm_nextendo_async_ensure(contextA) == 0 && result(contextA) == 0, "request before move construction"); lifetime = dm_nextendo_async_lifetime(contextA); + memset(contextA, 0x11, 8); memset(contextB, 0x5a, sizeof contextB); H(void (*)(void *, void *), "_ZN2nn7account12AsyncContextC1EOS1_")(contextB, contextA); + void *ipc; memcpy(&ipc, contextB + 0x18, sizeof ipc); + CHECK(!memcmp(contextB, contextA, 8) && !ipc && contextB[8] == 0x5a, "move construction writes the vtable and IPC pointer, and nothing else"); + CHECK(dm_nextendo_async_lifetime(contextB) == lifetime && !dm_nextendo_async_valid(contextA) && result(contextB) == 0, "move construction carries the completed request"); dtor(contextA); dtor(contextB); + // Nextendo off, a context answers as the offline host always has, whatever was constructed + mode=DM_NET_OFFLINE; ctor(contextA); TestEvent offline = {0}; done = 0; + CHECK(dm_nextendo_async_ensure(contextA) != 0 && !dm_nextendo_async_valid(contextA), "offline: no request starts"); + CHECK(event(contextA, &offline) == 0 && offline.signaled, "offline: the completion event fires immediately"); + CHECK(H(Event, "_ZN2nn7account12AsyncContext7HasDoneEPb")(contextA, &done) == 0 && done, "offline: the context is done"); + CHECK(result(contextA) != 0 && H(Object, "_ZN2nn7account12AsyncContext6CancelEv")(contextA) == 0, "offline: the result is failure and cancel has nothing to cancel"); + close_event(&offline); dtor(contextA); mode=DM_NET_NEXTENDO; +} +static dispatch_semaphore_t loginCancelled; +@interface LoginReply : NSURLProtocol +@end +@implementation LoginReply ++ (BOOL)canInitWithRequest:(NSURLRequest *)request { return [request.URL.host isEqual:@"login.test"]; } ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { return request; } +- (void)startLoading { + NSString *path = self.request.URL.path; + if ([path isEqual:@"/stall"]) return; + BOOL declared = [path isEqual:@"/declared"], streamed = [path isEqual:@"/streamed"]; + NSHTTPURLResponse *reply = [[NSHTTPURLResponse alloc] initWithURL:self.request.URL statusCode:200 HTTPVersion:@"HTTP/1.1" + headerFields:declared ? @{@"Content-Length": @"65537"} : @{}]; + [self.client URLProtocol:self didReceiveResponse:reply cacheStoragePolicy:NSURLCacheStorageNotAllowed]; + [self.client URLProtocol:self didLoadData:[@"{\"ok\":true}" dataUsingEncoding:NSUTF8StringEncoding]]; + if (streamed) [self.client URLProtocol:self didLoadData:[NSMutableData dataWithLength:65536]]; + [self.client URLProtocolDidFinishLoading:self]; +} +- (void)stopLoading { + if ([self.request.URL.path isEqual:@"/stall"]) dispatch_semaphore_signal(loginCancelled); +} +@end + +static void login_http_tests(void) { + NSURLSessionConfiguration *config = NSURLSessionConfiguration.ephemeralSessionConfiguration; + config.protocolClasses = @[LoginReply.class]; + NSString *error = nil; + CHECK([nxl_send_with_config(nxl_request(@"https://login.test/ok", 2), config, &error)[@"ok"] isEqual:@YES], "a small JSON reply is accepted"); + for (NSString *kind in @[@"declared", @"streamed"]) { + error = nil; + CHECK(!nxl_send_with_config(nxl_request([@"https://login.test/" stringByAppendingString:kind], 2), config, &error) && + [error isEqual:@"Nextendo's answer is too large"], "oversized replies are rejected"); + } + loginCancelled = dispatch_semaphore_create(0); error = nil; + uint64_t start = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + CHECK(!nxl_send_with_config(nxl_request(@"https://login.test/stall", .25), config, &error) && + [error isEqual:@"Nextendo did not answer in time"] && clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - start < NSEC_PER_SEC, + "a stalled answer cannot leave the synchronous caller waiting"); + CHECK(!dispatch_semaphore_wait(loginCancelled, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC)), "a stalled task is cancelled"); +} + +// The Mac sign-in's pieces that need no network: the record it builds from an nx2 game token passes hle_nextendo_apple.m's own checks, and the stored sign-in +// is a private file that a loose or linked one cannot stand in for +static void login_tests(void) { + NSString *token = valid_record()[@"token"]; NSString *error = nil; NSTimeInterval now = NSDate.date.timeIntervalSince1970; + NSDictionary *record = nxl_record(token, now, &error); + CHECK(record && [record[@"identity"][@"pid"] unsignedLongLongValue] == 1800000042ull && [record[@"identity"][@"username"] isEqual:@"synthetic_user"], "the sign-in's record takes its identity from the token's payload"); + set_record(record); uint8_t available = 0; uint64_t pid = 0; + CHECK(dm_nextendo_account_available(&available) == 0 && available && dm_nextendo_account_id(&pid) == 0 && pid == 1800000042ull, "the sign-in's record passes the account decoder"); + NSString *payload = [NSString stringWithFormat:@"1800000042.synthetic_user.%llu", (unsigned long long)now - 5]; uint8_t mac[32] = {0}; + NSString *stale = [NSString stringWithFormat:@"nx2.%@.%@", b64([payload dataUsingEncoding:NSUTF8StringEncoding]), b64([NSData dataWithBytes:mac length:32])]; + CHECK(!nxl_record(stale, now, &error) && error.length, "an expired game token gives no record"); + CHECK(!nxl_record(@"oauth.abc.def", now, &error) && !nxl_record(@"nx2.bm9uZQ.AA", now, &error), "a token that is not an nx2 one, or names no identity, gives no record"); + char dir[] = "/tmp/t_nextendo_login.XXXXXX"; CHECK(mkdtemp(dir) != NULL, "temporary sign-in folder"); + setenv("DM_NEXTENDO_LOGIN_DIR", dir, 1); + CHECK(!nxl_read_refresh(), "no stored sign-in at first"); + CHECK(nxl_write_refresh(@"synthetic-refresh") && [nxl_read_refresh() isEqual:@"synthetic-refresh"], "the stored sign-in reads back"); + struct stat st; CHECK(!stat(nxl_refresh_path().fileSystemRepresentation, &st) && (st.st_mode & 0777) == 0600, "the stored sign-in is readable by its owner only"); + chmod(nxl_refresh_path().fileSystemRepresentation, 0644); CHECK(!nxl_read_refresh(), "a stored sign-in others can read is refused"); + NSString *link = [[NSString stringWithUTF8String:dir] stringByAppendingPathComponent:@"elsewhere"]; + CHECK(nxl_write_refresh(@"synthetic-refresh") && !rename(nxl_refresh_path().fileSystemRepresentation, link.fileSystemRepresentation) && !symlink(link.fileSystemRepresentation, nxl_refresh_path().fileSystemRepresentation) && !nxl_read_refresh(), "a linked stored sign-in is refused"); + unlink(nxl_refresh_path().fileSystemRepresentation); unlink(link.fileSystemRepresentation); + CHECK(nxl_write_refresh(@"synthetic-refresh") && nxl_write_refresh(nil) && !nxl_read_refresh(), "sign-out removes the stored sign-in"); + unsetenv("DM_NEXTENDO_LOGIN_DIR"); rmdir(dir); set_record(valid_record()); +} +NSString *dm_nextendo_login_access(void) { return @"synthetic-access"; } // in place of hle_nextendo_apple.m's weak one: a sign-in's access token +// Each account route gets the token nextendo.network takes there (hle_nextendo_apple.m): the nx2 game token for online-status, the access +// token for the rest +static void bearer_tests(void) { + NSMutableDictionary *record = valid_record(); set_record(record); NSString *game = record[@"token"]; + CHECK([dm_nextendo_api_bearer("me") isEqual:@"synthetic-access"] && [dm_nextendo_api_bearer("friends") isEqual:@"synthetic-access"] && [dm_nextendo_api_bearer("presence") isEqual:@"synthetic-access"] + && [dm_nextendo_api_bearer("online-status") isEqual:game], + "me, friends and presence get the access token; online-status the nx2 game token"); +} +int main(void) { @autoreleasepool { + // No configured provider is a normal unavailable result, not an OS storage + // read or a spawned helper. Offline never invokes even an installed provider. + uint8_t absent=7; dm_nextendo_set_credential_provider(NULL); + CHECK(!dm_nextendo_account_available(&absent) && !absent && dm_nextendo_account_ensure()!=0 && !atomic_load(&providerCalls), "unconfigured backend never queries an implicit credential source"); + dm_nextendo_set_credential_provider(provider); unsetenv("DM_NEXTENDO_ROUTES"); mode=DM_NET_AUTO; + CHECK(!dm_nextendo_account_available(&absent) && !absent && !atomic_load(&providerCalls), "automatic local mode without a profile never invokes the credential provider"); + setenv("DM_NEXTENDO_ROUTES","/synthetic/public-policy.tsv",1); mode=DM_NET_NEXTENDO; + dm_nextendo_set_game_version("3.0.5"); identity_tests(); login_tests(); login_http_tests(); token_tests(); async_tests(); bearer_tests(); + CHECK(atomic_load(&entered) > 0 && atomic_load(&entered) == atomic_load(&left) && atomic_load(&waits) > 0, "blocking account hooks publish balanced guest contexts and mark host security waits"); + printf("Nextendo account: %d checks, %d failures; synthetic provider only, no user credentials read\n", checks, failures); return failures ? 1 : 0; +} } diff --git a/dm/host/tests/t_nextendo_api.m b/dm/host/tests/t_nextendo_api.m new file mode 100644 index 0000000000..3c9b7cbb20 --- /dev/null +++ b/dm/host/tests/t_nextendo_api.m @@ -0,0 +1,94 @@ +// Canonical API behavior with a synthetic proof and mock transport only. +#import "../nextendo_api_apple.h" +#include "../nextendo_account.h" +#include +#include +static int checks, failures, requests; +static BOOL linked = YES; +static unsigned response_status = 200; +static bool oversized, transport_failed; +static const char *me_reply; +// Exercise the production streaming delegate directly; no URL connection starts. +@interface DmNextendoApiTransfer : NSObject +@property(nonatomic) NSMutableData *data; +@property(nonatomic) BOOL failed; +@property(nonatomic) NSInteger status; +@property(nonatomic) dispatch_semaphore_t completed; +@property(nonatomic) NSUInteger limit; +@end +#define CHECK(x) do { checks++; if (!(x)) { failures++; fprintf(stderr,"API check failed at %d\n",__LINE__); } } while (0) +NSString *dm_nextendo_api_bearer(const char *resource) { (void)resource; return linked ? @"synthetic-proof" : nil; } +NSData *dm_nextendo_api_identity(void) { return nil; } +void dm_guest_host_wait_begin(void) {} +void dm_guest_host_wait_end(void) {} +static bool transport(const char *url,const char *method,const char *authorization,const uint8_t *body,size_t body_size, + uint8_t *output,size_t capacity,size_t *size,unsigned *status) { + requests++; CHECK(!strcmp(authorization,"Bearer synthetic-proof")); + CHECK(!strcmp(url,"https://nextendo.network/api/friends") || !strcmp(url,"https://nextendo.network/api/me") || !strcmp(url,"https://nextendo.network/api/presence") || + !strcmp(url,"https://nextendo.network/api/profile")); + if (strstr(url,"presence")) { CHECK(!strcmp(method,"POST") && body && body_size); } + else { CHECK(!strcmp(method,"GET") && !body_size); } + const char *json=me_reply && strstr(url,"/api/me")?me_reply:"{\"friends\":[]}"; size_t length=strlen(json); CHECK(capacity > length); + memcpy(output,json,length); *size=oversized?capacity+1:length; *status=response_status; + return !transport_failed; +} +int main(void) { @autoreleasepool { + dm_nextendo_api_test_transport(transport); uint8_t output[256]; size_t size=99; + CHECK(!dm_nextendo_api_request("friends",NULL,0,output,sizeof output,&size) && size==14); + CHECK(!dm_nextendo_api_request("me",NULL,0,output,sizeof output,&size)); + CHECK(!dm_nextendo_api_request("presence",(const uint8_t*)"{}",2,output,sizeof output,&size)); + CHECK(!dm_nextendo_api_request("profile",NULL,0,output,sizeof output,&size)); + int asked=requests; // play history is no resource any more (Nextendo refuses its writes to third-party apps): refused before any request + CHECK(dm_nextendo_api_request("history",NULL,0,output,sizeof output,&size)!=0 && dm_nextendo_api_request("history",(const uint8_t*)"{}",2,output,sizeof output,&size)!=0 && requests==asked); + response_status=500; CHECK(dm_nextendo_api_request("friends",NULL,0,output,sizeof output,&size)!=0); response_status=200; + char country[3]="ZZ"; + me_reply="{\"account\":{\"country\":\"fr \"},\"nsa\":\"abcdef0000001234\"}"; CHECK(!dm_nextendo_account_country(country) && !strcmp(country,"FR")); + me_reply="{\"account\":{\"country\":\"France\"}}"; CHECK(!dm_nextendo_account_country(country) && !country[0]); + me_reply="{\"account\":{}}"; CHECK(!dm_nextendo_account_country(country) && !country[0]); + char birthday[11]="x"; + me_reply="{\"account\":{\"birthday\":\"1990-05-12\"}}"; CHECK(!dm_nextendo_account_birthday(birthday) && !strcmp(birthday,"1990-05-12")); + me_reply="{\"birth_date\":\"1991-02-03T00:00:00Z\"}"; CHECK(!dm_nextendo_account_birthday(birthday) && !strcmp(birthday,"1991-02-03")); + me_reply="{\"account\":{\"birthday\":\"12/05/1990\"}}"; CHECK(!dm_nextendo_account_birthday(birthday) && !birthday[0]); + me_reply="{\"account\":{}}"; CHECK(!dm_nextendo_account_birthday(birthday) && !birthday[0]); + me_reply=NULL; + for (unsigned status=300;status<=500;status+=100) { response_status=status; CHECK(dm_nextendo_api_request("friends",NULL,0,output,sizeof output,&size)!=0 && !size); } + response_status=200; oversized=true; CHECK(dm_nextendo_api_request("friends",NULL,0,output,sizeof output,&size)!=0 && !size); oversized=false; + transport_failed=true; CHECK(dm_nextendo_api_request("friends",NULL,0,output,sizeof output,&size)!=0 && !size); transport_failed=false; + int before=requests; + CHECK(dm_nextendo_api_request("https://untrusted.invalid",NULL,0,output,sizeof output,&size)!=0); + CHECK(dm_nextendo_api_request("../friends",NULL,0,output,sizeof output,&size)!=0); + CHECK(dm_nextendo_api_request("friends",(const uint8_t*)"{}",2,output,sizeof output,&size)!=0); + CHECK(dm_nextendo_api_request("presence",NULL,0,output,sizeof output,&size)!=0); + CHECK(dm_nextendo_api_request("profile",(const uint8_t*)"{}",2,output,sizeof output,&size)!=0); + CHECK(dm_nextendo_api_request("friends",NULL,0,NULL,0,&size)!=0 && dm_nextendo_api_request("friends",NULL,0,output,0,&size)!=0); + linked=NO; CHECK(dm_nextendo_api_request("friends",NULL,0,output,sizeof output,&size)!=0); + CHECK(before==requests && !size); + NSURLSession *dummy=[NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.ephemeralSessionConfiguration]; + NSURL *fixtureURL=[NSURL URLWithString:@"https://nextendo.network/api/friends"]; if (!fixtureURL) return 1; + NSURLSessionDataTask *dummy_task=[dummy dataTaskWithURL:fixtureURL]; // never resumed + DmNextendoApiTransfer *transfer=[DmNextendoApiTransfer new]; transfer.limit=1024*1024; + NSHTTPURLResponse *response=[[NSHTTPURLResponse alloc] initWithURL:fixtureURL statusCode:200 HTTPVersion:@"HTTP/1.1" headerFields:@{@"Content-Length":@"1048577"}]; + if (!response || !dummy_task || !transfer) return 1; + __block BOOL cancelled=NO; + [transfer URLSession:dummy dataTask:dummy_task didReceiveResponse:response completionHandler:^(NSURLSessionResponseDisposition disposition){cancelled=disposition==NSURLSessionResponseCancel;}]; + CHECK(cancelled&&transfer.failed&&!transfer.data.length); + transfer=[DmNextendoApiTransfer new]; transfer.limit=1024*1024; + NSData *largeChunk=[NSMutableData dataWithLength:1024*1024], *extraChunk=[NSData dataWithBytes:"X" length:1]; + if (!largeChunk || !extraChunk) return 1; + [transfer URLSession:dummy dataTask:dummy_task didReceiveData:largeChunk]; + CHECK(!transfer.failed&&transfer.data.length==1024*1024); + [transfer URLSession:dummy dataTask:dummy_task didReceiveData:extraChunk]; + CHECK(transfer.failed&&transfer.data.length==1024*1024); + transfer=[DmNextendoApiTransfer new]; // no limit: only the status is kept, any answer is dropped + [transfer URLSession:dummy dataTask:dummy_task didReceiveData:largeChunk]; [transfer URLSession:dummy dataTask:dummy_task didReceiveData:extraChunk]; + CHECK(!transfer.failed&&!transfer.data.length); + transfer=[DmNextendoApiTransfer new];__block BOOL redirect_refused=NO; + NSURL *redirectURL=[NSURL URLWithString:@"https://untrusted.invalid/"]; if (!redirectURL) return 1; + NSURLRequest *redirectRequest=[NSURLRequest requestWithURL:redirectURL]; if (!redirectRequest) return 1; + [transfer URLSession:dummy task:dummy_task willPerformHTTPRedirection:response newRequest:redirectRequest completionHandler:^(NSURLRequest *request){redirect_refused=request==nil;}]; + CHECK(redirect_refused&&transfer.failed); + [transfer URLSession:dummy task:dummy_task didCompleteWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:nil]]; + CHECK(transfer.failed&&dispatch_semaphore_wait(transfer.completed,DISPATCH_TIME_NOW)==0); + [dummy invalidateAndCancel]; + printf("Nextendo API: %d checks, %d failed; synthetic transport only\n",checks,failures); return failures?1:0; +} } diff --git a/dm/host/tests/t_nextendo_off.c b/dm/host/tests/t_nextendo_off.c new file mode 100644 index 0000000000..46e7c4e91a --- /dev/null +++ b/dm/host/tests/t_nextendo_off.c @@ -0,0 +1,44 @@ +// The Nextendo provider as it is offline, for the host unit tests that compile a service file without the network code (t_friends, t_account, t_account_save): +// DM_NETWORK is offline, so no Nextendo call is reached, and each fails if one is. Weak, so a test's own definition wins. +#include "../hle.h" +#include "../net_socket.h" +#include "../nextendo_account.h" +#include "../nextendo_social.h" +#include "../friends_history.h" +__attribute__((weak)) dm_net_mode_t dm_net_mode(void) { return DM_NET_OFFLINE; } +__attribute__((weak)) uint64_t hle_system_event_binding(void *g) { (void)g; return 0; } +__attribute__((weak)) void *guest_sym(const char *name) { (void)name; return NULL; } +__attribute__((weak)) void dm_hle_wait_enter(void) { abort(); } // the HLE_FORCE_WAIT gate's entry (entry.S); no wait hook is called here +__attribute__((weak)) uint32_t dm_friends_history_key(void *out, const void *uid, unsigned flag) { (void)out; (void)uid; (void)flag; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_async_attach(void *o, uint64_t l, uint64_t e) { (void)o; (void)l; (void)e; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_async_cancel(void *o) { (void)o; return RES_FAIL; } +__attribute__((weak)) void dm_nextendo_async_construct(void *o) { (void)o; } +__attribute__((weak)) void dm_nextendo_async_destroy(void *o) { (void)o; } +__attribute__((weak)) uint32_t dm_nextendo_async_done(void *o, uint8_t *out) { (void)o; (void)out; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_async_execute(void *o, dm_nextendo_async_operation op, const void *c) { (void)o; (void)op; (void)c; return RES_FAIL; } +__attribute__((weak)) uint64_t dm_nextendo_async_lifetime(void *o) { (void)o; return 0; } +__attribute__((weak)) void *dm_nextendo_async_move(void *o, void *s) { (void)s; return o; } +__attribute__((weak)) uint32_t dm_nextendo_async_result(void *o) { (void)o; return RES_FAIL; } +__attribute__((weak)) void dm_nextendo_async_swap(void *o, void *s) { (void)o; (void)s; } +__attribute__((weak)) bool dm_nextendo_async_valid(void *o) { (void)o; return false; } +__attribute__((weak)) uint32_t dm_nextendo_friends_available(uint8_t *a, const void *u) { (void)a; (void)u; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_friends_list(int *n, void *o, const void *u, int off, int cap, const void *f, bool ids) { if (n) *n = 0; (void)o; (void)u; (void)off; (void)cap; (void)f; (void)ids; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_friends_update(void *o, const void *u, const uint64_t *ids, int n) { (void)o; (void)u; (void)ids; (void)n; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_friends_ensure(const void *u) { (void)u; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_presence_commit(const void *o) { (void)o; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_presence_describe(void *o, const char *d) { (void)o; (void)d; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_presence_initialize(void *o, const void *u) { (void)o; (void)u; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_social_publish(unsigned st, const uint8_t *f, size_t n) { (void)st; (void)f; (void)n; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_account_available(uint8_t *out) { if (!out) return RES_FAIL; *out = 0; return RES_OK; } // as hle_nextendo_apple.m answers offline +__attribute__((weak)) uint32_t dm_nextendo_account_birthday(char output[11]) { (void)output; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_account_country(char output[3]) { (void)output; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_account_ensure(void) { return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_account_id(uint64_t *out) { (void)out; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_account_load_token(uint64_t *size, char *buffer, uint64_t capacity) { (void)size; (void)buffer; (void)capacity; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_account_username(char output[33]) { (void)output; return RES_FAIL; } +__attribute__((weak)) uint32_t dm_nextendo_async_ensure(void *o) { (void)o; return RES_FAIL; } +__attribute__((weak)) void dm_guest_host_wait_begin(void) {} +__attribute__((weak)) void dm_guest_host_wait_end(void) {} +__attribute__((weak)) void hle_bind_system_event(void *g, int autoclear) { (void)g; (void)autoclear; } +__attribute__((weak)) void hle_signal_system_event(void *g) { (void)g; } +__attribute__((weak)) int dm_account_uid_exists(const void *uid) { (void)uid; return 0; } diff --git a/dm/host/tests/t_nextendo_routes.c b/dm/host/tests/t_nextendo_routes.c new file mode 100644 index 0000000000..b79bbeb7e0 --- /dev/null +++ b/dm/host/tests/t_nextendo_routes.c @@ -0,0 +1,132 @@ +// Production DNS policy and TLS transport with ephemeral public test certificates. +#include "../nextendo_routes.h" +#include "../net_socket.h" +#include "../ssl_backend.h" +#include +#include +#include +#include +#include + +static int checks, failures; +static _Atomic unsigned waits; +#define CHECK(test, message) do { checks++; if (!(test)) { failures++; fprintf(stderr, "FAIL line %d: %s\n", __LINE__, message); } } while (0) +void dm_guest_host_wait_begin(void) { atomic_fetch_add(&waits, 1); } +void dm_guest_host_wait_end(void) {} +typedef struct { uint8_t length, family; uint16_t port; uint32_t address; uint8_t padding[8]; } Address; +static void resolve_checks(int ready) { + dm_net_addrinfo hint = {.family = 2, .type = 1, .protocol = 6, .flags = 2}; void *output = (void *)1; + CHECK(dm_net_getaddrinfo("never-configured.nintendo.net", "443", &hint, &output) == 8 && output == NULL, "unconfigured Nintendo hostname is refused before native DNS"); + CHECK(dm_net_getaddrinfo("unconfigured.example.invalid", "443", &hint, &output) == 8 && output == NULL, "unconfigured third-party hostname is refused too"); + CHECK(dm_net_getaddrinfo("127.0.0.1", "1234", &hint, &output) == 0 && output, "numeric peer resolution survives missing/invalid service configuration"); + if (output) dm_net_freeaddrinfo(output); + if (!ready) { CHECK(dm_net_getaddrinfo("api.console.invalid", "443", &hint, &output) == 8 && !output, "failed configuration publishes no partial route"); return; } + CHECK(dm_net_getaddrinfo("API.CONSOLE.INVALID.", "443", &hint, &output) == 0 && output, "exact host matching normalizes DNS case and one final dot"); + if (output) { dm_net_addrinfo *info = output; Address address; memcpy(&address, info->addr, sizeof address); + CHECK(info->family == 2 && info->type == 1 && address.address == htonl(0x7f000001) && address.port == htons(443) && !strcmp(info->canonname, "API.CONSOLE.INVALID."), "native resolver preserves guest canonical name and translates configured address"); dm_net_freeaddrinfo(output); } + CHECK(dm_net_getaddrinfo_legacy("api.console.invalid", "443", &hint, &output) == 0 && output, "SDK4 routing shares the same resolver policy"); + if (output) { dm_net_addrinfo_legacy *info = output; CHECK(info->addr && info->canonname && !strcmp(info->canonname, "api.console.invalid"), "SDK4 pointer layout stays correct after canonical-name preservation"); dm_net_freeaddrinfo(output); } + hint.type = 2; hint.protocol = 17; + CHECK(dm_net_getaddrinfo("nncs2-%.n.n.srv.nintendo.net", "10025", &hint, &output) == 0 && output, + "default socket resolver expands a retail NAT template before scoped routing"); + if (output) { Address address; memcpy(&address, ((dm_net_addrinfo *)output)->addr, sizeof address); + CHECK(address.address == htonl(0x7f000001) && address.port == htons(10025), "NAT template retains its configured address and UDP port"); dm_net_freeaddrinfo(output); } + CHECK(dm_net_getaddrinfo_legacy("nncs2-%.n.n.srv.nintendo.net", "10125", &hint, &output) == 0 && output, + "legacy resolver applies the same default NSD expansion"); + if (output) dm_net_freeaddrinfo(output); + CHECK(dm_net_getaddrinfo("unconfigured-%.example.invalid", "10025", &hint, &output) == 8 && !output, + "NSD expansion cannot admit an unconfigured service"); + CHECK(dm_net_getaddrinfo("nncs2-%/.n.n.srv.nintendo.net", "10025", &hint, &output) == 8 && !output, + "malformed service templates fail before native DNS"); + hint.type = 1; hint.protocol = 6; + hint.flags = 4; CHECK(dm_net_getaddrinfo("api.console.invalid", "443", &hint, &output) == 8 && !output, "AI_NUMERICHOST does not turn a mapped DNS name into a numeric caller input"); + hint.flags = 1; CHECK(dm_net_getaddrinfo(NULL, "0", &hint, &output) == 0 && output, "passive null-host binding never requires a DNS service route"); if (output) dm_net_freeaddrinfo(output); +} +static void tls_checks(int ready, unsigned port, bool reject_peer) { + char context[32] = {0}, connection[32] = {0}; CHECK(dm_ssl_context_create(context, 32) == 0 && dm_ssl_connection_create(connection, context) == 0, "actual native TLS registry prepared"); + CHECK(dm_ssl_set_hostname(connection, "never-configured.nintendo.net", 29) != 0, "unknown SNI cannot bypass fail-closed DNS through a literal socket"); + CHECK(dm_ssl_set_hostname(connection, "127.0.0.9", 9) != 0, "an unconfigured numeric address does not authorize TLS SNI"); + CHECK(dm_ssl_set_hostname(connection, "nncs2-lp1.n.n.srv.nintendo.net", (unsigned)strlen("nncs2-lp1.n.n.srv.nintendo.net")) != 0, "plaintext NAT route does not silently become a TLS route"); + if (!ready) { CHECK(dm_ssl_set_hostname(connection, "api.console.invalid", 19) != 0, "missing/invalid configuration cannot admit service TLS"); dm_ssl_connection_destroy(connection); dm_ssl_context_destroy(context); return; } + CHECK(dm_ssl_set_hostname(connection, "api.console.invalid", 19) == 0, "exact TLS route admits its configured verification hostname"); + if (port) { + dm_net_addrinfo hint = {.family=2,.type=1,.protocol=6}; void *answer = NULL; char service[16]; snprintf(service, sizeof service, "%u", port); + CHECK(dm_net_getaddrinfo("api.console.invalid", service, &hint, &answer) == 0 && answer, "actual TLS socket obtains the routed resolver address"); + int fd = dm_net_socket(2, 1, 6); dm_net_addrinfo *info = answer; + CHECK(info && fd >= 0 && dm_net_connect(fd, info->addr, info->addrlen) == 0 && dm_ssl_set_socket(connection, fd) == 0, "guest TCP descriptor is connected and borrowed safely"); if (answer) dm_net_freeaddrinfo(answer); + if (reject_peer) { + CHECK(dm_ssl_handshake(connection) != 0, "a different CA or enrolled certificate rejects the actual TLS peer"); + int sent = 99; uint32_t verification = 0; + CHECK(dm_ssl_last_error(connection, &verification, true) == 0 && verification && + dm_ssl_write(connection, "PING", &sent, 4) != 0 && sent == 0, + "failed verification retains its error and sends no application data"); + dm_ssl_connection_destroy(connection); dm_ssl_context_destroy(context); return; + } + CHECK(dm_ssl_handshake(connection) == 0, "mapped SNI and only its scoped DER CA complete a real TLS handshake"); + char bytes[8] = {0}; int n = 0; CHECK(dm_ssl_read(connection, bytes, &n, 5, false) == 0 && n == 5 && !memcmp(bytes, "HELLO", 5), "routed TLS receives actual server plaintext"); + CHECK(dm_ssl_write(connection, "PING", &n, 4) == 0 && n == 4 && dm_ssl_read(connection, bytes, &n, 4, false) == 0 && n == 4 && !memcmp(bytes, "PONG", 4), "routed TLS carries actual bidirectional guest data"); + } + dm_ssl_connection_destroy(connection); dm_ssl_context_destroy(context); + if (port) { + CHECK(dm_ssl_context_create(context, 32) == 0 && dm_ssl_connection_create(connection, context) == 0 && dm_ssl_set_hostname(connection, "wrong.console.invalid", 21) == 0, "negative mapped-host test uses a valid exact policy record"); + int fd = dm_net_socket(2,1,6); Address address = {16,2,htons((uint16_t)port),htonl(0x7f000001),{0}}; + CHECK(fd >= 0 && dm_net_connect(fd,&address,sizeof address) == 0 && dm_ssl_set_socket(connection,fd) == 0 && dm_ssl_handshake(connection) != 0, "a scoped trusted CA never bypasses mapped hostname validation"); + dm_ssl_connection_destroy(connection); dm_ssl_context_destroy(context); + } +} +static void handoff_checks(unsigned port) { + char context[32] = {0}, connection[32] = {0}; + CHECK(dm_ssl_context_create(context, 32) == 0 && dm_ssl_connection_create(connection, context) == 0, + "numeric handoff uses an actual independent TLS connection"); + CHECK(dm_ssl_set_hostname(connection, "127.0.0.1", 9) == 0, + "an explicitly paired numeric alias retains its enrolled service identity"); + int fd = dm_net_socket(2, 1, 6); Address address = {16, 2, htons((uint16_t)port), htonl(0x7f000001), {0}}; + CHECK(fd >= 0 && dm_net_connect(fd, &address, sizeof address) == 0 && dm_ssl_set_socket(connection, fd) == 0 && dm_ssl_handshake(connection) == 0, + "numeric handoff verifies the exact enrolled certificate with canonical service SNI"); + char bytes[8] = {0}; int size = 0; + CHECK(dm_ssl_read(connection, bytes, &size, 5, false) == 0 && size == 5 && !memcmp(bytes, "HELLO", 5) && + dm_ssl_write(connection, "PING", &size, 4) == 0 && size == 4 && + dm_ssl_read(connection, bytes, &size, 4, false) == 0 && size == 4 && !memcmp(bytes, "PONG", 4), + "the paired address carries real bidirectional encrypted traffic"); + dm_ssl_connection_destroy(connection); dm_ssl_context_destroy(context); +} +static void v2_checks(void) { + dm_net_addrinfo hint = {.family=2,.type=1,.protocol=6}; void *out = NULL; + const char *names[] = {"deep.scope.invalid", "scope.invalid", "nat2.scope.invalid", "nat3.scope.invalid", "special.scope.invalid"}; + const uint32_t ips[] = {0x7f000002,0x7f000002,0x7f000003,0x7f000003,0x7f000004}; + for (unsigned i = 0; i < sizeof names / sizeof names[0]; i++) { + CHECK(dm_net_getaddrinfo(names[i], "443", &hint, &out) == 0 && out, "V2 exact, suffix and label routes resolve"); + if (out) { Address address; memcpy(&address, ((dm_net_addrinfo *)out)->addr, sizeof address); + CHECK(address.address == htonl(ips[i]), "V2 precedence is exact before label before longest suffix"); dm_net_freeaddrinfo(out); } + } + CHECK(dm_net_getaddrinfo("evilscope.invalid", "443", &hint, &out) == 8 && !out, "suffix matching respects a DNS label boundary"); + CHECK(dm_nextendo_routes_retry_unconfigured() == 0 && dm_nextendo_routes_status() == 0, "explicit setup retry cannot replace a published policy"); +} +int main(int argc, char **argv) { + if (argc < 3 || argc > 5) return 2; setenv("DM_NETWORK", "nextendo", 1); if (strcmp(argv[1], "-")) setenv("DM_NEXTENDO_ROUTES", argv[1], 1); else unsetenv("DM_NEXTENDO_ROUTES"); + int expected = atoi(argv[2]), status = dm_nextendo_routes_initialize(); CHECK(status == expected && dm_nextendo_routes_status() == expected, "configuration reports its precise safe status"); + if (argc == 4 && argv[3][0] == '/') { + setenv("DM_NEXTENDO_ROUTES", argv[3], 1); + CHECK(dm_nextendo_routes_initialize() == expected, "a failed policy remains immutable without explicit setup"); + CHECK(dm_nextendo_routes_retry_unconfigured() == expected, "explicit setup reports the previous failed state"); + CHECK(dm_nextendo_routes_initialize() == 0 && dm_nextendo_routes_count() > 0, "explicit setup recovers after a complete profile is supplied"); + printf("Nextendo routes: %d checks, %d failures (recovery)\n",checks,failures); return failures ? 1 : 0; + } + CHECK((status == 0) == (dm_nextendo_routes_count() > 0), "only a fully validated table is published"); + setenv("DM_NEXTENDO_ROUTES", "/unconfigured/should-not-reload.tsv", 1); CHECK(dm_nextendo_routes_initialize() == expected, "routing configuration is immutable until the next process launch"); + CHECK(dm_bcat_online_enabled() == (status == 0), "BCAT capability requires an opted-in, fully published profile"); + resolve_checks(status == 0); + setenv("DM_NETWORK", "auto", 1); resolve_checks(status == 0); + tls_checks(status == 0, argc >= 4 ? (unsigned)strtoul(argv[3],NULL,10) : 0, argc == 5 && !strcmp(argv[4], "reject-peer")); + if (argc == 5 && !strcmp(argv[4], "v2")) v2_checks(); + if (argc == 5 && !strcmp(argv[4], "handoff")) handoff_checks((unsigned)strtoul(argv[3], NULL, 10)); + unsetenv("DM_NEXTENDO_ROUTES"); setenv("DM_NETWORK", "auto", 1); + dm_net_addrinfo local_hint = {.family=2,.type=1}; void *local_answer = NULL; + CHECK(!dm_net_nextendo_enabled() && !dm_bcat_online_enabled() && !dm_net_getaddrinfo("localhost","0",&local_hint,&local_answer) && local_answer, + "unconfigured AUTO retains ordinary local DNS and does not enable online services"); + if (local_answer) dm_net_freeaddrinfo(local_answer); + setenv("DM_NEXTENDO_ROUTES", "invalid-relative-profile", 1); + CHECK(dm_net_nextendo_enabled(), "an explicitly supplied invalid profile does not silently fall back to unrestricted AUTO"); + setenv("DM_NETWORK", "lan", 1); CHECK(!dm_bcat_online_enabled(), "BCAT capability stays off in local mode without any account read"); dm_net_addrinfo hint = {.family=2,.type=1}; void *answer = NULL; CHECK(dm_net_getaddrinfo("localhost", "0", &hint, &answer) == 0, "LAN resolver behavior remains independent of Nextendo policy"); if (answer) dm_net_freeaddrinfo(answer); + printf("Nextendo routes: %d checks, %d failures (status %d)\n", checks, failures, status); return failures ? 1 : 0; +} diff --git a/dm/host/tests/t_nextendo_social.m b/dm/host/tests/t_nextendo_social.m new file mode 100644 index 0000000000..dc0c24f40b --- /dev/null +++ b/dm/host/tests/t_nextendo_social.m @@ -0,0 +1,111 @@ +// Actual HTTP/schema/cache and SDK adapters with synthetic users/instructions. +#import +#include "../nextendo_api_apple.h" +#include "../nextendo_social.h" +#include "../net_socket.h" +#include +#include +#include +#include +static int checks,failures,requests; static unsigned generation=1,response_status=200; +static BOOL linked=YES; static NSString *reply,*posted_detail; +static dm_net_mode_t mode=DM_NET_AUTO; +static uint8_t uid[16]={1}; +static uint32_t constructor[]={0x52804002,0x2a1f03e1,0x14000000}; +static uint32_t presence_constructor[]={0x52801c02,0x2a1f03e1,0x14000000}; +static uint32_t nick[]={0x91006000,0xd65f03c0},presence[]={0x91010000,0xd65f03c0},account[]={0xf9400800,0xd65f03c0},valid[]={0x3944a000,0xd65f03c0},favorite[]={0x39448000,0xd65f03c0}; +#define CHECK(x) do{checks++;if(!(x)){failures++;fprintf(stderr,"social check failed line %d\n",__LINE__);}}while(0) +NSString *dm_nextendo_api_bearer(const char *resource){(void)resource;return linked?@"synthetic-social-proof":nil;} +NSData *dm_nextendo_api_identity(void){return linked?[NSData dataWithBytes:&generation length:sizeof generation]:nil;} +void dm_guest_host_wait_begin(void){} void dm_guest_host_wait_end(void){} +dm_net_mode_t dm_net_mode(void){return mode;} +int dm_account_uid_exists(const void *value){return value&&!memcmp(value,uid,16);} +int dm_account_copy_uid(void *value){if(!value)return 0;memcpy(value,uid,16);return 1;} +uint32_t dm_nextendo_account_ensure(void){return linked?0:0x2a2;} +void *guest_sym(const char *name){ + if(strstr(name,"UserPresenceC1"))return presence_constructor; + if(strstr(name,"FriendC1"))return constructor; + if(strstr(name,"GetNickname"))return nick; + if(strstr(name,"GetPresence"))return presence; + if(strstr(name,"GetAccountId"))return account; + if(strstr(name,"IsValid"))return valid; + if(strstr(name,"IsFavorite"))return favorite; + return NULL; +} +static bool transport(const char *url,const char *method,const char *auth,const uint8_t *body,size_t body_size,uint8_t *output,size_t capacity,size_t *size,unsigned *status){ + requests++;CHECK(!strcmp(auth,"Bearer synthetic-social-proof")); + if(strstr(url,"/api/presence")){ + CHECK(!strcmp(method,"POST")&&body&&body_size); + NSDictionary *posted=[NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:body length:body_size] options:0 error:nil]; + CHECK([posted[@"app_id"] isEqual:@"0100152000022000"]&&[posted[@"status"] unsignedIntValue]<=2); + posted_detail=posted[@"app_detail"]; + memcpy(output,"{}",2);*size=2;*status=response_status;return true; + } + CHECK(!strcmp(method,"GET")); + NSData *data=[(strstr(url,"/api/me")?@"{\"nsa\":\"abcdef0000001234\"}":reply) dataUsingEncoding:NSUTF8StringEncoding]; + if(data.length>capacity)return false;memcpy(output,data.bytes,data.length);*size=data.length;*status=response_status;return true; +} +int main(void){@autoreleasepool{ + setenv("DM_NEXTENDO_ROUTES","/synthetic/public-policy.tsv",1); + reply=@"{\"friends\":[{\"pid\":501,\"nsa\":\"abcdef0000000501\",\"name\":\"Alpha\",\"favorite\":true,\"presence\":{\"status\":2,\"app_id\":\"0100152000022000\",\"app_field\":\"AQID\"}},{\"pid\":502,\"name\":\"Beta\",\"presence\":{\"status\":1,\"app_id\":\"0100000000001000\"}},{\"pid\":503,\"name\":\"Gamma\",\"presence\":null}]}"; + dm_nextendo_api_test_transport(transport); + uint8_t available=9; + CHECK(!dm_nextendo_friends_available(&available,uid)&&available); + mode=DM_NET_LAN;available=9;CHECK(!dm_nextendo_friends_available(&available,uid)&&!available);mode=DM_NET_AUTO; + linked=NO;available=9;CHECK(dm_nextendo_friends_available(&available,uid)!=0&&!available);linked=YES; + uint8_t unavailable_uid[16]={9};CHECK(dm_nextendo_friends_ensure(unavailable_uid)!=0); + uint8_t filter[16]={0},objects[0x600+16];memset(objects,0xa5,sizeof objects);int count=-1; + CHECK(!dm_nextendo_friends_list(&count,objects,uid,0,3,filter,false)&&count==3); + uint64_t id=0;memcpy(&id,objects+0x10,8);CHECK(id==501&&!strcmp((char*)objects+0x18,"Alpha")); + CHECK(objects[0x58]==2&&objects[0x5c]==1&&objects[0x60]==1&&objects[0x61]==2&&objects[0x62]==3&&objects[0x120]==1&&objects[0x128]==1); + CHECK(!memcmp(objects,uid,16)&&objects[0x600]==0xa5); + int before=requests;uint64_t ids[4]={0,0,0,0xface}; + CHECK(!dm_nextendo_friends_list(&count,ids,NULL,1,1,filter,true)&&count==1&&ids[0]==502&&ids[1]==0&&ids[3]==0xface&&requests==before); + char profile[]="/tmp/nx-social-profile-XXXXXX";CHECK(mkdtemp(profile)!=NULL); + NSString *profilePath=[NSString stringWithUTF8String:profile]; if (!profilePath) return 1; + NSString *manifest=[profilePath stringByAppendingPathComponent:@"manifest.json"]; + CHECK([@"{\"identity\":{\"friends\":\"baas\",\"account\":\"baas\"}}" writeToFile:manifest atomically:YES encoding:NSUTF8StringEncoding error:nil]); + chmod(manifest.fileSystemRepresentation,0600); + NSString *routes=[[NSString stringWithUTF8String:profile] stringByAppendingPathComponent:@"routes.tsv"]; + setenv("DM_NEXTENDO_ROUTES",routes.fileSystemRepresentation,1); + CHECK(dm_nextendo_api_baas_namespace("friends")&&dm_nextendo_api_baas_namespace("account")); + CHECK(!dm_nextendo_friends_list(&count,ids,uid,0,1,filter,true)&&count==1&&ids[0]==0xabcdef0000000501ull); + chmod(manifest.fileSystemRepresentation,0666);CHECK(!dm_nextendo_api_baas_namespace("friends")); + unlink(manifest.fileSystemRepresentation);rmdir(profile);unsetenv("DM_NEXTENDO_ROUTES"); + available=9;before=requests;CHECK(!dm_nextendo_friends_available(&available,uid)&&!available&&requests==before); + setenv("DM_NEXTENDO_ROUTES","/synthetic/public-policy.tsv",1); + filter[4]=1;CHECK(!dm_nextendo_friends_list(&count,ids,uid,0,3,filter,true)&&count==1&&ids[0]==501);filter[4]=0; + filter[0]=3;CHECK(!dm_nextendo_friends_list(&count,ids,uid,0,3,filter,true)&&count==2);filter[0]=0; + filter[5]=1;CHECK(!dm_nextendo_friends_list(&count,ids,uid,0,3,filter,true)&&count==1);filter[5]=0; + uint64_t selected_ids[]={502,501};before=requests; + CHECK(!dm_nextendo_friends_update(objects,uid,selected_ids,2)&&requests==before+1&&!strcmp((char*)objects+0x18,"Beta")&&!strcmp((char*)objects+0x218,"Alpha")); + uint64_t absent=999;memset(objects,0xa5,sizeof objects);CHECK(dm_nextendo_friends_update(objects,uid,&absent,1)!=0&&objects[0]==0xa5); + filter[6]=1;CHECK(dm_nextendo_friends_list(&count,ids,uid,0,3,filter,true)!=0&&!count);filter[6]=0; + valid[0]=0;CHECK(dm_nextendo_friends_list(&count,objects,uid,0,1,filter,false)!=0&&!count);valid[0]=0x3944a000; + uint8_t bad_uid[16]={2};CHECK(dm_nextendo_friends_list(&count,ids,bad_uid,0,3,filter,true)!=0&&!count); + mode=DM_NET_LAN;CHECK(dm_nextendo_friends_list(&count,ids,uid,0,3,filter,true)!=0&&!count);mode=DM_NET_AUTO; + linked=NO;CHECK(dm_nextendo_friends_list(&count,ids,uid,0,3,filter,true)!=0&&!count);linked=YES; + generation++;response_status=503;CHECK(dm_nextendo_friends_list(&count,ids,uid,0,3,filter,true)!=0&&!count);response_status=200; + generation++;response_status=503;available=9;CHECK(dm_nextendo_friends_available(&available,uid)!=0&&!available);response_status=200; + for(NSString *bad in @[@"{}",@"{\"friends\":null}",@"{\"friends\":[{\"pid\":true,\"name\":\"wrong\"}]}",@"{\"friends\":[{\"pid\":501,\"name\":\"wrong\",\"presence\":{\"status\":99}}]}"]){ + generation++;reply=bad;CHECK(dm_nextendo_friends_list(&count,ids,uid,0,3,filter,true)!=0&&!count); + } + generation++;reply=@"{\"friends\":[]}";CHECK(!dm_nextendo_friends_list(&count,ids,uid,0,3,filter,true)&&!count); + uint64_t nsa=0;CHECK(!dm_nextendo_api_baas_id(&nsa)&&nsa==0xabcdef0000001234ull); + uint8_t own[0xe0+16];memset(own,0,sizeof own);own[0xe0]=0xa5; + CHECK(!dm_nextendo_presence_initialize(own,uid)&&!memcmp(own,uid,16)&&own[0xe0]==0xa5); + own[0x20]=1;own[0x21]=2;CHECK(!dm_nextendo_presence_commit(own));dm_nextendo_social_flush();CHECK([posted_detail isEqual:@""]); + // the game's description: key and value strings in turn, the description under sys_description + static const char described[]="mode\0race\0sys_description\0Grand Prix";memset(own+0x20,0,192);memcpy(own+0x20,described,sizeof described); + CHECK(!dm_nextendo_presence_commit(own));dm_nextendo_social_flush();CHECK([posted_detail isEqual:@"Grand Prix"]); + memset(own+0x20,'x',192);CHECK(!dm_nextendo_presence_commit(own));dm_nextendo_social_flush();CHECK([posted_detail isEqual:@""]); // a field that never ends its strings + memset(own+0x20,0,192); + // a refused upload is not the game's failure (a console's friends service uploads in the background), and the next publish is still sent + response_status=503;CHECK(!dm_nextendo_presence_commit(own));dm_nextendo_social_flush();response_status=200; + memcpy(own+0x20,described,sizeof described);posted_detail=nil;CHECK(!dm_nextendo_presence_commit(own));dm_nextendo_social_flush();CHECK([posted_detail isEqual:@"Grand Prix"]); + memset(own+0x20,0,192); + presence_constructor[0]=0;CHECK(dm_nextendo_presence_initialize(own,uid)!=0);presence_constructor[0]=0x52801c02; + mode=DM_NET_OFFLINE;CHECK(dm_nextendo_presence_commit(own)!=0);mode=DM_NET_AUTO; + linked=NO;CHECK(dm_nextendo_api_baas_id(&nsa)!=0&&!nsa);CHECK(dm_nextendo_presence_initialize(own,uid)!=0); + printf("Nextendo social: %d checks, %d failed; real parsers and SDK adapters, synthetic HTTP only\n",checks,failures);return failures?1:0; +}} diff --git a/dm/host/tests/t_nextendo_x509.c b/dm/host/tests/t_nextendo_x509.c new file mode 100644 index 0000000000..1bef669203 --- /dev/null +++ b/dm/host/tests/t_nextendo_x509.c @@ -0,0 +1,34 @@ +// Exercise the actual verifier with ephemeral DER fixtures, never account data. +#include "../nextendo_x509.h" +#include +#include +#include +#include +static unsigned char *read_file(const char *path, size_t *size) { + *size = 0; FILE *file = fopen(path, "rb"); if (!file) return NULL; + if (fseek(file, 0, SEEK_END)) { int error=errno; fclose(file); errno=error; return NULL; } + long length = ftell(file); int length_error=errno; + if (length < 1 || length > 65537) { fclose(file); errno=length_error; return NULL; } + if (fseek(file, 0, SEEK_SET)) { int error=errno; fclose(file); errno=error; return NULL; } + unsigned char *bytes = malloc((size_t)length); + if (!bytes) { int error=errno; fclose(file); errno=error; return NULL; } + size_t got=fread(bytes,1,(size_t)length,file); int read_error=errno; + int closed=fclose(file); + if (got!=(size_t)length || closed) { free(bytes); if (got!=(size_t)length) errno=read_error; return NULL; } + *size=(size_t)length; return bytes; +} +int main(int argc, char **argv) { + if (argc == 5 && !strcmp(argv[1], "--pin")) { + size_t pin_size, leaf_size; + unsigned char *pin = read_file(argv[3], &pin_size), *leaf = read_file(argv[4], &leaf_size); + bool valid = dm_nextendo_x509_verify_pin(argv[2], pin, pin_size, leaf, leaf_size); + free(pin); free(leaf); return valid ? 0 : 1; + } + if (argc < 4 || argc > 19 || !dm_nextendo_x509_available()) return 2; + size_t anchor_size = 0, sizes[16] = {0}, count = (size_t)argc - 3; + unsigned char *anchor = read_file(argv[2], &anchor_size); const unsigned char *chain[16] = {0}; + for (size_t i = 0; i < count; i++) chain[i] = read_file(argv[i + 3], &sizes[i]); + bool valid = dm_nextendo_x509_verify(argv[1], anchor, anchor_size, chain, sizes, count); + for (size_t i = 0; i < count; i++) free((void *)chain[i]); free(anchor); + return valid ? 0 : 1; +} diff --git a/dm/host/tests/t_nro.c b/dm/host/tests/t_nro.c index 2c114debd0..8cad92db1f 100644 --- a/dm/host/tests/t_nro.c +++ b/dm/host/tests/t_nro.c @@ -8,6 +8,8 @@ void dm_thread_service_connect(void) {} // threads started so far have nothing #include #include void mtl_present_screen(uint32_t w, uint32_t h) { (void)w; (void)h; } // loader.c: a screen taller than 16:9; no renderer here +dm_net_mode_t dm_net_mode(void) { return DM_NET_OFFLINE; } // loader.c: main from the --nextendo copy only online + // 40 fps (loader.c, compiled here): only a stub that takes ticks of 1/120 s (the FRAME_STEP_120 capability in its fixups table) gets it; the loader writes the step's unit (+0x38) // for it, 120, at every start, and 0 for every other stub. Elsewhere DM_FPS_TARGET=40 holds 30 static float page_target(const uint8_t *page) { float t; memcpy(&t, page, 4); return t; } diff --git a/dm/host/tests/t_nsd.c b/dm/host/tests/t_nsd.c new file mode 100644 index 0000000000..9549ebc110 --- /dev/null +++ b/dm/host/tests/t_nsd.c @@ -0,0 +1,36 @@ +// No game files, credentials or network calls. Exercise the actual NSD adapter. +#include "../nsd.h" +#include "../net_socket.h" +#include +#include +static dm_net_mode_t mode = DM_NET_NEXTENDO; +dm_net_mode_t dm_net_mode(void) { return mode; } +static int checks, failures; +#define CHECK(x) do { checks++; if (!(x)) { failures++; fprintf(stderr,"NSD failed at line %d\n",__LINE__); } } while (0) +int main(void) { + struct { char fqdn[256]; unsigned char guard[32]; } output; + memset(&output,0xa5,sizeof output); + CHECK(!dm_nsd_resolve(output.fqdn,"g23380901-%.s.n.srv.nintendo.net")); + CHECK(!strcmp(output.fqdn,"g23380901-lp1.s.n.srv.nintendo.net")); + CHECK(output.fqdn[255]==0 && output.guard[0]==0xa5 && output.guard[31]==0xa5); + CHECK(!dm_nsd_resolve(output.fqdn,"CTEST.CDN.NINTENDO.NET.") && !strcmp(output.fqdn,"ctest.cdn.nintendo.net")); + CHECK(!dm_nsd_resolve(output.fqdn,"accounts.nintendo.com") && !strcmp(output.fqdn,"e0d67c509fb203858ebcb2fe3f88c2aa.baas.nintendo.com")); + CHECK(!dm_nsd_resolve(output.fqdn,"api.accounts.nintendo.com") && !strcmp(output.fqdn,"e0d67c509fb203858ebcb2fe3f88c2aa.baas.nintendo.com")); + strcpy(output.fqdn,"nncs1-%.n.n.srv.nintendo.net"); + CHECK(!dm_nsd_resolve(output.fqdn,output.fqdn) && !strcmp(output.fqdn,"nncs1-lp1.n.n.srv.nintendo.net")); + CHECK(!dm_nsd_resolve(output.fqdn,"one.%.%.example") && !strcmp(output.fqdn,"one.lp1.lp1.example")); + const char *bad[]={"","a..b",".example","-bad.example","bad-.example","bad/name","http://example.com","white space","example:443","a..","invalid\x80.example"}; + for (unsigned i=0;i +#include + +void dm_audio_suspend(int on) { (void)on; } +void guest_clock_freeze_for(int reason, int on) { (void)reason; (void)on; } +void dm_gfx_suspend(int on) { (void)on; } +void dm_hid_opmode_changed(void) {} // hle_hid.c: the npads follow the console mode (hle_oe.c dm_set_opmode); not exercised here +void dm_gfx_quit_begin(void) {} // nvn_mtl.m: the pipeline archive starts writing as a program ends (hle_oe.c); no graphics here +void dm_host_shutdown_then(const char *why, void (*then)(void *), void *arg) { (void)why; (void)then; (void)arg; } +void dm_host_shutdown(const char *why) { (void)why; } + +static thr_t *worker; +static uint32_t event_read; +static _Atomic uint32_t received; +static void *notification_worker(void *arg) { + (void)arg; + pthread_setspecific(g_keythr, worker); + uint32_t handle = event_read; + uint64_t r[32] = {0, (uint64_t)&handle, 1, (uint64_t)-1}; + svc_thread(0x18, r); + assert(r[0] == 0); + atomic_store(&received, h_oe_PopMsg()); + pthread_mutex_lock(&G); + assert(worker->native_wait == 0 && worker->nhand == 0); + pthread_mutex_unlock(&G); + thread_exit(worker); + return NULL; +} + +int main(void) { + alarm(5); // The old implementation never returns from the parent's SignalEvent. + unsetenv("DM_OE_SCRIPT"); + setenv("DM_PREEMPT", "0", 1); + svc_thread_main_init(); + thr_t *parent = cur(); + parent->prio = 44; parent->core = 0; parent->mask = 1; + dm_guest_host_wait_begin(); dm_guest_host_wait_begin(); + assert(parent->native_wait == 2 && !thr_runnable(parent)); + dm_guest_host_wait_end(); assert(parent->native_wait == 1 && !thr_runnable(parent)); + dm_guest_host_wait_end(); assert(parent->native_wait == 0 && thr_runnable(parent)); + + uint64_t r[32] = {0}; + svc_thread(0x45, r); assert(r[0] == 0); + uint32_t event_write = r[1]; event_read = r[2]; + worker = calloc(1, sizeof *worker); assert(worker); + pthread_cond_init(&worker->cv, NULL); pthread_cond_init(&worker->pcv, NULL); + worker->started = 1; worker->prio = 41; worker->core = 0; worker->mask = 1; + pthread_mutex_lock(&G); + worker->handle = h_new(O_THREAD, worker); worker->all = g_all; g_all = worker; + pthread_mutex_unlock(&G); + pthread_t thread; assert(!pthread_create(&thread, NULL, notification_worker, NULL)); + for (;;) { + pthread_mutex_lock(&G); int waiting = worker->wkind == 4; pthread_mutex_unlock(&G); + if (waiting) break; + usleep(100); + } + r[0] = event_write; svc_thread(0x11, r); + pthread_mutex_lock(&G); + assert(worker->native_wait == 1 && worker->nhand == 0 && !thr_runnable(worker)); + pthread_mutex_unlock(&G); + assert(atomic_load(&received) == 0 && g_mqn == 0); + // No fabricated startup message and no timeout: only the real producer releases the pop. + mq_push(15); + pthread_join(thread, NULL); + assert(atomic_load(&received) == 15); + uint32_t msg = 999; + assert(!h_oe_TryPopMsg(&msg) && msg == 999); + r[0] = worker->handle; svc_thread(0x16, r); worker = NULL; + puts("PASS: native notification wait releases the same-core handoff; one real message delivered once; nested wait state balanced"); + return 0; +} diff --git a/dm/host/tests/t_online_policy.c b/dm/host/tests/t_online_policy.c new file mode 100644 index 0000000000..50d493f9a3 --- /dev/null +++ b/dm/host/tests/t_online_policy.c @@ -0,0 +1,27 @@ +// Actual resolver admission: automatic local networking remains independent of +// an absent Nextendo profile. Only localhost/numeric loopback are resolved. +#include "../net_socket.h" +#include +#include +#include +static unsigned calls, checks; +static int refuse(const char *name,char *out,size_t cap) { (void)name;(void)out;(void)cap;calls++;return -1; } +#define CHECK(c) do { checks++;assert(c); } while(0) +static int local(void) { dm_net_addrinfo hint={.family=2,.type=1};void *out=NULL; + int result=dm_net_getaddrinfo("localhost","0",&hint,&out);int okay=!result&&out; + if(out)dm_net_freeaddrinfo(out);return okay; } +int main(void) { + dm_net_set_dns_provider(refuse);unsetenv("DM_NETWORK");unsetenv("DM_NEXTENDO_ROUTES"); + CHECK(!dm_net_enabled()&&!dm_net_nextendo_enabled()&&!local()&&!calls); + setenv("DM_NETWORK","auto",1);CHECK(dm_net_enabled()&&!dm_net_nextendo_enabled()&&local()&&!calls); + setenv("DM_NEXTENDO_ROUTES","",1);CHECK(!dm_net_nextendo_enabled()&&local()&&!calls); + setenv("DM_NEXTENDO_ROUTES","explicit-but-invalid",1);dm_net_set_errno(113); + CHECK(dm_net_nextendo_enabled()&&!local()&&calls==1&&dm_net_errno()==113); + unsetenv("DM_NEXTENDO_ROUTES");setenv("DM_NETWORK","nextendo",1); + CHECK(dm_net_nextendo_enabled()&&!local()&&calls==2); + setenv("DM_NEXTENDO_ROUTES","explicit-but-invalid",1);setenv("DM_NETWORK","lan",1); + CHECK(!dm_net_nextendo_enabled()&&local()&&calls==2); + setenv("DM_NETWORK","ldn",1);CHECK(!dm_net_nextendo_enabled()&&local()&&calls==2); + printf("Online policy: %u checks PASS; unconfigured automatic/local DNS preserved\n",checks);return 0; +} +void dm_guest_host_wait_begin(void) {} void dm_guest_host_wait_end(void) {} diff --git a/dm/host/tests/t_pollwait.c b/dm/host/tests/t_pollwait.c index 5f97c00eb4..c08dd67a70 100644 --- a/dm/host/tests/t_pollwait.c +++ b/dm/host/tests/t_pollwait.c @@ -104,7 +104,10 @@ static void *signaller(void *unused) { return NULL; } int main(void) { - alarm(20); + setvbuf(stdout, NULL, _IONBF, 0); // each PASS line reaches the log as it passes, so a SIGALRM names the case that hung + // A hang guard, not a timing check (the checks count back-offs on poll_clock). The test makes about 2 s of real short sleeps, and a CI runner under ASan + // stretched them about a hundredfold: 200 sleeps of 300 us took 6.4 s and 241 took 9.6 s, and a 20 s alarm went off in the next case (run 42877114434) + alarm(60); me_handle = svc_thread_main_init(); poll_run(500, 0, 0); puts("PASS: 500 ns condition variable waits back off at 2 ms, not before"); diff --git a/dm/host/tests/t_resolver_cancel.c b/dm/host/tests/t_resolver_cancel.c new file mode 100644 index 0000000000..5b9920cc71 --- /dev/null +++ b/dm/host/tests/t_resolver_cancel.c @@ -0,0 +1,199 @@ +// Production resolver, synthetic Apple API. No DNS traffic or account data. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct _DNSServiceRef_t { + DNSServiceGetAddrInfoReply callback; + void *context; + dispatch_queue_t queue; + _Atomic int closed; +}; +static pthread_mutex_t fixture_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t fixture_changed = PTHREAD_COND_INITIALIZER; +static DNSServiceRef services[512]; +static unsigned service_count, deallocations, checks; +static int start_error, queue_error; +static char queue_key; +static DNSServiceErrorType fixture_start(DNSServiceRef *, DNSServiceFlags, uint32_t, + DNSServiceProtocol, const char *, DNSServiceGetAddrInfoReply, void *); +static DNSServiceErrorType fixture_queue(DNSServiceRef, dispatch_queue_t); +static void fixture_deallocate(DNSServiceRef); +#define DNSServiceGetAddrInfo fixture_start +#define DNSServiceSetDispatchQueue fixture_queue +#define DNSServiceRefDeallocate fixture_deallocate +#include "../hle_net_backend.c" +#undef DNSServiceGetAddrInfo +#undef DNSServiceSetDispatchQueue +#undef DNSServiceRefDeallocate + +static _Atomic unsigned waits, balances; +void dm_guest_host_wait_begin(void) { + atomic_fetch_add(&waits, 1); atomic_fetch_add(&balances, 1); + pthread_mutex_lock(&fixture_lock); pthread_cond_broadcast(&fixture_changed); pthread_mutex_unlock(&fixture_lock); +} +void dm_guest_host_wait_end(void) { atomic_fetch_sub(&balances, 1); } +#define CHECK(c) do { ++checks; if (!(c)) { fprintf(stderr,"FAIL %d: %s\n",__LINE__,#c); abort(); } } while (0) +static DNSServiceErrorType fixture_start(DNSServiceRef *out, DNSServiceFlags flags, uint32_t index, + DNSServiceProtocol protocol, const char *name, + DNSServiceGetAddrInfoReply callback, void *context) { + assert(dispatch_get_specific(&queue_key) == &queue_key); + assert(flags == kDNSServiceFlagsTimeout && !index && protocol == kDNSServiceProtocol_IPv4 && name && callback); + if (start_error) { *out=(DNSServiceRef)(uintptr_t)1; return start_error; } + DNSServiceRef service = calloc(1, sizeof *service); assert(service); + service->callback = callback; service->context = context; *out = service; + pthread_mutex_lock(&fixture_lock); assert(service_count < 512); + services[service_count++] = service; pthread_cond_broadcast(&fixture_changed); pthread_mutex_unlock(&fixture_lock); + return 0; +} +static DNSServiceErrorType fixture_queue(DNSServiceRef service, dispatch_queue_t queue) { + assert(service && queue && dispatch_get_specific(&queue_key) == &queue_key); + service->queue = queue; return queue_error; +} +static void fixture_deallocate(DNSServiceRef service) { + assert(dispatch_get_specific(&queue_key) == &queue_key && !atomic_exchange(&service->closed, 1)); + ++deallocations; +} +static void wait_services(unsigned target) { + struct timespec until; clock_gettime(CLOCK_REALTIME, &until); until.tv_sec += 5; + pthread_mutex_lock(&fixture_lock); + while (service_count < target) assert(!pthread_cond_timedwait(&fixture_changed, &fixture_lock, &until)); + pthread_mutex_unlock(&fixture_lock); +} +static int blocked, unblocked; +static void block_queue(void *unused) { + (void)unused; + pthread_mutex_lock(&fixture_lock); blocked=1; pthread_cond_broadcast(&fixture_changed); + while (!unblocked) pthread_cond_wait(&fixture_changed,&fixture_lock); + pthread_mutex_unlock(&fixture_lock); +} +static void wait_registry(unsigned expected, int finalizing) { + struct timespec until; clock_gettime(CLOCK_REALTIME,&until); until.tv_sec+=5; + pthread_mutex_lock(&fixture_lock); + for (;;) { + pthread_mutex_lock(&g_resolver_lock); unsigned active=0; + for (unsigned i=0;i<64;++i) active+=g_resolver_jobs[i]!=NULL; + int ready=blocked && active>=expected && (!finalizing || g_resolver_finalizing); + pthread_mutex_unlock(&g_resolver_lock); + if (ready) break; + assert(!pthread_cond_timedwait(&fixture_changed,&fixture_lock,&until)); + } + pthread_mutex_unlock(&fixture_lock); +} +static void unblock_queue(void) { + pthread_mutex_lock(&fixture_lock); unblocked=1; pthread_cond_broadcast(&fixture_changed); pthread_mutex_unlock(&fixture_lock); +} +static void *finalizer(void *unused) { (void)unused; dm_net_finalize(); return NULL; } +typedef struct { DNSServiceRef service; DNSServiceFlags flags; int error; uint32_t address; } response; +static void respond(void *context) { + response *r = context; + struct sockaddr_in address = {.sin_len=sizeof address,.sin_family=AF_INET,.sin_addr={r->address}}; + // An explicit late callback test holds its own job reference. Real Apple + // deallocation cancels callbacks; this also checks the publication guard. + r->service->callback(r->service, r->flags, 0, r->error, "fixture.invalid", + r->error ? NULL : (struct sockaddr *)&address, 60, r->service->context); +} +static void reply(DNSServiceRef service, DNSServiceFlags flags, int error, uint32_t address) { + response r = {service, flags, error, htonl(address)}; + dispatch_sync_f(g_resolver_queue, &r, respond); +} +typedef struct { uint32_t id; const char *name; pthread_t thread; int success, error; uint32_t addresses[65]; size_t count; } query; +static void *lookup(void *context) { + query *q = context; + typedef struct { char *name, **aliases; int family, length; char **addresses; } hostent; + dm_net_set_errno(37); + hostent *out = dm_net_gethostbyname_cancel(q->name, q->id); + q->success = out != NULL; q->error = dm_net_errno(); + if (out) { + assert(out->family == 2 && out->length == 4 && !out->aliases[0] && !strcmp(out->name,q->name)); + while (out->addresses[q->count]) { assert(q->count < 64); memcpy(&q->addresses[q->count],out->addresses[q->count],4); ++q->count; } + } + return NULL; +} +static void launch(query *q, uint32_t id) { *q=(query){.id=id,.name="fixture.invalid"}; CHECK(!pthread_create(&q->thread,NULL,lookup,q)); } +static void join(query *q) { CHECK(!pthread_join(q->thread,NULL)); } +int main(void) { + setenv("DM_NETWORK","lan",1); + CHECK(net_resolver_queue() != NULL); + dispatch_queue_set_specific(g_resolver_queue,&queue_key,&queue_key,NULL); + uint32_t id=dm_net_request_cancel_handle(); CHECK(id && dm_net_request_cancel_handle()!=id); + CHECK(dm_net_cancel(0)==0 && dm_net_errno()==22); + CHECK(dm_net_cancel(id)==0); // No tombstone for a future query. + query q; unsigned n=service_count; launch(&q,id); wait_services(n+1); + reply(services[n],kDNSServiceFlagsAdd|kDNSServiceFlagsMoreComing,0,0x7f000002); + reply(services[n],kDNSServiceFlagsAdd|kDNSServiceFlagsMoreComing,0,0x7f000002); + reply(services[n],kDNSServiceFlagsAdd,0,0x7f000003); join(&q); + CHECK(q.success && q.count==2 && q.addresses[0]==htonl(0x7f000002) && atomic_load(&services[n]->closed)); + // Reuse the same ID after successful completion; cancel only this generation. + n=service_count; launch(&q,id); wait_services(n+1); + net_resolver_job *late=services[n]->context; net_resolver_retain(late); + CHECK(dm_net_cancel(id)==0); join(&q); + CHECK(!q.success && q.error==125 && atomic_load(&services[n]->closed)); + reply(services[n],kDNSServiceFlagsAdd,0,0x7f000009); CHECK(late->count==0); + net_resolver_release(late); + n=service_count; launch(&q,id); wait_services(n+1); + reply(services[n],kDNSServiceFlagsAdd,0,0x7f000004); join(&q); CHECK(q.success && q.count==1); + // Queue an old generation's cancellation, then register a new query using + // the same ID before that cancellation runs. It must not target the new one. + query next; n=service_count; launch(&q,id); wait_services(n+1); + dispatch_async_f(g_resolver_queue,NULL,block_queue); wait_registry(1,0); + CHECK(!dm_net_cancel(id)); launch(&next,id); wait_registry(2,0); unblock_queue(); + wait_services(n+2); join(&q); CHECK(!q.success && q.error==125); + reply(services[n+1],kDNSServiceFlagsAdd,0,0x7f000005); join(&next); CHECK(next.success); + // A zero ID is a valid query, although Cancel(0) cannot cancel it. + n=service_count; launch(&q,0); wait_services(n+1); CHECK(dm_net_cancel(0)==0); + reply(services[n],0,kDNSServiceErr_NoSuchRecord,0); join(&q); CHECK(!q.success && q.error==37); + const int negative[]={kDNSServiceErr_NoSuchRecord,kDNSServiceErr_NoSuchName,0}; + for (unsigned i=0;i<3;++i) { + n=service_count; launch(&q,id); wait_services(n+1); + net_resolver_job *empty=services[n]->context; net_resolver_retain(empty); + reply(services[n],0,negative[i],0x7f000001); join(&q); + CHECK(!q.success && q.error==37 && empty->count==0); + reply(services[n],kDNSServiceFlagsAdd,0,0x7f000009); CHECK(empty->count==0); + net_resolver_release(empty); + } + const int errors[]={kDNSServiceErr_NoMemory,kDNSServiceErr_Timeout,kDNSServiceErr_ServiceNotRunning,kDNSServiceErr_PolicyDenied}; + const int expected[]={12,110,100,13}; + for (unsigned i=0;i<4;++i) { + n=service_count; launch(&q,id); wait_services(n+1); + net_resolver_job *failed=services[n]->context; net_resolver_retain(failed); + reply(services[n],0,errors[i],0); join(&q); CHECK(!q.success && q.error==expected[i]); + reply(services[n],kDNSServiceFlagsAdd,0,0x7f000001); CHECK(failed->count==0); + net_resolver_release(failed); + } + start_error=kDNSServiceErr_NoMemory; launch(&q,id); join(&q); CHECK(!q.success && q.error==12); start_error=0; + queue_error=kDNSServiceErr_BadParam; launch(&q,id); join(&q); CHECK(!q.success && q.error==22); queue_error=0; + // Finalize fences new native queries until all existing services are closed. + n=service_count; launch(&q,id); wait_services(n+1); blocked=unblocked=0; + dispatch_async_f(g_resolver_queue,NULL,block_queue); wait_registry(1,0); + pthread_t finisher; CHECK(!pthread_create(&finisher,NULL,finalizer,NULL)); wait_registry(1,1); + launch(&next,id); join(&next); CHECK(!next.success && next.error==11 && service_count==n+1); + unblock_queue(); CHECK(!pthread_join(finisher,NULL)); join(&q); CHECK(!q.success && q.error==125); + // All 64 slots can be live; a 65th operation fails without starting DNS. + query many[64]; n=service_count; + for (unsigned i=0;i<64;++i) launch(many+i,dm_net_request_cancel_handle()); + wait_services(n+64); launch(&q,id); join(&q); CHECK(!q.success && q.error==11 && service_count==n+64); + dm_net_finalize(); + for (unsigned i=0;i<64;++i) { join(many+i); CHECK(!many[i].success && many[i].error==125); } + CHECK(deallocations==service_count); + for (unsigned i=0;i<64;++i) CHECK(!g_resolver_jobs[i]); + // Numeric answers do not start DNS; offline mode remains unavailable. + setenv("DM_NETWORK","auto",1); n=service_count; + CHECK(dm_net_gethostbyname_cancel("127.0.0.1",0)!=NULL); + CHECK(dm_net_gethostbyname_cancel(NULL,id)==NULL && dm_net_errno()==22); + setenv("DM_NETWORK","offline",1); + CHECK(dm_net_gethostbyname_cancel("fixture.invalid",id)==NULL && dm_net_errno()==100); + CHECK(service_count==n && atomic_load(&waits)>0 && !atomic_load(&balances)); + atomic_store(&g_resolver_next_id,UINT64_C(0x100000000)); + CHECK(!dm_net_request_cancel_handle() && dm_net_errno()==11); + for (unsigned i=0;i +#include +#include +#include +#include +#include + +static unsigned waits, balance; +void dm_guest_host_wait_begin(void) { ++waits; ++balance; } +void dm_guest_host_wait_end(void) { --balance; } +int main(void) { + // This fixture watchdog only detects a broken smoke; the production query + // uses Apple's own kDNSServiceFlagsTimeout deadline without an app timer. + alarm(45); + setenv("DM_NETWORK","lan",1); + typedef struct { char *name, **aliases; int family, length; char **addresses; } hostent; + hostent *result=dm_net_gethostbyname_cancel("localhost",dm_net_request_cancel_handle()); + if (!result) { fprintf(stderr,"real Apple localhost lookup unavailable: errno=%d\n",dm_net_errno()); return 1; } + unsigned count=0; + while (result->addresses[count]) { + uint32_t address; memcpy(&address,result->addresses[count],4); + if ((ntohl(address)>>24)!=127 || count>=64) return 1; + ++count; + } + dm_net_finalize(); alarm(0); + if (!count || result->family!=2 || result->length!=4 || !waits || balance) return 1; + printf("real Apple DNSService localhost: %u loopback answers, callbacks completed, finalize PASS\n",count); + return 0; +} diff --git a/dm/host/tests/t_server_environment.c b/dm/host/tests/t_server_environment.c index 48c6af7d3e..9a682c798e 100644 --- a/dm/host/tests/t_server_environment.c +++ b/dm/host/tests/t_server_environment.c @@ -64,32 +64,7 @@ static void check_server_environment(void) { } } -static void check_friend_ids(void) { - Result (*ids)(int *, void *, int, int, const void *) = hook("_ZN2nn7friends13GetFriendListEPiPNS_7account23NetworkServiceAccountIdEiiRKNS0_12FriendFilterE"); - Result (*ids_uid)(int *, void *, const void *, int, int, const void *) = hook("_ZN2nn7friends13GetFriendListEPiPNS_7account23NetworkServiceAccountIdERKNS2_3UidEiiRKNS0_12FriendFilterE"); - const uint64_t before[] = {0x123456789abcdef0, 0xfedcba9876543210}; - uint64_t output[2]; - uint8_t uid[16] = {1}, filter[32] = {0}; - if (ids) { - int count = 7; - memcpy(output, before, sizeof output); - CHECK(ids(&count, output, 2, 2, filter) == RES_FAIL, "friend IDs without Uid remain unavailable offline"); - CHECK(count == 0, "unavailable ID list reports zero entries"); - CHECK(!memcmp(output, before, sizeof output), "unavailable ID list leaves client storage untouched"); - count = 7; - CHECK(ids(&count, NULL, 0, 0, filter) == RES_FAIL && count == 0, "zero-capacity ID query remains empty"); - } - if (ids_uid) { - int count = 7; - memcpy(output, before, sizeof output); - CHECK(ids_uid(&count, output, uid, 2, 2, filter) == RES_FAIL, "friend IDs with Uid remain unavailable offline"); - CHECK(count == 0, "unavailable per-user ID list reports zero entries"); - CHECK(!memcmp(output, before, sizeof output), "unavailable per-user ID list leaves client storage untouched"); - count = 7; - CHECK(ids_uid(&count, NULL, uid, 0, 0, filter) == RES_FAIL && count == 0, "zero-capacity per-user query remains empty"); - } -} - +// The friend ID lists (Super Kirby Clash) are hle_friends.c's on this branch, where the Nextendo provider answers them: t_friends checks them offline static void check_network_error(void) { void (*show)(Result) = hook("_ZN2nn3err23ShowNetworkServiceErrorENS_6ResultE"); if (show) { @@ -101,7 +76,6 @@ static void check_network_error(void) { int main(void) { check_server_environment(); - check_friend_ids(); CHECK(enters == 0 && leaves == 0, "offline queries open no applet"); check_network_error(); CHECK(unexpected == 0, "offline handlers need no event binding or network operation"); diff --git a/dm/host/tests/t_ssl.m b/dm/host/tests/t_ssl.m new file mode 100644 index 0000000000..c26b462df2 --- /dev/null +++ b/dm/host/tests/t_ssl.m @@ -0,0 +1,360 @@ +// Real loopback TLS through the guest's actual C / C++ HLE entries and production socket ownership API. +// test_ssl_transport.py creates an ephemeral test CA/server and invokes this executable; no user credentials or trust-store mutations. +#import +#import +#include "../hle.h" +#include "t_gate_fixture.h" +#include "../ssl_backend.h" +#include "../net_socket.h" +#include +#include +#include +#include +#include +#include + +static int checks, failures; +static _Atomic int entered, left, waits; +static NSData *caPem, *caDer, *clientPki; +static NSString *systemRoot; +static unsigned port; +static char context_key[32], connection_key[32]; +#define CHECK(condition, message) do { checks++; if (!(condition)) { failures++; fprintf(stderr, "FAIL line %d: %s\n", __LINE__, message); } } while (0) +static uint64_t milliseconds(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000; } +void dm_guest_host_wait_begin(void) { atomic_fetch_add(&waits, 1); } +void dm_guest_host_wait_end(void) {} +void thr_svc_enter(uint64_t *registers, uint64_t pc) { (void)registers; (void)pc; atomic_fetch_add(&entered, 1); } +void thr_svc_leave(void) { atomic_fetch_add(&left, 1); } +int dm_guest_as_contains(uintptr_t address) { (void)address; return 0; } +uint64_t gate_dispatch(uint64_t ret, uint64_t *registers) { (void)ret; (void)registers; abort(); } +uint64_t unimpl_c(unsigned index, uint64_t *registers) { (void)index; (void)registers; abort(); } +void dm_thread_returned(void) { abort(); } +static void *hook(const char *name) { + fixture_gate_prepare(); + unsigned long bytes; const hle_force_ent *p = (const hle_force_ent *)getsectiondata(&_mh_execute_header, "__DATA", "swforce", &bytes); + for (unsigned long i = 0; p && i < bytes / sizeof *p; i++) if (!strcmp(p[i].name, name)) return p[i].fn; + fprintf(stderr, "Missing TLS hook: %s\n", name); abort(); +} +#define H(type, name) ((type)hook(name)) +typedef uint32_t (*ContextCreate)(void *, unsigned); +typedef uint32_t (*ConnectionCreate)(void *, void *); +typedef uint32_t (*ObjectCall)(void *); +typedef uint32_t (*SetInt)(void *, unsigned); +typedef uint32_t (*Read)(void *, void *, int *, unsigned); +typedef uint32_t (*Write)(void *, const void *, int *, unsigned); +typedef uint32_t (*Poll)(void *, unsigned *, const unsigned *, unsigned); +typedef struct { uint8_t len, family; uint16_t port; uint32_t ip; uint8_t padding[8]; } Address; +static void identifier_lifecycle(void) { + typedef uint32_t (*GetId)(void *, uint64_t *); + uint64_t id = UINT64_MAX, context_id = UINT64_MAX, connection_id = UINT64_MAX; + CHECK(H(GetId, "nnsslContextGetContextId")(context_key, &id) == 0 && id == 0, + "empty C context query succeeds with identifier zero before creation"); + CHECK(H(GetId, "_ZN2nn3ssl7Context12GetContextIdEPm")(context_key, &id) == 0 && id == 0, + "empty C++ context query has the same SDK semantics"); + CHECK(H(GetId, "nnsslConnectionGetConnectionId")(connection_key, &id) == 0 && id == 0, + "empty connection query succeeds with identifier zero"); + CHECK(H(GetId, "_ZN2nn3ssl10Connection12GetContextIdEPm")(connection_key, &id) == 0 && id == 0, + "empty connection has no associated context identifier"); + CHECK(H(ObjectCall, "nnsslConnectionDoHandshake")(connection_key) != 0 && + H(ConnectionCreate, "nnsslConnectionCreate")(connection_key, context_key) != 0, + "identifier queries do not create a context or grant a TLS session"); + CHECK(H(ContextCreate, "_ZN2nn3ssl7Context6CreateENS1_10SslVersionE")(context_key, 1) == 0 && + H(GetId, "nnsslContextGetContextId")(context_key, &context_id) == 0 && context_id, + "C++ context creation after the empty C query produces a real identifier"); + CHECK(H(ConnectionCreate, "nnsslConnectionCreate")(connection_key, context_key) == 0 && + H(GetId, "nnsslConnectionGetConnectionId")(connection_key, &connection_id) == 0 && connection_id && connection_id != context_id, + "connection creation retains a distinct live identifier"); + CHECK(H(GetId, "_ZN2nn3ssl10Connection12GetContextIdEPm")(connection_key, &id) == 0 && id == context_id, + "live connection reports its actual parent context identifier"); + CHECK(H(ObjectCall, "nnsslConnectionDestroy")(connection_key) == 0 && + H(GetId, "nnsslConnectionGetConnectionId")(connection_key, &id) == 0 && id == 0, + "destroyed connection returns to the empty identifier state"); + CHECK(H(ObjectCall, "nnsslContextDestroy")(context_key) == 0 && + H(GetId, "nnsslContextGetContextId")(context_key, &id) == 0 && id == 0, + "destroyed context returns to the empty identifier state"); + CHECK(H(GetId, "nnsslContextGetContextId")(NULL, &id) == DM_SSL_BAD_POINTER && + H(GetId, "nnsslContextGetContextId")(context_key, NULL) == DM_SSL_BAD_POINTER && + H(GetId, "nnsslConnectionGetConnectionId")(NULL, &id) == DM_SSL_BAD_POINTER && + H(GetId, "nnsslConnectionGetConnectionId")(connection_key, NULL) == DM_SSL_BAD_POINTER, + "identifier query null-pointer errors remain failures"); +} +static int create(bool import) { + memset(context_key, 0xa5, sizeof context_key); memset(connection_key, 0x5a, sizeof connection_key); + CHECK(H(ContextCreate, "nnsslContextCreate")(context_key, 32) == 0, "C context create uses caller object pointer"); + if (import) { + uint64_t id = 0; + CHECK(H(uint32_t (*)(void *, uint64_t *, const void *, unsigned, int), "_ZN2nn3ssl7Context15ImportServerPkiEPmPKcjNS0_17CertificateFormatE")(context_key, &id, caPem.bytes, (unsigned)caPem.length, 1) == 0 && id, "actual C++ ImportServerPki imports only a test CA into this context"); + } + CHECK(H(ConnectionCreate, "nnsslConnectionCreate")(connection_key, context_key) == 0, "C connection create links actual context"); + CHECK(context_key[0] == (char)0xa5 && connection_key[0] == 0x5a, "no guessed SDK private fields are overwritten"); + CHECK(H(ObjectCall, "nnsslContextDestroy")(context_key) != 0, "context cannot be destroyed with an active connection"); + int fd = dm_net_socket(2, 1, 6); Address address = {16, 2, htons(port), htonl(0x7f000001), {0}}; + CHECK(fd >= 0 && dm_net_connect(fd, &address, sizeof address) == 0, "production guest socket connects to local TLS server"); + CHECK(H(uint32_t (*)(void *, int), "nnsslConnectionSetSocketDescriptor")(connection_key, fd) == 0, "TLS borrows an owned native duplicate with its generation"); + return fd; +} +static void hostname(const char *name) { CHECK(H(uint32_t (*)(void *, const char *, unsigned), "nnsslConnectionSetHostName")(connection_key, name, (unsigned)strlen(name)) == 0, "set actual TLS peer hostname"); } +static uint32_t handshake(bool nonblock) { + CHECK(H(SetInt, "nnsslConnectionSetIoMode")(connection_key, nonblock ? 2 : 1) == 0, "select TLS blocking mode"); + uint64_t deadline = milliseconds() + 5000; unsigned wouldblock = 0; + for (;;) { + uint32_t r = H(ObjectCall, "nnsslConnectionDoHandshake")(connection_key); + if (r != DM_SSL_WOULD_BLOCK) { if (nonblock) CHECK(wouldblock > 0, "nonblocking handshake actually yielded WouldBlock"); return r; } + wouldblock++; if (milliseconds() > deadline) return DM_SSL_TIMEOUT; + unsigned wanted = 1, ready = 0; H(Poll, "nnsslConnectionPoll")(connection_key, &ready, &wanted, 100); + } +} +static uint32_t read_some(void *bytes, int *n, unsigned capacity, bool peek) { + uint64_t deadline = milliseconds() + 5000; + for (;;) { + uint32_t result = H(Read, peek ? "nnsslConnectionPeek" : "nnsslConnectionRead")(connection_key, bytes, n, capacity); + if (result != DM_SSL_WOULD_BLOCK) return result; + if (milliseconds() >= deadline) return DM_SSL_TIMEOUT; + unsigned wanted = 1, ready = 0; H(Poll, "nnsslConnectionPoll")(connection_key, &ready, &wanted, 100); + } +} +static void destroy(int fd, bool already_closed) { + CHECK(H(ObjectCall, "nnsslConnectionDestroy")(connection_key) == 0, "TLS connection destroy"); + if (!already_closed) { Address a; unsigned n = sizeof a; CHECK(dm_net_name(fd, &a, &n, 0) < 0 && dm_net_errno() == 9, "default TLS ownership closes the original generation"); } + CHECK(H(ObjectCall, "nnsslContextDestroy")(context_key) == 0, "TLS context released"); +} +static void trusted(void) { + int fd = create(true); hostname("localhost"); + CHECK(H(uint32_t (*)(void *, int, unsigned), "nnsslConnectionSetOption")(connection_key, 3, 1) == 0, "enable ALPN"); + uint8_t alpn[] = {2, 'h', '2', 8, 'h', 't', 't', 'p', '/', '1', '.', '1'}; + CHECK(H(uint32_t (*)(void *, const uint8_t *, unsigned), "nnsslConnectionSetNextAlpnProto")(connection_key, alpn, sizeof alpn) == 0, "SDK19 C ALPN input buffer signature"); + CHECK(handshake(true) == 0, "trusted loopback TLS handshake validates chain and hostname"); + unsigned omitted_size = 99, omitted_count = 99; + CHECK(H(uint32_t (*)(void *, unsigned *, unsigned *), "nnsslConnectionDoHandshakeWithCertBuffer")(connection_key, &omitted_size, &omitted_count) == 0 && !omitted_size && !omitted_count, + "an unregistered certificate buffer performs a verified handshake without exporting certificates"); + CHECK(H(uint32_t (*)(void *, unsigned *, unsigned *), "_ZN2nn3ssl10Connection11DoHandshakeEPjS2_")(connection_key, NULL, NULL) == 0, + "the SDK permits omitted certificate output pointers"); + uint8_t untouched = 0x7a; omitted_size = omitted_count = 99; + CHECK(H(uint32_t (*)(void *, unsigned *, unsigned *, void *, unsigned), "nnsslConnectionDoHandshakeWithBuffer")(connection_key, &omitted_size, &omitted_count, &untouched, 0) == 0 && !omitted_size && !omitted_count && untouched == 0x7a, + "a zero-capacity certificate buffer follows the SDK's handshake-only branch without writing it"); + CHECK(H(uint32_t (*)(void *, unsigned *, unsigned *, void *, unsigned), "_ZN2nn3ssl10Connection11DoHandshakeEPjS2_Pcj")(connection_key, &omitted_size, &omitted_count, NULL, 8192) == 0 && !omitted_size && !omitted_count, + "a null explicit certificate buffer also selects handshake-only semantics"); + unsigned state = 0, size = 0; uint8_t selected[16] = {0}; + CHECK(H(uint32_t (*)(void *, unsigned *, uint8_t *, unsigned *, unsigned), "nnsslConnectionGetNextAlpnProto")(connection_key, &state, selected, &size, sizeof selected) == 0 && state == 1 && size == 8 && !memcmp(selected, "http/1.1", 8), "native ALPN reports the server selection rather than the client's first choice"); + char cipher[72]; CHECK(H(uint32_t (*)(void *, void *), "_ZN2nn3ssl10Connection13GetCipherInfoEPNS1_10CipherInfoE")(connection_key, cipher) == 0 && !strcmp(cipher + 64, "TLSv1.2"), "actual negotiated TLS version reported"); + unsigned wanted = 1, ready = 99; uint64_t start = milliseconds(); + CHECK(H(Poll, "nnsslConnectionPoll")(connection_key, &ready, &wanted, 10) == 0 && ready == 0 && milliseconds() - start >= 8, "TLS poll honors the full finite timeout"); + char bytes[64] = {0}; int n = 99; uint32_t result = H(Read, "nnsslConnectionRead")(connection_key, bytes, &n, sizeof bytes); + CHECK(result == DM_SSL_WOULD_BLOCK && n == 0, "nonblocking TLS read exposes proper WouldBlock result"); + CHECK(read_some(bytes, &n, 5, true) == 0 && n == 5 && !memcmp(bytes, "HELLO", 5), "TLS peek decrypts without consuming"); + int pending = 0; CHECK(H(uint32_t (*)(void *, int *), "nnsslConnectionPending")(connection_key, &pending) == 0 && pending >= 5, "peek data included in pending"); + CHECK(read_some(bytes, &n, 5, false) == 0 && n == 5 && !memcmp(bytes, "HELLO", 5), "TLS read consumes peeked data exactly once"); + n = 0; CHECK(H(Write, "nnsslConnectionWrite")(connection_key, "ECHO", &n, 4) == 0 && n == 4, "actual TLS write"); + unsigned total = 0; + while (total < 4) { n = 0; result = read_some(bytes + total, &n, 4 - total, false); if (result || n <= 0) break; total += (unsigned)n; } + CHECK(total == 4 && !memcmp(bytes, "ABCD", 4), "partial native TLS records preserve bytes"); + uint8_t certificates[8193]; memset(certificates, 0x7a, sizeof certificates); unsigned count = 0; size = 0; + CHECK(H(uint32_t (*)(void *, unsigned *, unsigned *, void *, unsigned), "nnsslConnectionDoHandshakeWithBuffer")(connection_key, &size, &count, certificates, 8192) == 0 && size > 128 && count == 1 && certificates[8192] == 0x7a, "verified explicit-buffer C handshake signature exports leaf DER"); + CHECK(H(uint32_t (*)(void *, unsigned *, unsigned *, void *, unsigned), "nnsslConnectionDoHandshakeWithBuffer")(connection_key, NULL, NULL, certificates, 8192) == 0 && certificates[8192] == 0x7a, + "a real certificate buffer is exported even when its metadata output pointers are omitted"); + certificates[0] = 0x7a; + CHECK(H(uint32_t (*)(void *, unsigned *, unsigned *, void *, unsigned), "nnsslConnectionDoHandshakeWithBuffer")(connection_key, &size, &count, certificates, 1) != 0 && certificates[0] == 0x7a, + "a nonempty undersized certificate buffer still fails without a partial certificate write"); + CHECK(H(uint32_t (*)(void *, void *, unsigned), "nnsslConnectionSetServerCertBuffer")(connection_key, certificates, 8192) == 0, "register server certificate buffer"); + CHECK(H(uint32_t (*)(void *, unsigned *, unsigned *), "nnsslConnectionDoHandshakeWithCertBuffer")(connection_key, &size, &count) == 0 && size > 128 && count == 1, "verified three-argument WithCertBuffer uses the registered buffer"); + CHECK(H(uint32_t (*)(void *, int, unsigned), "nnsslConnectionSetOption")(connection_key, 1, 1) == 0, "request actual server certificate chain"); + CHECK(H(uint32_t (*)(void *, unsigned *, unsigned *, void *, unsigned), "nnsslConnectionDoHandshakeWithBuffer")(connection_key, &size, &count, certificates, 8192) == 0 && count >= 1 && !memcmp(certificates, "CertChMN", 8), "actual chain envelope produced"); + struct { uint32_t size, pad; const uint8_t *data; } detail = {0}; + CHECK(H(uint32_t (*)(void *, void *, const void *, unsigned), "nnsslConnectionGetServerCertDetail")(connection_key, &detail, certificates, 0) == 0 && detail.size > 128 && detail.data >= certificates && detail.data + detail.size <= certificates + size, "chain detail layout and offset correct"); + CHECK(read_some(bytes, &n, sizeof bytes, false) == 0 && n == 0, "close_notify is orderly TLS EOF"); + destroy(fd, false); +} +static void rejected(bool import, const char *name) { + int fd = create(import); hostname(name); + CHECK(handshake(false) != 0, import ? "wrong hostname rejected with trusted CA" : "untrusted test CA rejected"); + uint32_t verify = 0; CHECK(H(uint32_t (*)(void *, uint32_t *), "nnsslConnectionGetVerifyCertError")(connection_key, &verify) == 0 && verify != 0, "certificate verification failure retained"); + CHECK(H(ObjectCall, "nnsslConnectionDoHandshake")(connection_key) != 0, "failed trust cannot be bypassed by retrying after reading its error"); + unsigned size = 99, count = 99; + CHECK(H(uint32_t (*)(void *, unsigned *, unsigned *), "nnsslConnectionDoHandshakeWithCertBuffer")(connection_key, &size, &count) != 0 && !size && !count, + "omitting certificate export never bypasses failed chain or hostname verification"); + destroy(fd, false); +} +static bool scoped_policy(const char *guest, char *host, size_t capacity, const uint8_t **der, size_t *size) { + if (strcmp(guest, "api.console.invalid") || capacity < 10) return false; + memcpy(host, "localhost", 10); *der = caDer.bytes; *size = caDer.length; return true; +} +static void scoped(void) { + dm_ssl_set_peer_policy(scoped_policy); int fd = create(false); hostname("api.console.invalid"); + CHECK(handshake(false) == 0, "explicit host policy rewrites SNI and scopes a copied DER CA"); destroy(fd, false); + rejected(false, "outside.invalid"); dm_ssl_set_peer_policy(NULL); +} +static void ownership(void) { + int fd = create(false); CHECK(dm_net_close(fd) == 0, "application closes its original while TLS retains a duplicate"); + int reused = dm_net_socket(2, 2, 17); CHECK(reused == fd, "guest descriptor slot reused"); destroy(fd, true); + Address a; unsigned n = sizeof a; CHECK(dm_net_name(reused, &a, &n, 0) == 0, "TLS destroy generation guard preserves the reused guest descriptor"); dm_net_close(reused); + CHECK(H(ContextCreate, "nnsslContextCreate")(context_key, 32) == 0 && H(ConnectionCreate, "nnsslConnectionCreate")(connection_key, context_key) == 0, "second ownership context"); + CHECK(H(uint32_t (*)(void *, int, unsigned), "nnsslConnectionSetOption")(connection_key, 0, 1) == 0, "DoNotCloseSocket configured before attachment"); + fd = dm_net_socket(2, 1, 6); Address address = {16, 2, htons(port), htonl(0x7f000001), {0}}; + CHECK(dm_net_connect(fd, &address, sizeof address) == 0 && H(uint32_t (*)(void *, int), "nnsslConnectionSetSocketDescriptor")(connection_key, fd) == 0, "attach independently owned connection"); + CHECK(H(ObjectCall, "nnsslConnectionDestroy")(connection_key) == 0, "destroy DoNotCloseSocket connection"); n = sizeof a; + CHECK(dm_net_name(fd, &a, &n, 0) == 0, "explicit DoNotCloseSocket preserves the original"); dm_net_close(fd); H(ObjectCall, "nnsslContextDestroy")(context_key); + CHECK(H(ContextCreate, "nnsslContextCreate")(context_key, 32) == 0 && H(ConnectionCreate, "nnsslConnectionCreate")(connection_key, context_key) == 0, "stream-only adapter context"); + fd = dm_net_socket(2, 2, 17); CHECK(fd >= 0 && dm_net_connect(fd, &address, sizeof address) == 0, "native UDP socket is actually connected"); + CHECK(H(uint32_t (*)(void *, int), "nnsslConnectionSetSocketDescriptor")(connection_key, fd) == DM_SSL_BAD_SOCKET, "stream TLS rejects connected UDP before taking ownership"); + CHECK(H(ObjectCall, "nnsslConnectionDestroy")(connection_key) == 0, "rejected datagram connection destroys safely"); n = sizeof a; + CHECK(dm_net_name(fd, &a, &n, 0) == 0, "failed socket attachment leaves the caller's datagram open"); dm_net_close(fd); H(ObjectCall, "nnsslContextDestroy")(context_key); +} +static void abrupt(void) { + int fd = create(true); hostname("localhost"); CHECK(handshake(false) == 0, "abrupt-close test handshake"); + char bytes[16]; int n = 0; CHECK(read_some(bytes, &n, 5, false) == 0 && n == 5, "abrupt-close greeting"); + CHECK(H(Write, "nnsslConnectionWrite")(connection_key, "ABRT", &n, 4) == 0 && n == 4, "request abrupt TCP close from the test server"); + CHECK(read_some(bytes, &n, sizeof bytes, false) != 0 && n == 0, "raw TCP EOF without close_notify is a TLS truncation error"); destroy(fd, false); +} +typedef struct { int result; } BlockedRead; +static void *blocked_reader(void *opaque) { + BlockedRead *call = opaque; char byte; + call->result = H(int (*)(void *, char *, unsigned), "_ZN2nn3ssl10Connection4ReadEPcj")(connection_key, &byte, 1); + return NULL; +} +static void concurrent_destroy(void) { + int fd = create(true); hostname("localhost"); CHECK(handshake(false) == 0, "concurrent close handshake"); + char bytes[8]; int n = 0; CHECK(read_some(bytes, &n, 5, false) == 0 && n == 5, "concurrent close greeting"); + CHECK(H(int (*)(void *, const char *, unsigned), "_ZN2nn3ssl10Connection5WriteEPKcj")(connection_key, "WAIT", 4) == 4, "scalar C++ Write returns the real byte count"); + BlockedRead call = {0}; pthread_t thread; CHECK(pthread_create(&thread, NULL, blocked_reader, &call) == 0, "start actual blocking TLS read"); + struct timespec pause = {0, 30000000}; nanosleep(&pause, NULL); uint64_t start = milliseconds(); + CHECK(H(ObjectCall, "nnsslConnectionDestroy")(connection_key) == 0, "destroy can cancel a connection while its TLS read owns it"); + int reused = dm_net_socket(2, 2, 17); CHECK(reused == fd, "original slot reused while old read exits"); + CHECK(pthread_join(thread, NULL) == 0 && call.result == -1 && milliseconds() - start < 1000, "scalar C++ Read exits on close without using the reused slot"); + Address a; unsigned length = sizeof a; CHECK(dm_net_name(reused, &a, &length, 0) == 0, "old TLS operation leaves the reused descriptor intact"); dm_net_close(reused); + CHECK(H(ObjectCall, "nnsslContextDestroy")(context_key) == 0, "context released after canceled operation"); +} +static void mutual_authentication(void) { + if (@available(macOS 15.0, iOS 18.0, *)) { + int fd = create(true); uint64_t identifier = 0; + typedef uint32_t (*ImportClient)(void *, uint64_t *, const char *, const char *, unsigned, unsigned); + ImportClient import = H(ImportClient, "_ZN2nn3ssl7Context15ImportClientPkiEPmPKcS4_jj"); + CHECK(import(context_key, NULL, clientPki.bytes, "test-only", (unsigned)clientPki.length, 9) == DM_SSL_BAD_POINTER, "PKCS12 import requires its public output ID pointer"); + CHECK(import(context_key, &identifier, clientPki.bytes, "incorrect", (unsigned)clientPki.length, 9) != 0, "PKCS12 rejects a wrong test password"); + CHECK(import(context_key, &identifier, clientPki.bytes, "test-only", (unsigned)clientPki.length, 9) == 0 && identifier, "test client identity imported only into memory"); + hostname("localhost"); CHECK(handshake(false) == 0, "mutual TLS client identity handshake"); + char bytes[8]; int n = 0; + CHECK(read_some(bytes, &n, 5, false) == 0 && n == 5, "mutual TLS greeting"); + CHECK(H(Write, "nnsslConnectionWrite")(connection_key, "MTLS", &n, 4) == 0 && n == 4, "request peer-observed certificate evidence"); + CHECK(read_some(bytes, &n, 4, false) == 0 && n == 4 && !memcmp(bytes, "CERT", 4), "server verified the real client certificate and private-key proof"); + CHECK(H(uint32_t (*)(void *, uint64_t), "_ZN2nn3ssl7Context9RemovePkiEm")(context_key, identifier) == 0, "imported client identity can be removed"); + destroy(fd, false); + } +} +static void backpressure(bool nonblock) { + int fd = create(true); hostname("localhost"); CHECK(handshake(nonblock) == 0, "backpressure handshake"); + int small = 4096; unsigned option_size = sizeof small; CHECK(dm_net_sockopt(fd, 0xffff, 0x1001, &small, &option_size, 1) == 0, "constrain the actual TCP send buffer"); + char greeting[8]; int n = 0; CHECK(read_some(greeting, &n, 5, false) == 0 && n == 5, "backpressure greeting"); + CHECK(H(Write, "nnsslConnectionWrite")(connection_key, "BULK", &n, 4) == 0 && n == 4, "begin delayed native server read"); + unsigned size = 2 * 1024 * 1024, position = 0, blocked = 0; uint8_t *data = malloc(size); for (unsigned i = 0; i < size; i++) data[i] = i % 251; + uint64_t deadline = milliseconds() + 8000; + while (position < size && milliseconds() < deadline) { + n = 0; uint32_t result = H(Write, "nnsslConnectionWrite")(connection_key, data + position, &n, size - position); + if (result == DM_SSL_WOULD_BLOCK) { blocked++; if (n) break; unsigned wanted = 2, ready = 0; H(Poll, "nnsslConnectionPoll")(connection_key, &ready, &wanted, 100); } + else if (result || n <= 0 || (unsigned)n > size - position) break; + else position += (unsigned)n; + } + CHECK(position == size && (!nonblock || blocked > 0), "TLS writes resume under native backpressure in the selected I/O mode"); + CHECK(read_some(greeting, &n, 4, false) == 0 && n == 4 && !memcmp(greeting, "GOOD", 4), "server receives every byte once, including the last cached TLS record"); + free(data); destroy(fd, false); +} +static void read_timeout(void) { + int fd = create(true); hostname("localhost"); CHECK(handshake(false) == 0, "timeout test handshake"); + char bytes[8]; int n = 0; CHECK(read_some(bytes, &n, 5, false) == 0 && n == 5, "timeout test greeting"); + CHECK(H(Write, "nnsslConnectionWrite")(connection_key, "WAIT", &n, 4) == 0 && n == 4, "server deliberately waits without TLS plaintext"); + CHECK(H(SetInt, "_ZN2nn3ssl17ConnectionPrivate12SetIoTimeoutEj")(connection_key, 30) == 0, "set the actual SDK I/O timeout"); + uint64_t start = milliseconds(); uint32_t result = H(Read, "nnsslConnectionRead")(connection_key, bytes, &n, sizeof bytes); + CHECK(result == DM_SSL_TIMEOUT && n == 0 && milliseconds() - start >= 25 && milliseconds() - start < 1000, "blocking TLS read observes its real deadline and returns Horizon Timeout"); + destroy(fd, false); +} +typedef struct { uint32_t id, status; uint64_t size; const uint8_t *data; } BuiltinInfo; +static NSString *store_path(void) { return [systemRoot stringByAppendingPathComponent:@"0100000000000800/files/ssl_TrustedCerts.bdf"]; } +static NSMutableData *store_fixture(uint32_t status) { + NSMutableData *data = [NSMutableData dataWithLength:24 + caDer.length]; uint32_t header[] = {0x546c7373, 1, 1, status, (uint32_t)caDer.length, 16}; + memcpy(data.mutableBytes, header, sizeof header); memcpy((char *)data.mutableBytes + 24, caDer.bytes, caDer.length); return data; +} +static bool stand_in_ca(const uint8_t **der, size_t *size) { *der = caDer.bytes; *size = caDer.length; return true; } +static void builtin_store(void) { + typedef uint32_t (*GetSize)(unsigned *, const uint32_t *, unsigned); + typedef uint32_t (*GetCerts)(void **, uint8_t *, unsigned, const uint32_t *, unsigned); + GetSize get_size = H(GetSize, "_ZN2nn3ssl14BuiltInManager28GetBuiltInCertificateBufSizeEPjPNS0_15CaCertificateIdEj"); + GetCerts get_certs = H(GetCerts, "_ZN2nn3ssl14BuiltInManager22GetBuiltInCertificatesEPPNS1_22BuiltInCertificateInfoEPhjPNS0_15CaCertificateIdEj"); + unsetenv("DM_SYSTEM_DATA_DIR"); unsetenv("DM_SYSTEM_DIR"); unsigned size = 99; uint32_t id = 1; + CHECK(dm_ssl_import_server(context_key, NULL, caDer.bytes, (unsigned)caDer.length, 2) == DM_SSL_BAD_POINTER, "server certificate import requires its public output ID pointer"); + CHECK(get_size(&size, &id, 1) != 0 && !size, "missing firmware never fabricates a built-in CA"); + // A provider's CA stands in for a missing store (Nextendo's, hle_nextendo_routes.c): served under each ID asked for, and not once a store file exists + dm_ssl_set_builtin_fallback(stand_in_ca); uint32_t pair[2] = {1, 0x3e8}; unsigned one = 24 + ((caDer.length + 3) & ~(NSUInteger)3); + CHECK(get_size(&size, pair, 2) == 0 && size == 2 * one, "no store: the provider's CA stands in under each ID asked for"); + uint8_t *standIn = malloc(size); void *standOut = NULL; BuiltinInfo second; + CHECK(get_certs(&standOut, standIn, size, pair, 2) == 0 && standOut == standIn, "stand-in certificates fit the advertised size"); + memcpy(&second, standIn + 24, sizeof second); + CHECK(second.id == 0x3e8 && second.status == 1 && second.size == caDer.length && !memcmp(second.data, caDer.bytes, caDer.length), "each stand-in entry keeps the ID asked for and the provider's DER"); + free(standIn); + [[NSFileManager defaultManager] createDirectoryAtPath:[store_path() stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil]; + setenv("DM_SYSTEM_DATA_DIR", systemRoot.fileSystemRepresentation, 1); NSMutableData *fixture = store_fixture(1); + CHECK([fixture writeToFile:store_path() atomically:YES], "write synthetic public test CA store outside the repository"); + CHECK(get_size(&size, &id, 1) == 0 && size == 24 + ((caDer.length + 3) & ~(NSUInteger)3), "BDF size uses the SDK's 24-byte pointer record and aligned DER"); + id = 0x3e8; CHECK(get_size(&size, &id, 1) != 0 && !size, "with a store file the stand-in is not used: an ID it lacks fails"); id = 1; dm_ssl_set_builtin_fallback(NULL); + CHECK(get_size(&size, &id, 1) == 0, "store size again after the stand-in check"); + uint8_t *buffer = malloc(size + 25); memset(buffer, 0x6b, size + 25); void *output = (void *)1; + CHECK(get_certs(&output, buffer, size - 1, &id, 1) != 0 && output == NULL && buffer[0] == 0x6b, "undersized certificate output writes no partial metadata"); + CHECK(get_certs(&output, buffer, size, &id, 1) == 0 && output == buffer && buffer[size] == 0x6b, "built-in output respects caller capacity"); + BuiltinInfo info; memcpy(&info, buffer, sizeof info); + CHECK(sizeof info == 24 && info.id == 1 && info.status == 1 && info.size == caDer.length && info.data == buffer + 24 && !memcmp(info.data, caDer.bytes, caDer.length), "actual built-in ID, trust status, size, pointer and DER preserved"); + id = UINT32_MAX; unsigned all_size = 0; CHECK(get_size(&all_size, &id, 1) == 0 && all_size == size + 24, "All query reserves its real end sentinel"); + CHECK(get_certs(&output, buffer, all_size, &id, 1) == 0, "All query exports original entries"); + BuiltinInfo sentinel; memcpy(&sentinel, buffer + 24, sizeof sentinel); + CHECK(sentinel.id == UINT32_MAX && sentinel.status == UINT32_MAX && sentinel.size == 0 && sentinel.data == NULL, "All query terminates without a fake certificate"); + id = 999; CHECK(get_size(&size, &id, 1) != 0 && !size, "unknown firmware certificate ID fails"); + id = 1; uint32_t bad_offset = UINT32_MAX; memcpy((char *)fixture.mutableBytes + 20, &bad_offset, 4); [fixture writeToFile:store_path() atomically:YES]; + CHECK(get_size(&size, &id, 1) != 0 && !size, "BDF entry outside file bounds rejected"); + fixture = store_fixture(1); ((char *)fixture.mutableBytes)[24] = 0; [fixture writeToFile:store_path() atomically:YES]; + CHECK(get_size(&size, &id, 1) != 0 && !size, "malformed DER rejected before exposing an entry"); + fixture = store_fixture(1); ((char *)fixture.mutableBytes)[0] = 0; [fixture writeToFile:store_path() atomically:YES]; + CHECK(get_size(&size, &id, 1) != 0 && !size, "wrong BDF magic rejected"); + fixture = store_fixture(2); [fixture writeToFile:store_path() atomically:YES]; rejected(false, "localhost"); + fixture = store_fixture(1); [fixture writeToFile:store_path() atomically:YES]; + int fd = create(false); hostname("localhost"); CHECK(handshake(false) == 0, "original trusted firmware anchor applies only to the TLS context"); destroy(fd, false); + rejected(false, "wrong.invalid"); + // The CertStore archive's file in DM_SYSTEM_DIR's system data layout (hle_fs.c), when DM_SYSTEM_DATA_DIR has none + [[NSFileManager defaultManager] removeItemAtPath:store_path() error:nil]; unsetenv("DM_SYSTEM_DATA_DIR"); + NSString *sysdata = [systemRoot stringByAppendingPathComponent:@"sysdata/0100000000000800/ssl_TrustedCerts.bdf"]; + [[NSFileManager defaultManager] createDirectoryAtPath:[sysdata stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil]; + CHECK([store_fixture(1) writeToFile:sysdata atomically:YES], "write synthetic public test CA store in the system data layout"); + setenv("DM_SYSTEM_DIR", systemRoot.fileSystemRepresentation, 1); + CHECK(get_size(&size, &id, 1) == 0 && size == 24 + ((caDer.length + 3) & ~(NSUInteger)3), "store read from DM_SYSTEM_DIR/sysdata/0100000000000800"); + free(buffer); [[NSFileManager defaultManager] removeItemAtPath:sysdata error:nil]; unsetenv("DM_SYSTEM_DIR"); +} +static int check_real_store(const char *directory) { + setenv("DM_NETWORK", "lan", 1); setenv("DM_SYSTEM_DATA_DIR", directory, 1); uint32_t all = UINT32_MAX; unsigned size = 0; + CHECK(dm_ssl_builtin_size(&size, &all, 1) == 0 && size > 24, "real firmware certificate table parsed"); + if (!size) return 1; uint8_t *bytes = malloc(size + 1); bytes[size] = 0xa5; void *out = NULL; + CHECK(dm_ssl_builtin_certificates(&out, bytes, size, &all, 1) == 0 && out == bytes && bytes[size] == 0xa5, "real firmware output fits exact advertised size"); + unsigned count = 0, trusted_count = 0; + for (unsigned i = 0; i < size / 24; i++) { + BuiltinInfo info; memcpy(&info, bytes + i * 24, sizeof info); if (info.id == UINT32_MAX) break; + CHECK(info.data >= bytes && info.data <= bytes + size && info.size <= (uint64_t)(bytes + size - info.data), "real certificate pointer stays within the output allocation"); + NSData *der = [NSData dataWithBytes:info.data length:(NSUInteger)info.size]; SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)der); + CHECK(certificate != NULL && info.status <= 3, "real firmware certificate DER and status valid"); if (certificate) CFRelease(certificate); + count++; trusted_count += info.status == 1; + } + printf("real firmware certificate store: %u entries, %u trusted; %d checks, %d failures\n", count, trusted_count, checks, failures); free(bytes); return failures ? 1 : 0; +} +int main(int argc, char **argv) { @autoreleasepool { + if (argc == 3 && !strcmp(argv[1], "--certstore")) return check_real_store(argv[2]); + if (argc != 6) return 2; + NSString *caPemPath=[NSString stringWithUTF8String:argv[1]], *caDerPath=[NSString stringWithUTF8String:argv[2]], *pkiPath=[NSString stringWithUTF8String:argv[4]]; + if (!caPemPath || !caDerPath || !pkiPath) return 2; + caPem = [NSData dataWithContentsOfFile:caPemPath]; caDer = [NSData dataWithContentsOfFile:caDerPath]; port = (unsigned)strtoul(argv[3], NULL, 10); + clientPki = [NSData dataWithContentsOfFile:pkiPath]; + systemRoot = [NSString stringWithUTF8String:argv[5]]; + CHECK(caPem.length && caDer.length && clientPki.length && port, "ephemeral TLS test fixtures loaded"); + setenv("DM_NETWORK", "offline", 1); + CHECK(H(uint32_t (*)(void), "nnsslInitialize")() == 0 && H(ContextCreate, "nnsslContextCreate")(context_key, 32) != 0, "offline SSL initialization compatibility without a fake TLS session"); + setenv("DM_NETWORK", "lan", 1); + CHECK(H(ContextCreate, "nnsslContextCreate")(context_key, 64) != 0, "TLS1.3-only request is not silently downgraded"); + identifier_lifecycle(); + trusted(); rejected(false, "localhost"); rejected(true, "wrong.invalid"); scoped(); ownership(); abrupt(); concurrent_destroy(); mutual_authentication(); backpressure(true); backpressure(false); read_timeout(); builtin_store(); + CHECK(H(uint32_t (*)(void), "nnsslFinalize")() == 0, "SSL finalization"); + CHECK(atomic_load(&entered) > 0 && atomic_load(&entered) == atomic_load(&left) && atomic_load(&waits) > 0, "TLS blocking operations publish balanced guest contexts and yield while waiting"); + printf("TLS hooks: %d checks, %d failures\n", checks, failures); return failures ? 1 : 0; +} } diff --git a/dm/host/tests/t_ssl_trace.c b/dm/host/tests/t_ssl_trace.c new file mode 100644 index 0000000000..664c3f9141 --- /dev/null +++ b/dm/host/tests/t_ssl_trace.c @@ -0,0 +1,43 @@ +// Exercise the numeric writer's privacy boundary without TLS, accounts or game files. +#include "../ssl_trace.h" +#include +#include +#include + +static _Atomic unsigned failures; +static void *writer(void *unused) { + (void)unused; + for (unsigned i = 0; i < 200; ++i) { + errno = EDOM; + dm_tls_trace(DM_TLS_HANDSHAKE, UINT64_MAX, UINT32_MAX, INT32_MIN, UINT64_MAX, 0x3f); + if (errno != EDOM) atomic_fetch_add(&failures, 1); + } + return NULL; +} +int main(void) { + FILE *capture = tmpfile(); assert(capture); + fflush(stderr); int saved = dup(STDERR_FILENO); assert(saved >= 0); + assert(dup2(fileno(capture), STDERR_FILENO) >= 0); + const char *disabled[] = {NULL, "", "0", "true", "01", "1x"}; + for (unsigned i = 0; i < sizeof disabled / sizeof *disabled; ++i) { + if (disabled[i]) assert(!setenv("DM_SSL_TRACE", disabled[i], 1)); + else assert(!unsetenv("DM_SSL_TRACE")); + errno = ERANGE; dm_tls_trace(DM_TLS_HOSTNAME, 0, 0, 0, 0, 0); + assert(errno == ERANGE); + } + fflush(stderr); assert(ftell(capture) == 0); + assert(!setenv("DM_SSL_TRACE", "1", 1)); + pthread_t threads[8]; + for (unsigned i = 0; i < 8; ++i) assert(!pthread_create(threads + i, NULL, writer, NULL)); + for (unsigned i = 0; i < 8; ++i) assert(!pthread_join(threads[i], NULL)); + assert(!atomic_load(&failures)); + fflush(stderr); assert(dup2(saved, STDERR_FILENO) >= 0); assert(!close(saved)); + assert(!fseek(capture, 0, SEEK_SET)); char line[256]; unsigned lines = 0; + while (fgets(line, sizeof line, capture)) { + assert(!strcmp(line, "[ssl-trace] stage=6 session=18446744073709551615 result=0xffffffff native=-2147483648 detail=18446744073709551615 flags=0x3f\n")); + ++lines; + } + assert(lines == 128 && !ferror(capture)); assert(!fclose(capture)); + puts("TLS trace: disabled modes, concurrent 128-event bound, numeric-only fields and errno preservation PASS"); + return 0; +} diff --git a/dm/host/tests/t_symbols.c b/dm/host/tests/t_symbols.c index 69ad4828d8..da99b74068 100644 --- a/dm/host/tests/t_symbols.c +++ b/dm/host/tests/t_symbols.c @@ -22,6 +22,7 @@ static uint8_t *test_section(const struct mach_header_64 *mh, const char *seg, c #include "../hle.c" #include "../loader.c" void mtl_present_screen(uint32_t w, uint32_t h) { (void)w; (void)h; } // loader.c: a screen taller than 16:9; no renderer here +dm_net_mode_t dm_net_mode(void) { return DM_NET_OFFLINE; } // loader.c: main from the --nextendo copy only online #undef getsectiondata struct dm_flags g_flag; diff --git a/dm/host/tests/test_bcat_launch.py b/dm/host/tests/test_bcat_launch.py new file mode 100644 index 0000000000..a21310cf13 --- /dev/null +++ b/dm/host/tests/test_bcat_launch.py @@ -0,0 +1,161 @@ +"""Run the real launch selector/downloader with original synthetic HTTPS data. + +No provider connection, account, Nintendo resource or app is used. The private +runtime copy differs only in its test signing pin and synthetic XML digest; +the fixture also supplies its own temporary home and synthetic HTTP responses. +Each invocation is a NEW process, so a cached launch cannot skip revalidation. +""" +from pathlib import Path +import base64 +import hashlib +import io +import json +import os +import shutil +import shlex +import subprocess +import tempfile +import time +import zipfile +from datetime import datetime, timezone + +REPO = Path(__file__).resolve().parents[3] +SOURCE = REPO / 'dm/host/hle_bcat_apple.m' +PIN = 'xI+atR6VesrCH89ZDZD4t3WQLcYOFEhk5F0HLMzgWk4=' +XML = b'' + + +def run(): + with tempfile.TemporaryDirectory(prefix='bcat-launch-') as temp: + root = Path(temp).resolve() + crypto = os.environ.get('DM_OPENSSL_ROOT') or subprocess.check_output([os.environ.get('PYTHON', 'python3'), str(REPO / 'dm/tools/apple_crypto.py'), 'macos'], text=True).strip() + openssl = os.environ.get('OPENSSL_TOOL', '/opt/homebrew/opt/openssl@4/bin/openssl') + secret = bytes.fromhex('302e020100300506032b657004220420') + bytes([7]) + bytes(31) + (root / 'key.der').write_bytes(secret) + public = subprocess.check_output([openssl, 'pkey', '-inform', 'DER', '-in', str(root / 'key.der'), '-pubout', '-outform', 'DER'])[-32:] + def signed(enabled=True): + now = int(time.time()) + def fmt(value): + return datetime.fromtimestamp(value, timezone.utc).isoformat().replace('+00:00', 'Z') + payload = json.dumps({'document_type': 'game_catalog', 'schema_version': 1, 'revision': 4, + 'issued_at': fmt(now - 60), 'expires_at': fmt(now + 3600), + 'games': [{'title_ids': ['0100f8f0000a2000'], 'enabled': enabled, + 'required_capabilities': ['versions.exact.v1'], 'versions': {'policy': 'exact', 'accepted': ['5.5.2']}}]}, separators=(',', ':')).encode() + (root / 'payload').write_bytes(payload) + sig = subprocess.check_output([openssl, 'pkeyutl', '-sign', '-rawin', '-keyform', 'DER', '-inkey', str(root / 'key.der'), '-in', str(root / 'payload')]) + return json.dumps({'key_id': 'catalog-key-1', 'payload': base64.b64encode(payload).decode(), 'signature': base64.b64encode(sig).decode()}).encode() + (root / 'catalog.json').write_bytes(signed()) + (root / 'invalid.json').write_bytes(signed(False)) + (root / 'static.xml').write_bytes(XML) + (root / 'dummy.txt').write_bytes(b'0') + names = ['coopdata/CoopSetting.byaml', 'vsdata/VSSetting_0.byaml', 'vsdata/VSSetting_1.byaml', 'fesdata/Festival.byaml', 'fesdata/HapTexture.bfres', 'fesdata/IconTexture.bfres', 'fesdata/PanelTexture.bfres'] + for marker in [1, 2]: + buf = io.BytesIO() + with zipfile.ZipFile(buf, 'w', compression=zipfile.ZIP_DEFLATED) as archive: + for name in names: + data = (b'YB\x02\0' + bytes(27) if name.endswith('.byaml') else b'FRES' + bytes(27)) + bytes([marker]) + archive.writestr(name, data) + (root / f'v{marker}.zip').write_bytes(buf.getvalue()) + (root / 'corrupt.zip').write_bytes(b'not a ZIP') + source = SOURCE.read_text() + old_xml = '8d8d21a93dce2f8eab1659a3bf5cdca10f61df83d50bc0a34784b1629dd215fa' + assert source.count(PIN) == source.count(old_xml) == 1 + source = source.replace(PIN, base64.b64encode(public).decode()).replace(old_xml, hashlib.sha256(XML).hexdigest()) + runtime = root / 'fixture-runtime.inc' + runtime.write_text(source) + binary = root / 'launch' + flags = shlex.split(os.environ.get('SAN', '')) + if os.environ.get('DM_BCAT_TEST_SANITIZE') == '1' and not flags: + flags = ['-fsanitize=address,undefined', '-fno-omit-frame-pointer'] + print('BCAT launch compiler sanitizer flags:', flags or 'none', flush=True) + command = ['clang', '-O1', '-g', '-Wall', '-Wextra', '-Werror', '-Wno-unused-function', '-Wno-unused-parameter', '-Wno-deprecated-declarations', '-fobjc-arc', *flags, + '-I' + str(REPO / 'dm/host'), '-I' + str(Path(crypto) / 'include'), '-DDM_OPENSSL_X509', '-DDM_BCAT_RUNTIME_INCLUDE="' + str(runtime) + '"', '-DDM_BCAT_TITLES=@"0100f8f0000a2000",@"01003bc0000a0000",@"01003c700009c800"', '-DDM_BCAT_PLAIN_TITLE=@"01003c700009c800"', + str(REPO / 'dm/host/tests/t_bcat_launch.m'), str(Path(crypto) / 'lib/libcrypto.a'), '-lz', '-framework', 'Foundation', '-o', str(binary)] + subprocess.run(command, check=True) + cache = root / 'cache' + def launch(mode, expected, *, use_cache=cache): + child_env = os.environ.copy() + if any('-fsanitize=' in flag for flag in flags): + child_env['ASAN_OPTIONS'] = child_env.get('ASAN_OPTIONS', '') + ':halt_on_error=1' + child_env['UBSAN_OPTIONS'] = child_env.get('UBSAN_OPTIONS', '') + ':halt_on_error=1' + completed = subprocess.run([str(binary), str(root), mode, str(use_cache)], capture_output=True, text=True, timeout=20, env=child_env) + if completed.returncode: + raise RuntimeError(f'BCAT scenario {mode} exited {completed.returncode}:\n{completed.stderr}') + value = json.loads(completed.stdout) + assert value['firstCalendarMarker'] == expected, (mode, value, completed.stderr) + if mode != 'offline' and not mode.startswith('gate-'): + assert value['catalogRequests'] == (2 if mode == 'runtime-refresh' else 1), (mode, value) + elif mode == 'offline': + assert value['requests'] == 0 and not value['freshAttempt'], value + assert not value['syncAccepted'], value + print(mode, json.dumps(value, sort_keys=True), flush=True) + return value + first = launch('v1', 1) + assert first['result'] == 0 and first['archiveRequests'] == 1 + again = launch('304', 1) + assert again['result'] == 0 and again['conditionalRequests'] == 1 + changed = launch('v2', 2) + assert changed['result'] == 0 and changed['conditionalRequests'] == 1 + runtime = launch('runtime-refresh', 1, use_cache=root / 'runtime-cache') + assert (runtime['runtimeDeliveryMarker'], runtime['runtimeOverlayMarker'], runtime['retainedFDMarker']) == (2, 1, 1), runtime + plain_cache = root / 'cache-without-etag' + for _ in range(2): + plain = launch('noetag', 1, use_cache=plain_cache) + assert plain['result'] == 0 and plain['archiveRequests'] == 1 and plain['conditionalRequests'] == 0 + pointer = (cache / 'current.json').read_bytes() + inventory = {str(p.relative_to(cache)): hashlib.sha256(p.read_bytes()).hexdigest() for p in cache.rglob('*') if p.is_file()} + for mode in ['error', 'corrupt', 'invalid', 'timeout']: + result = launch(mode, 2) + assert result['result'] != 0 + if mode == 'timeout': + assert 11 <= result['elapsed'] <= 14, result + assert result['archiveRequests'] == 1, result + assert (cache / 'current.json').read_bytes() == pointer + assert {str(p.relative_to(cache)): hashlib.sha256(p.read_bytes()).hexdigest() for p in cache.rglob('*') if p.is_file()} == inventory + launch('offline', 2) + launch('offline', 0, use_cache=root / 'empty-cache') + profile = root / 'valid-profile' + shutil.copytree(cache, profile) + setup = {'formatVersion': 1, 'titleID': '0100f8f0000a2000', 'version': '5.5.2'} + (profile / 'setup.json').write_text(json.dumps(setup)) + invalid = root / 'invalid-profile' + invalid.mkdir() + (invalid / 'setup.json').write_text(json.dumps(dict(setup, titleID='01003bc0000a0000'))) + for mode in ['gate-missing', 'gate-invalid', 'gate-unrelated']: + value = launch(mode, 0) + assert not value['requests'] and not value['freshAttempt'] and not value['syncAccepted'], value + offline = launch('gate-no-provider', 2) + assert not offline['requests'] and not offline['freshAttempt'] and not offline['syncAccepted'], offline + online = launch('gate-online', 1) + assert online['catalogRequests'] == online['archiveRequests'] == 1 and online['result'] == 0, online + # A normal build without the optional verifier must retain the offline + # behavior, even if another caller incorrectly requests online mode. + no_crypto = [value for value in command if value not in ('-DDM_OPENSSL_X509', str(Path(crypto) / 'lib/libcrypto.a'))] + subprocess.run(no_crypto, check=True) + unavailable = launch('gate-no-verifier', 0) + assert not unavailable['requests'] and not unavailable['freshAttempt'] and not unavailable['syncAccepted'], unavailable + provider = root / 'fixture-provider.c' + provider.write_text('int dm_bcat_online_enabled(void) { return 1; }\n') + subprocess.run([*command, str(provider)], check=True) + bridged = launch('gate-provider-online', 1) + assert bridged['catalogRequests'] == bridged['archiveRequests'] == 1 and bridged['result'] == 0, bridged + process = subprocess.Popen([str(binary), str(root), 'interrupt', str(cache)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + deadline = time.monotonic() + 5 + while not (root / 'interrupt-ready').exists(): + assert process.poll() is None and time.monotonic() < deadline + time.sleep(0.01) + process.terminate() + process.communicate(timeout=3) + assert process.returncode != 0 + assert (cache / 'current.json').read_bytes() == pointer + assert {str(p.relative_to(cache)): hashlib.sha256(p.read_bytes()).hexdigest() for p in cache.rglob('*') if p.is_file()} == inventory + finally: + if process.poll() is None: + process.kill() + process.communicate(timeout=3) + print('BCAT launch refresh: 20 new-process scenarios passed; first open/fallback/304/no-ETag/shared deadline/interruption/profile/provider/verifier gates and immutable runtime overlay validated') + + +if __name__ == '__main__': + run() diff --git a/dm/host/tests/test_bcat_zip.py b/dm/host/tests/test_bcat_zip.py new file mode 100644 index 0000000000..2a0d098e58 --- /dev/null +++ b/dm/host/tests/test_bcat_zip.py @@ -0,0 +1,64 @@ +"""Run the production bounded ZIP reader on original synthetic calendars.""" +from pathlib import Path +import io +import struct +import subprocess +import sys +import tempfile +import zipfile +import warnings + +names = ('coopdata/CoopSetting.byaml', 'vsdata/VSSetting_0.byaml', 'vsdata/VSSetting_1.byaml', + 'fesdata/Festival.byaml', 'fesdata/HapTexture.bfres', 'fesdata/IconTexture.bfres', 'fesdata/PanelTexture.bfres') +byaml = b'YB\x02\0' + struct.pack(' { + Binding(get: { nextendoBirthdayFormat.date(from: birthday) ?? nextendoBirthdayFormat.date(from: nextendoBirthdayDefault)! }, + set: { birthday = nextendoBirthdayFormat.string(from: $0) }) + } + + var body: some View { + Section { + HStack { + Text("Nextendo account") + Spacer() + Text(busy ? "Checking…" : account ?? "Not signed in").foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle) + } + if dm_nextendo_signed_in() { + DatePicker("Birthday, if Nextendo has none", selection: birthdayDate, in: ...Date(), displayedComponents: .date) + Button("Sign out", role: .destructive) { dm_nextendo_sign_out(); account = nil; note = "" }.disabled(busy) + } else { + Button("Sign in…") { + busy = true; note = "" + dm_nextendo_sign_in { a, e in busy = false; account = a; note = e ?? "" } + }.disabled(busy) + } + } header: { Text("Online") } footer: { + Text(note.isEmpty ? "Online play goes through Nextendo, a community service. Set Network to Nextendo to use it. Nextendo asks for a verified e-mail address and a Discord link before online play." : note) + } + .onAppear { + guard dm_nextendo_signed_in() else { return } + busy = true + dm_nextendo_check { a, e in busy = false; account = a; note = e ?? "" } + } + } +} + +/// The name other players see (DM_NICK; hle_account.c GetNickname). Empty: the Nextendo username in Nextendo mode, else Player. At most 10 characters, a Switch +/// nickname's limit, which game menus are sized for. Kept under its own key and put in the environment at Play while Network is not offline +private let playerNameKey = "player.name" +private let playerNameMax = 10 +private struct PlayerNameSection: View { + @Binding var name: String + let fixed: Bool // an env file or the launch set DM_NICK: shown, not changed + + var body: some View { + Section { + TextField("Use my Nextendo name", text: $name) + .textInputAutocapitalization(.never).autocorrectionDisabled().disabled(fixed) + .onChange(of: name) { _, typed in if typed.count > playerNameMax { name = String(typed.prefix(playerNameMax)) } } + } header: { Text("Player name") } footer: { + Text(fixed ? "Set by an env file or at launch." : "The name other players see, up to 10 characters. Leave it empty to use your Nextendo username (Player when not signed in).") + } + } +} + /// UIDocumentPickerViewController for a folder, in the two callbacks a SwiftUI sheet wants. private struct DocumentPicker: UIViewControllerRepresentable { var types: [UTType] = [.folder] @@ -104,6 +170,10 @@ private struct LauncherView: View { @State private var report: SaveSyncReport? @State private var asking: SaveSyncReport.Step? + @AppStorage(playerNameKey) private var playerName = "" + private var nameFixed: Bool { m.fixed.contains("DM_NICK") } + private var nameShown: Bool { ["lan", "ldn", "nextendo", "auto"].contains(m.values["DM_NETWORK"] ?? "") } + var body: some View { GeometryReader { geometry in // Landscape: the game's name and Play on the left third, the settings beside them; upright (Rotation, an iPad turned), the name and Play above the settings @@ -174,12 +244,16 @@ private struct LauncherView: View { } } } + if nameShown { + PlayerNameSection(name: nameFixed ? .constant(getenv("DM_NICK").map { String(cString: $0) } ?? "") : $playerName, fixed: nameFixed) + } Section { Button("Reset to tested defaults") { m.reset() } .disabled(!m.changed) } footer: { Text("Brings back all settings this game was tested with.") } + if dm_nextendo_built() { NextendoSection() } // The background save check reads the selected folder until it returns. CloudSavesSection(checking: checking) Section { @@ -245,9 +319,30 @@ private struct LauncherView: View { private func go(_ choice: String?) { asking = nil if let choice { setenv("DM_SAVE_SYNC_CHOICE", choice, 1); fputs("launcher: DM_SAVE_SYNC_CHOICE=\(choice)\n", stderr) } + applyNextendoProfile() + applyPlayerName() play() } + /// The typed player name (PlayerNameSection), while Network is not offline; what an env file or the launch set stays, and an empty field leaves the game's default + private func applyPlayerName() { + let typed = playerName.trimmingCharacters(in: .whitespacesAndNewlines) + guard !nameFixed, nameShown, !typed.isEmpty else { return } + setenv("DM_NICK", String(typed.prefix(playerNameMax)), 1); fputs("launcher: DM_NICK set\n", stderr) + } + + /// The birthday picked under the Nextendo account and the device's region, for the Nintendo Account info a game reads online (hle_account.c: the Nextendo + /// account's own country comes first). What an env file or the launch set stays + private func applyNextendoProfile() { + guard dm_nextendo_built() else { return } + if getenv("DM_NEXTENDO_BIRTHDAY") == nil, let b = UserDefaults.standard.string(forKey: nextendoBirthdayKey), nextendoBirthdayFormat.date(from: b) != nil { + setenv("DM_NEXTENDO_BIRTHDAY", b, 1); fputs("launcher: DM_NEXTENDO_BIRTHDAY set\n", stderr) + } + if getenv("DM_NEXTENDO_COUNTRY") == nil, let region = Locale.current.region?.identifier, region.count == 2, region.allSatisfy({ $0.isASCII && $0.isUppercase }) { + setenv("DM_NEXTENDO_COUNTRY", region, 1); fputs("launcher: DM_NEXTENDO_COUNTRY=\(region)\n", stderr) + } + } + private func appIcon() -> UIImage? { if let i = UIImage(named: "AppIcon") { return i } guard let icons = info("CFBundleIcons") as? [String: Any], let primary = icons["CFBundlePrimaryIcon"] as? [String: Any], diff --git a/dm/ios/Sources/NextendoSignIn.h b/dm/ios/Sources/NextendoSignIn.h new file mode 100644 index 0000000000..5e721f4703 --- /dev/null +++ b/dm/ios/Sources/NextendoSignIn.h @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT +// The launcher's Nextendo section (Launcher.swift) calls these. They sign in through dm/host/nextendo_login_apple.inc, showing +// Nextendo's page in an ASWebAuthenticationSession; the host turns the saved sign-in into a game token when a game asks +// (hle_nextendo_login_apple.m). + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// YES when the app was built with --nextendo, so its bundle holds the public service profile (dm/nextendo-services, build_ipa.sh). +BOOL dm_nextendo_built(void); + +/// YES when a sign-in is saved on this device. No network; dm_nextendo_check tests the account itself. +BOOL dm_nextendo_signed_in(void); + +/// Fetches a game token as a game would, off the main thread. done runs on the main thread with "name (PID n)", or nil and the reason. +void dm_nextendo_check(void (^done)(NSString *_Nullable account, NSString *_Nullable error)); + +/// Shows Nextendo's sign-in page over the app. done runs on the main thread when it is over, as for dm_nextendo_check. +void dm_nextendo_sign_in(void (^done)(NSString *_Nullable account, NSString *_Nullable error)); + +/// Deletes the saved sign-in. +void dm_nextendo_sign_out(void); + +NS_ASSUME_NONNULL_END diff --git a/dm/ios/Sources/NextendoSignIn.m b/dm/ios/Sources/NextendoSignIn.m new file mode 100644 index 0000000000..6911c08990 --- /dev/null +++ b/dm/ios/Sources/NextendoSignIn.m @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: MIT +// Nextendo sign-in on the iPhone (NextendoSignIn.h). Nextendo redirects only to a loopback address, which neither a custom URL scheme +// nor an associated domain can stand for. So the web authentication session is started without a callback scheme, a listener in the +// app takes the redirect, and the session is then closed by the app. +#import "NextendoSignIn.h" +#define NXL_TRANSFER_CLASS DmNextendoSignInTransfer +#import "../../host/nextendo_login_apple.inc" +#import +#import + +typedef void (^DmNextendoDone)(NSString *_Nullable account, NSString *_Nullable error); + +static void report(DmNextendoDone done, NSDictionary *record, NSString *why) { + NSString *account = record ? [NSString stringWithFormat:@"%@ (PID %@)", record[@"identity"][@"username"], record[@"identity"][@"pid"]] : nil; + NSString *error = record ? nil : why ?: @"the sign-in failed"; + dispatch_async(dispatch_get_main_queue(), ^{ done(account, error); }); +} + +BOOL dm_nextendo_built(void) { + NSString *profile = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"dm/nextendo-services/routes.tsv"]; + return [NSFileManager.defaultManager fileExistsAtPath:profile]; +} +BOOL dm_nextendo_signed_in(void) { return nxl_read_refresh() != nil; } +void dm_nextendo_sign_out(void) { nxl_write_refresh(nil); } +void dm_nextendo_check(DmNextendoDone done) { + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + NSString *why = nil; + NSDictionary *record = nxl_game_record(&why); + report(done, record, why); + }); +} + +// The window the sign-in sheet is shown over: the key window of a connected scene, else any window of one +@interface DmNextendoPresenter : NSObject +@end +@implementation DmNextendoPresenter +- (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session { + (void)session; + UIWindow *fallback = nil; + for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) { + if (![scene isKindOfClass:UIWindowScene.class]) continue; + for (UIWindow *window in ((UIWindowScene *)scene).windows) { + if (window.isKeyWindow) return window; + if (!fallback) fallback = window; + } + } + return fallback ?: [[UIWindow alloc] init]; // the launcher always has a window; this keeps the type's contract +} +@end + +void dm_nextendo_sign_in(DmNextendoDone done) { + static ASWebAuthenticationSession *current; + static DmNextendoPresenter *presenter; + static _Atomic int closed_by_player; + if (!nxl_client_id()) { report(done, nil, kNxNoClient); return; } + NSString *verifier = nxl_random_urlsafe(32), *state = nxl_random_urlsafe(16); + uint16_t port = 0; + int listener = verifier && state ? nxl_listen_loopback(&port) : -1; + if (listener < 0) { report(done, nil, @"the sign-in could not start (no loopback listener)"); return; } + NSString *redirect = [NSString stringWithFormat:@"http://127.0.0.1:%u/callback", port]; + + [current cancel]; + atomic_store(&closed_by_player, 0); + presenter = [DmNextendoPresenter new]; + // With no callback scheme, the completion handler runs only when the player closes the sheet + current = [[ASWebAuthenticationSession alloc] initWithURL:nxl_authorize_url(redirect, state, verifier) callbackURLScheme:nil + completionHandler:^(NSURL *url, NSError *error) { (void)url; (void)error; atomic_store(&closed_by_player, 1); }]; + current.presentationContextProvider = presenter; + current.prefersEphemeralWebBrowserSession = NO; + if (![current start]) { + close(listener); current = nil; + report(done, nil, @"the sign-in page could not be shown"); + return; + } + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + NSDictionary *query = nxl_wait_callback(listener, state, 300, &closed_by_player); + close(listener); + bool cancelled = atomic_load(&closed_by_player); + dispatch_async(dispatch_get_main_queue(), ^{ [current cancel]; current = nil; }); + if (!query) { report(done, nil, cancelled ? @"the sign-in was cancelled" : @"no answer from the sign-in page in 5 minutes"); return; } + NSString *why = nil; + NSDictionary *record = nxl_finish_sign_in(query, verifier, redirect, &why); + report(done, record, why); + }); +} diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.m index 5f9b4204b0..92c1660e33 100644 --- a/dm/ios/Sources/main.m +++ b/dm/ios/Sources/main.m @@ -202,9 +202,27 @@ static int boot_env(void) { aoc_locate(); // add-on content: Documents/aoc, else /aoc; an empty Documents/aoc explicitly selects no DLC NSString *pso = [res stringByAppendingPathComponent:@"pso"]; // the pipeline archive made offline (build_ipa.sh, dm/gfx/tools/pso_offline.py): the shader pairs' bases, which the device then does not build if ([fm fileExistsAtPath:pso]) setenv("DM_PSO_BUNDLE", pso.fileSystemRepresentation, 0); + // An app built with --nextendo (build_ipa.sh): the public service profile, unless an env file names another. hle_nextendo_routes.c takes only files of this + // user's, writable by no one else, and the installer may own the bundle's: a private copy in Library/Application Support each start + NSString *bundled = [res stringByAppendingPathComponent:@"dm/nextendo-services"]; + if (!getenv("DM_NEXTENDO_ROUTES") && [fm fileExistsAtPath:[bundled stringByAppendingPathComponent:@"routes.tsv"]]) { + NSString *copy = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"nxnative/nextendo-services"]; + BOOL ok = [fm createDirectoryAtPath:copy withIntermediateDirectories:YES attributes:@{NSFilePosixPermissions: @0700} error:nil]; + // every file of the profile: routes.tsv, provider-ca.der, manifest.json and the pinned server certificates (.der, dm/tools/nextendo_services.py) + NSArray *files = [fm contentsOfDirectoryAtPath:bundled error:nil]; + ok = ok && files.count; + for (NSString *f in files) { + NSString *to = [copy stringByAppendingPathComponent:f]; + ok = ok && [[NSData dataWithContentsOfFile:[bundled stringByAppendingPathComponent:f]] writeToFile:to atomically:YES] && !chmod(to.fileSystemRepresentation, 0600); + } + if (ok) setenv("DM_NEXTENDO_ROUTES", [copy stringByAppendingPathComponent:@"routes.tsv"].fileSystemRepresentation, 0); + else fprintf(stderr, "[RED] boot: the Nextendo service profile could not be copied to %s; Nextendo mode refuses every service\n", copy.fileSystemRepresentation); + } chdir(doc.fileSystemRepresentation); g_argv[0] = strdup("dmhost"); g_argv[1] = strdup(dm.fileSystemRepresentation); g_argc = 2; - dm_host_preload_start(g_argc, g_argv); // Module tables / relocation / takeover run early in the background, in parallel with UIKit startup (and the launcher: the settings it sets are read when the game starts) + // Module tables / relocation / takeover run early in the background, in parallel with UIKit startup (and the launcher: the settings it sets are read when the game starts). + // Not with Nextendo's patched main (dm/nextendo, loader.c nextendo_main): which main loads follows the launcher's Network choice, so loading waits for Play + if (![fm fileExistsAtPath:[dm stringByAppendingPathComponent:@"nextendo/main.fixups.tsv"]]) dm_host_preload_start(g_argc, g_argv); return 1; } diff --git a/dm/ios/project.yml b/dm/ios/project.yml index d89d0aed8f..75b40d4fe8 100644 --- a/dm/ios/project.yml +++ b/dm/ios/project.yml @@ -52,6 +52,7 @@ targets: GCSupportsControllerUserInteraction: true # Physical controllers (GameController) GCSupportedGameControllers: - ProfileName: ExtendedGamepad + NSLocalNetworkUsageDescription: Local multiplayer uses your local network to find and connect to compatible peers. CADisableMinimumFrameDurationOnPhone: true UIApplicationSceneManifest: UIApplicationSupportsMultipleScenes: false diff --git a/dm/ios/tools/build_ipa.sh b/dm/ios/tools/build_ipa.sh index cfb2152017..ef6aabfa11 100755 --- a/dm/ios/tools/build_ipa.sh +++ b/dm/ios/tools/build_ipa.sh @@ -18,6 +18,9 @@ # DM_LANG= is the game language (DMLanguage in Info.plist, default en-US; DM_LANG in the app's Documents/env.txt overrides it on the phone); # both are also the launcher's defaults (dm/launcher.json from dm/games/settings.py; the player's choice there wins over them, Documents/env.txt over the choice); # the IPA name, code modules, RomFS marker and shader tables come from the game profile +# DM_NEXTENDO_SERVICES= (the NSP script's --nextendo): the public Nextendo service profile into dm/nextendo-services (main.m); a $PATCHED/nextendo (Nextendo's patched main) +# goes in as module nmain (gen_embed.py) with its tables in dm/nextendo; DM_NETWORK and DM_NEXTENDO are the launcher's Network defaults (dm/games/settings.tsv); +# DM_NEXTENDO_CLIENT_ID= is the Nextendo application the app signs in as (DMNextendoClientID in Info.plist) # PROGRAMS_TSV= (the NSP script, a multi-program application: Super Mario 3D All-Stars): one app holding several programs, one row each, "\t\t\t\t\t", # program 0's being GAME / PATCHED / ROMFS / MSL_IOS / GFXAPI (the app's name, version, icon and identity are its). Each program's modules go in sections tagged p (gen_embed.py --tag), # its tables and launcher settings in dm/p/, its RomFS and offline HTML pages in p/, its shader libraries in msl/p/, and the host is built over a table of their profiles @@ -119,11 +122,12 @@ if [ -n "${PROGRAMS_TSV:-}" ]; then # each program's modules under its tag (th done < <(prog_rows); prog_back else J=(); [ -f "$(dirname "$ROMFS")/jit/jit.img" ] && J=(--jit "$(dirname "$ROMFS")/jit/jit.img") F=$("${DM_PYTHON:-python3}" tools/gen_embed.py ${J[@]+"${J[@]}"} "$PATCHED" Gen/embed.S $MODS) || die "gen_embed"; fi -echo "OTHER_LDFLAGS = \$(inherited) \$(DM_FRAMEWORKS) $F" >> Gen/dm.xcconfig +echo "OTHER_LDFLAGS = \$(inherited) \$(DM_FRAMEWORKS) \$(DM_EXTRA_LIBRARIES) $F" >> Gen/dm.xcconfig # One program's tables into TD: the rewriter's, the shader tables and the launcher's settings program_tables() { cp "$PATCHED"/*.fixups.tsv "$PATCHED"/*.gates.tsv "$PATCHED"/*.cuts.tsv "$PATCHED"/*.obs.tsv $TD/ || die "copy rewriter tables" if [ -f "$PATCHED/nro.tsv" ]; then cp "$PATCHED/nro.tsv" $TD/ || die "copy the NRO table"; fi # the NRO modules the game loads with nn::ro (hle_ro.c), embedded by gen_embed.py +if [ -f "$PATCHED/nextendo/main.fixups.tsv" ]; then mkdir -p "$TD/nextendo" && cp "$PATCHED"/nextendo/*.tsv "$TD/nextendo/" || die "copy the tables of Nextendo's patched main"; fi # loader.c nextendo_main if [ "$GFXAPI" = vulkan ] || [ "$GFXAPI" = gl ]; then cp "$GD/shader_map.tsv" $TD/ || die "copy shader tables" # empty NVN table: the NVN layer draws nothing else cp "$GD/shader_map.tsv" "$GD/c1_full.tsv" $TD/ || die "copy shader tables" if [ -f "$GD/cb_extent.tsv" ]; then cp "$GD/cb_extent.tsv" $TD/ || die "copy cb_extent.tsv"; else t "no $GD/cb_extent.tsv: the host copies whole uniform bindings"; fi @@ -181,6 +185,8 @@ LD=$("${DM_PYTHON:-python3}" -c 'import json, sys; print(next((s["default"] for if [ -n "$LD" ] && [ "$LD" != "$DM_LANG" ]; then t "game language: the game has no $DM_LANG; packing $LD, its first"; export DM_LANG=$LD; fi # Diagnostic build: DM_ENV_FILE=file → dm/env.txt in the bundle (main.m sets one environment variable per line at boot) if [ -n "${DM_ENV_FILE:-}" ]; then cp "$DM_ENV_FILE" Gen/dm/env.txt || die "copy DM_ENV_FILE"; t "env: $(grep -v '^#' "$DM_ENV_FILE" | tr '\n' ' ')"; fi +# Online play on Nextendo (the NSP script's --nextendo): the public service profile, which main.m hands to the host as DM_NEXTENDO_ROUTES. No account data: the player signs in in the app +if [ -n "${DM_NEXTENDO_SERVICES:-}" ]; then mkdir -p Gen/dm/nextendo-services && cp "$DM_NEXTENDO_SERVICES"/routes.tsv "$DM_NEXTENDO_SERVICES"/manifest.json "$DM_NEXTENDO_SERVICES"/*.der Gen/dm/nextendo-services/ || die "copy the Nextendo service profile"; t "Nextendo: service profile from $DM_NEXTENDO_SERVICES"; fi # The shader libraries go into the archive as DmIOS.app/msl/, or an NVN game's as the file DmIOS.app/msl/.img (main.m sets DM_MSL_DIR to msl) if [ "$GFXAPI" = vulkan ]; then MSLDIR=vk; elif [ "$GFXAPI" = gl ]; then MSLDIR=gl; else MSLDIR=b-$V; fi # Shared-font stand-ins, one per type (make_shared_fonts.py, about 7 s: unhinted cuts of STD_FONT, by default macOS's Arial Unicode, which iOS lacks, and the button icons; needs fontTools, @@ -217,6 +223,11 @@ COMMIT=$(git -C "$DM" rev-parse --short=12 HEAD 2> /dev/null) && { [ -z "$(git - case "$MSLDIR" in b-*) /usr/libexec/PlistBuddy -c "Add :DMChain string ${MSLDIR#b-}" Gen/Info.plist > /dev/null || die "DMChain";; esac # DM_METAL_CAPTURE=1: a development build that may write GPU frame captures (MetalCaptureEnabled; the host's DM_GPU_CAPTURE switch writes them to Documents/gpu_captures) if [ "${DM_METAL_CAPTURE:-0}" = 1 ]; then /usr/libexec/PlistBuddy -c "Add :MetalCaptureEnabled bool true" Gen/Info.plist > /dev/null || die "MetalCaptureEnabled"; t "Metal frame capture: enabled (DM_METAL_CAPTURE=1)"; fi +# The Nextendo application the app signs in as (DMNextendoClientID, read by dm/host/nextendo_login_apple.inc); without one the app cannot sign in +if [ -n "${DM_NEXTENDO_SERVICES:-}" ]; then + if [ -n "${DM_NEXTENDO_CLIENT_ID:-}" ]; then /usr/libexec/PlistBuddy -c "Add :DMNextendoClientID string $DM_NEXTENDO_CLIENT_ID" Gen/Info.plist > /dev/null || die "DMNextendoClientID"; t "Nextendo: signs in as client $DM_NEXTENDO_CLIENT_ID" + else t "Nextendo: no DM_NEXTENDO_CLIENT_ID, so this app cannot sign in (register a public application at nextendo.network/developers)"; fi +fi RP=; if [ -n "${PROGRAMS_TSV:-}" ]; then # a game of several programs: each program's files, which the Xcode build phase copies under p as the IPA has them (stage_resources.sh) RP=Gen/resources_programs.tsv; printf '# program\tRomFS\tmarker\tiOS shaders\tshader folder (build_ipa.sh)\n' > "$RP" M0=$MSLDIR; while IFS= read -r row; do prog_set "$row"; printf '%s\t%s\t%s\t%s\t%s\n' "$PN" "$ROMFS" "$MARKER" "$(lib_path "$MSL_IOS/$MSLDIR")" "$MSLDIR" >> "$RP"; done < <(prog_rows); prog_back; MSLDIR=$M0; fi diff --git a/dm/ios/tools/build_smoke.py b/dm/ios/tools/build_smoke.py index aa5732a822..bb290cfbdf 100644 --- a/dm/ios/tools/build_smoke.py +++ b/dm/ios/tools/build_smoke.py @@ -63,7 +63,7 @@ def run(*command, capture=False): config = run(sys.executable, ios / 'tools/gen_build.py', REPO / 'dm/host', gen, capture=True).stdout flags = run(sys.executable, ios / 'tools/gen_embed.py', patched, gen / 'embed.S', *modules, capture=True).stdout.strip() - (gen / 'dm.xcconfig').write_text(config + f'OTHER_LDFLAGS = $(inherited) $(DM_FRAMEWORKS) {flags}\n') + (gen / 'dm.xcconfig').write_text(config + f'OTHER_LDFLAGS = $(inherited) $(DM_FRAMEWORKS) $(DM_EXTRA_LIBRARIES) {flags}\n') run('xcodegen', 'generate') # Exercise the real resource-copy phase with tiny, clearly synthetic data. diff --git a/dm/ios/tools/gen_build.py b/dm/ios/tools/gen_build.py index d6e38bf2b6..0029b106da 100644 --- a/dm/ios/tools/gen_build.py +++ b/dm/ios/tools/gen_build.py @@ -15,7 +15,7 @@ # gen/vpx and gen/dav1d): header paths keep this order, so the host's headers are found first lines = [shlex.split(l) for l in cmd.splitlines() if l.lstrip().startswith('clang')] lines.sort(key=lambda t: any(a.startswith(('gen/vpx/', 'gen/dav1d/')) for a in t)) -srcs, incs, defs, fws = [], [], [], [] +srcs, incs, defs, fws, libraries = [], [], [], [], [] for toks in lines: i = 0 while i < len(toks): @@ -25,6 +25,8 @@ d = os.path.normpath(os.path.join(host, t[2:])) if d not in incs: incs.append(d) elif t.startswith('-D'): defs.append(t) + elif t.endswith('/libcrypto.a'): + if t not in libraries: libraries.append(t) elif t.endswith(('.c', '.m', '.S')): srcs.append(os.path.normpath(os.path.join(host, t))) i += 1 assert srcs, 'no source files in the compile command' @@ -48,3 +50,5 @@ mac_only = [f for f in fws if not os.path.isdir(f'{sdk}/System/Library/Frameworks/{f}.framework')] if mac_only: print('gen_build: not in the iOS SDK, left out of the link: ' + ' '.join(mac_only), file=sys.stderr) print('DM_FRAMEWORKS = ' + ' '.join(f'-framework {f}' for f in fws if f not in mac_only)) + +print('DM_EXTRA_LIBRARIES = ' + ' '.join('"' + p + '"' for p in libraries)) diff --git a/dm/ios/tools/gen_embed.py b/dm/ios/tools/gen_embed.py index d9a45580d1..d13edc0697 100644 --- a/dm/ios/tools/gen_embed.py +++ b/dm/ios/tools/gen_embed.py @@ -23,11 +23,11 @@ out, dst, names = a[0], a[1], a[2:] PG = 0x4000 def r16(x): return (x + PG - 1) & ~(PG - 1) -def pieces(n): # the module's (x0, W, x1[, x2]) as (file start, end) - hdr = dict(l[2:].split() for l in open(f'{out}/{n}.fixups.tsv')) +def pieces(n, directory=out): # the module's (x0, W, x1[, x2]) as (file start, end) + hdr = dict(l[2:].split() for l in open(f'{directory}/{n}.fixups.tsv')) te, po = int(hdr['TEXT_END'], 16), int(hdr['PATCH_OFF'], 16) ko, ks = int(hdr['KEY_PAGE_OFF'], 16), int(hdr['KEY_PAGE_SIZE'], 16) - bin_ = os.path.abspath(f'{out}/{n}.patched.bin'); sz = os.path.getsize(bin_) + bin_ = os.path.abspath(f'{directory}/{n}.patched.bin'); sz = os.path.getsize(bin_) a, end = r16(te), r16(sz) if po < 0: # patch area before the base (patch_nso.py FAR): W ends at the end of data, the loader supplies zero pages for bss and the key page; in the file the patch area follows at FILE_IMAGE_LEN fl, bl = int(hdr['FILE_IMAGE_LEN'], 16), int(hdr.get('BACK_LEN', '0'), 16) @@ -48,6 +48,14 @@ def place(asm, bin_, sz, lo, hi): # one piece, 16K aligned at both ends (vm_re assert all(len(x) <= 16 for x in sect.split(',')) asm.append(f' .section {sect}'); place(asm, bin_, sz, lo, hi) flags.append(f'-Wl,-segprot,__DM{tag}{n}W,rw,rw') +if 'main' in names and os.path.isfile(os.path.join(out, 'nextendo/main.fixups.tsv')): + # Nextendo's patched main (scripts/build_ipa_from_nsp.py --nextendo, /nextendo) as module nmain, beside the original: iOS runs no code made at run time, + # so the copy the loader maps in Nextendo mode is in the executable too (loader.c nextendo_main, embed_name). After NX-Port-Studio (MIT) + bin_, sz, parts = pieces('main', os.path.join(out, 'nextendo')) + for sect, (lo, hi) in zip((f'__TEXT,__dm{tag}nmainx0', f'__DM{tag}nmainW,__img', f'__TEXT,__dm{tag}nmainx1', f'__TEXT,__dm{tag}nmainx2'), parts): + assert all(len(x) <= 16 for x in sect.split(',')) + asm.append(f' .section {sect}'); place(asm, bin_, sz, lo, hi) + flags.append(f'-Wl,-segprot,__DM{tag}nmainW,rw,rw') tab = os.path.join(out, 'nro.tsv') nros = [ln.split('\t')[0] for ln in open(tab) if ln.strip() and not ln.startswith('#') and not ln.startswith('refused\t')] if os.path.exists(tab) else [] if nros: diff --git a/dm/net/nextendo-pins/e6d779cb8b5e9c3a41909c6051bc8b3138707857f184e1c6b77688cb65c7a643.der b/dm/net/nextendo-pins/e6d779cb8b5e9c3a41909c6051bc8b3138707857f184e1c6b77688cb65c7a643.der new file mode 100644 index 0000000000..139bef3114 Binary files /dev/null and b/dm/net/nextendo-pins/e6d779cb8b5e9c3a41909c6051bc8b3138707857f184e1c6b77688cb65c7a643.der differ diff --git a/dm/net/nextendo-services.json b/dm/net/nextendo-services.json new file mode 100644 index 0000000000..7d171565cf --- /dev/null +++ b/dm/net/nextendo-services.json @@ -0,0 +1,193 @@ +{ + "formatVersion": 1, + "source": "https://git.nextendo.network/NextendoNetwork", + "provider": { + "server": "51.178.29.194", + "nat": "164.132.111.120", + "caURL": "https://git.nextendo.network/api/v1/repos/NextendoNetwork/Prelude-Nextendo/raw/romfs/sd/rootCA.pem?ref=482c182917228d69ebbbabfea44fffa4a44051be", + "caSHA256": "a654c0eff8aa20a72280ea0ef2b5c2a17392922dd78ffbb113862e1ad2c66d49" + }, + "base": [ + { + "match": "label", + "host": "nncs2-*.n.n.srv.nintendo.net", + "server": "nat", + "tls": false + }, + { + "match": "suffix", + "host": "nintendo.net", + "server": "server", + "tls": true + }, + { + "match": "suffix", + "host": "nintendo.com", + "server": "server", + "tls": true + }, + { + "match": "suffix", + "host": "nintendowifi.net", + "server": "server", + "tls": true + }, + { + "match": "suffix", + "host": "nintendo.co.jp", + "server": "server", + "tls": true + }, + { + "match": "exact", + "host": "nncs1-lp1.n.n.srv.nintendo.net", + "server": "server", + "tls": false + }, + { + "match": "pinned-exact", + "host": "g2b309e01-lp1.s.n.srv.nintendo.net", + "server": "nat", + "tls": true, + "certificateSHA256": "e6d779cb8b5e9c3a41909c6051bc8b3138707857f184e1c6b77688cb65c7a643" + }, + { + "match": "pinned-exact", + "host": "g2df33d01-lp1.p.srv.nintendo.net", + "server": "nat", + "tls": true, + "certificateSHA256": "e6d779cb8b5e9c3a41909c6051bc8b3138707857f184e1c6b77688cb65c7a643" + } + ], + "families": { + "demonware": [ + { + "match": "suffix", + "host": "demonware.net", + "server": "server", + "tls": true + } + ], + "ubisoft": [ + { + "match": "exact", + "host": "public-ubiservices.ubi.com", + "server": "server", + "tls": true + }, + { + "match": "exact", + "host": "public-ws-ubiservices.ubi.com", + "server": "server", + "tls": true + }, + { + "match": "exact", + "host": "jd.ubisoft.com", + "server": "server", + "tls": true + }, + { + "match": "exact", + "host": "phonescoring.jd.ubisoft.com", + "server": "server", + "tls": true + }, + { + "match": "exact", + "host": "v2.phonescoring.jd.ubisoft.com", + "server": "server", + "tls": true + } + ] + }, + "titles": { + "0100fcf002a58000": [ + { + "match": "exact", + "host": "api.braincloudservers.com", + "server": "server", + "tls": true + }, + { + "match": "exact", + "host": "na.ultimatechickenhorseserver.com", + "server": "server", + "tls": true + }, + { + "match": "exact", + "host": "eu.ultimatechickenhorseserver.com", + "server": "server", + "tls": true + }, + { + "match": "exact", + "host": "ap.ultimatechickenhorseserver.com", + "server": "server", + "tls": true + } + ], + "0100ab401f136000": [ + { + "match": "exact", + "host": "api.epicgames.dev", + "server": "server", + "tls": true + }, + { + "match": "exact", + "host": "switch-ggst-game.guiltygear.com", + "server": "server", + "tls": true + }, + { + "match": "exact", + "host": "prod-switch-match-ggst-game.guiltygear.com", + "server": "server", + "tls": true + }, + { + "match": "exact", + "host": "prod-to3match-ggst-game.guiltygear.com", + "server": "server", + "tls": true + } + ], + "0100b6e012ebe000": [ + { + "match": "exact", + "host": "public-ubiservices.ubi.com", + "server": "server", + "tls": true + } + ], + "010092a00c4b6000": [ + { + "match": "exact", + "host": "nswitch.f13.illfonic.com", + "server": "server", + "tls": true + } + ] + }, + "titleFamilies": { + "01001b300b9be000": "demonware", + "0100f9f00c696000": "demonware", + "0100ea6014bb8000": "ubisoft" + }, + "identities": { + "01006f8002326000": { + "account": "baas", + "friends": "baas" + }, + "0100c2500fc20000": { + "account": "pid", + "friends": "baas" + }, + "010015100b514000": { + "account": "pid", + "friends": "baas" + } + } +} diff --git a/dm/third_party/notices/OpenSSL/LICENSE.txt b/dm/third_party/notices/OpenSSL/LICENSE.txt new file mode 100644 index 0000000000..49cc83d2ee --- /dev/null +++ b/dm/third_party/notices/OpenSSL/LICENSE.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/dm/third_party/notices/OpenSSL/PROVENANCE.md b/dm/third_party/notices/OpenSSL/PROVENANCE.md new file mode 100644 index 0000000000..6f4e469a4e --- /dev/null +++ b/dm/third_party/notices/OpenSSL/PROVENANCE.md @@ -0,0 +1,3 @@ +# OpenSSL + +The Apple game host statically links libcrypto for strict verification of explicitly configured private service certificates. OpenSSL 4.1.0 is licensed under Apache-2.0; the unchanged [license text](LICENSE.txt) accompanies this source tree; redistributors of linked applications must preserve this notice and license. Source: https://github.com/openssl/openssl/releases/tag/openssl-4.1.0. The download SHA-256 is pinned in `dm/tools/apple_crypto.py`. No OpenSSL source or compiled library is vendored here. diff --git a/dm/tools/apple_crypto.py b/dm/tools/apple_crypto.py new file mode 100644 index 0000000000..4f8d176649 --- /dev/null +++ b/dm/tools/apple_crypto.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Prepare a static, scoped X.509 verifier dependency for Apple game hosts. + +The source archive is pinned by SHA-256. Nothing is installed system-wide, no +account state is read, and iOS archives never link a macOS Homebrew library. +Only the resulting prefix is printed; build output goes to a private log. +""" +import argparse +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import tarfile +import tempfile +import urllib.request + +VERSION = '4.1.0' +SOURCE = f'https://github.com/openssl/openssl/releases/download/openssl-{VERSION}/openssl-{VERSION}.tar.gz' +SHA256 = '50c17baf54cb008f6ce42d50deb4b28050a1aad711636cabd4b241c7e90cc2fd' +MAX_ARCHIVE = 100 * 2**20 + + +def digest(path): + h = hashlib.sha256() + with path.open('rb') as f: + for block in iter(lambda: f.read(2**20), b''): h.update(block) + return h.hexdigest() + + +def extract_source(archive, destination): + with tarfile.open(archive, 'r:gz') as tar: + members = tar.getmembers() + if len(members) > 30000 or sum(m.size for m in members) > 512 * 2**20: + raise ValueError('OpenSSL source archive exceeds its bounds') + for member in members: + parts = Path(member.name).parts + if not parts or parts[0] != f'openssl-{VERSION}' or member.name.startswith('/') or '..' in parts: + raise ValueError('Invalid OpenSSL source path') + if not member.isfile() and not member.isdir(): + raise ValueError('OpenSSL source contains an unsupported link or file') + # Manual regular-file extraction also works with Apple's older Python; + # no archive link, owner, special mode or absolute path is restored. + for member in members: + target = destination / member.name + if member.isdir(): target.mkdir(parents=True, exist_ok=True, mode=0o700) + else: + target.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + source = tar.extractfile(member) + if source is None: raise ValueError('OpenSSL regular file has no data') + with source, target.open('xb') as output: + shutil.copyfileobj(source, output, 2**20) + target.chmod(0o700 if member.mode & 0o111 else 0o600) + + +def run(command, **kwargs): + return subprocess.check_output(command, text=True, **kwargs).strip() + + +def prepare(platform, cache=None): + if platform not in ('macos', 'ios'): raise ValueError('Unsupported crypto platform') + # Build both platforms against their declared deployment targets. A local + # Homebrew archive may require this Mac's newer OS even when statically linked. + cache = Path(cache) if cache else Path.home() / 'Library/Application Support/nxnative/Toolchains/OpenSSL' + if cache.is_symlink(): raise ValueError('The crypto cache must not be a symbolic link') + cache.mkdir(parents=True, exist_ok=True, mode=0o700) + sdk = 'iphoneos' if platform == 'ios' else 'macosx' + sdk_path = run(['xcrun', '--sdk', sdk, '--show-sdk-path']) + minimum = '26.0' if platform == 'ios' else '14.0' + options = ['no-shared', 'no-tests', 'no-apps', 'no-module'] + identity = {'format': 2, 'source_sha256': SHA256, 'platform': platform, 'architecture':'arm64', + 'minimum_os':minimum, 'configure_options':options, + 'sdk': sdk_path, 'compiler': run(['xcrun', '--sdk', sdk, 'clang', '--version'])} + key = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()[:24] + target = cache / (platform + '-' + key) + with (cache / (platform + '.lock')).open('a') as lock: + os.chmod(lock.name, 0o600); fcntl.flock(lock, fcntl.LOCK_EX) + receipt = target / 'receipt.json' + if receipt.is_file() and not receipt.is_symlink(): + try: + record = json.loads(receipt.read_text()) + if record['identity'] == identity and digest(target / 'lib/libcrypto.a') == record['libcrypto_sha256'] and (target / 'include/openssl/x509.h').is_file(): return target + except (OSError, ValueError, KeyError): pass + archive = cache / f'openssl-{VERSION}.tar.gz' + if not archive.is_file() or archive.is_symlink() or digest(archive) != SHA256: + request = urllib.request.Request(SOURCE, headers={'User-Agent': 'NX-Port-Studio'}) + with tempfile.NamedTemporaryFile(dir=cache, prefix='.download-', delete=False) as out: + temporary = Path(out.name) + try: + with urllib.request.urlopen(request, timeout=30) as response: + size = 0 + for block in iter(lambda: response.read(2**20), b''): + size += len(block) + if size > MAX_ARCHIVE: raise ValueError('OpenSSL download exceeds its bounds') + out.write(block) + out.close() + if digest(temporary) != SHA256: raise ValueError('OpenSSL source integrity check failed') + temporary.replace(archive) + finally: temporary.unlink(missing_ok=True) + # OpenSSL's generated Makefile cannot represent a source path containing + # spaces. Build in the system temp directory, then publish to Support. + with tempfile.TemporaryDirectory(prefix='nx-crypto-' + platform + '-') as work: + work = Path(work); extract_source(archive, work) + source = work / f'openssl-{VERSION}'; output = work / 'prefix' + env = dict(os.environ, SDKROOT=sdk_path) + env['CFLAGS'] = ('-miphoneos-version-min=' if platform == 'ios' else '-mmacosx-version-min=') + minimum + configuration = 'ios64-xcrun' if platform == 'ios' else 'darwin64-arm64-cc' + log_path = cache / (platform + '-build.log') + with log_path.open('w') as log: + os.chmod(log_path, 0o600) + for command in ([str(source / 'Configure'), configuration, *options, '--prefix=' + str(output)], + ['make', '-j4', 'build_libs'], ['make', 'install_dev']): + subprocess.run(command, cwd=source, env=env, stdout=log, stderr=subprocess.STDOUT, check=True) + library = output / 'lib/libcrypto.a' + if not library.is_file(): raise ValueError('The static crypto library was not produced') + # A failed attempt never publishes a usable prefix. + (output / 'receipt.json').write_text(json.dumps({'identity': identity, 'libcrypto_sha256': digest(library)}, sort_keys=True)) + if target.exists(): shutil.rmtree(target) + output.rename(target) + return target + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('platform', choices=('macos', 'ios')) + parser.add_argument('--cache', type=Path) + options = parser.parse_args() + try: print(prepare(options.platform, options.cache)) + except (OSError, ValueError, tarfile.TarError, subprocess.CalledProcessError) as error: + raise SystemExit('Static crypto preparation failed; inspect the private toolchain build log: ' + str(error)) from None diff --git a/dm/tools/bcat_prepare.m b/dm/tools/bcat_prepare.m new file mode 100644 index 0000000000..5084353753 --- /dev/null +++ b/dm/tools/bcat_prepare.m @@ -0,0 +1,14 @@ +#import +#include "../host/nextendo_bcat.h" +#include +#include +int main(int argc, const char **argv) { @autoreleasepool { + if (argc == 3 && !strcmp(argv[1], "supported")) return dm_bcat_supported(argv[2]) ? 0 : 2; + if (argc == 5 && !strcmp(argv[1], "validate")) return dm_bcat_validate(argv[2],argv[3],argv[4]) ? 0 : 1; + if (argc != 5) { fprintf(stderr, "usage: bcat_prepare title version signed-catalog destination\n"); return 2; } + char error[256] = {0}; + if (!dm_bcat_prepare(argv[1], argv[2], argv[3], argv[4], error, sizeof error)) { + fprintf(stderr, "BCAT: %s\n", error); return 1; + } + puts("BCAT: verified calendar snapshot prepared (no account data)"); return 0; +} } diff --git a/dm/tools/friends_keyring/.gitignore b/dm/tools/friends_keyring/.gitignore new file mode 100644 index 0000000000..cd42ee34e8 --- /dev/null +++ b/dm/tools/friends_keyring/.gitignore @@ -0,0 +1,2 @@ +bin/ +obj/ diff --git a/dm/tools/friends_keyring/FriendsPlayHistoryResources.cs b/dm/tools/friends_keyring/FriendsPlayHistoryResources.cs new file mode 100644 index 0000000000..5c8e9cc260 --- /dev/null +++ b/dm/tools/friends_keyring/FriendsPlayHistoryResources.cs @@ -0,0 +1,160 @@ +// Locate the play-history signing resource in a privately supplied friends NSO. +// This original decoder contains no firmware bytes, signing material or fixed +// firmware offsets. The caller must first validate the source NCA's title and +// integrity. Unsupported or ambiguous code shapes fail closed. +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; + +internal static class FriendsPlayHistoryResources { + const int HeaderSize = 0x100; + const int MaximumInput = 64 * 1024 * 1024; + const int MaximumSegment = 64 * 1024 * 1024; + const int MaximumImage = 128 * 1024 * 1024; + readonly record struct Segment(int File, int Address, int Length, int Stored); + readonly record struct Candidate(int Table, int Hmac); + + static InvalidDataException Invalid() => new("The friends play-history resource could not be verified in this firmware."); + static uint Word(ReadOnlySpan data, int offset) => BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(offset, 4)); + static int Bounded(uint value, int limit) { if (value > limit) throw Invalid(); return (int)value; } + static bool Fits(int offset, int length, int total) => offset >= 0 && length >= 0 && offset <= total && length <= total - offset; + static bool Overlaps(int a, int n, int b, int m) => n != 0 && m != 0 && (long)a < (long)b + m && (long)b < (long)a + n; + + public static byte[] Extract(byte[] nso) { + if (nso == null || nso.Length < HeaderSize || nso.Length > MaximumInput || + Word(nso, 0) != 0x304f534e || Word(nso, 4) != 0) throw Invalid(); + uint flags = Word(nso, 12); + if ((flags & ~63u) != 0) throw Invalid(); + var segments = new Segment[3]; int imageSize = 0; + for (int i = 0; i < 3; i++) { + int at = 16 + i * 16; + var s = new Segment(Bounded(Word(nso, at), MaximumInput), Bounded(Word(nso, at + 4), MaximumImage), + Bounded(Word(nso, at + 8), MaximumSegment), Bounded(Word(nso, 96 + i * 4), MaximumInput)); + if (s.File < HeaderSize || !Fits(s.File, s.Stored, nso.Length) || !Fits(s.Address, s.Length, MaximumImage) || + (s.Address & 3) != 0 || ((flags & (1u << i)) == 0 && s.Stored != s.Length)) throw Invalid(); + foreach (var previous in segments.AsSpan(0, i)) + if (Overlaps(s.File, s.Stored, previous.File, previous.Stored) || + Overlaps(s.Address, s.Length, previous.Address, previous.Length)) throw Invalid(); + segments[i] = s; imageSize = Math.Max(imageSize, s.Address + s.Length); + } + int bss = Bounded(Word(nso, 60), MaximumSegment); + if (!Fits(segments[2].Address, segments[2].Length + (long)bss, MaximumImage) || + segments[0].Length < 4 || (segments[0].Length & 3) != 0 || segments[1].Length < 256) throw Invalid(); + byte[] image = new byte[imageSize]; + try { + Span digest = stackalloc byte[32]; + for (int i = 0; i < 3; i++) { + var s = segments[i]; var destination = image.AsSpan(s.Address, s.Length); + var source = nso.AsSpan(s.File, s.Stored); + if ((flags & (1u << i)) != 0) DecodeLz4(source, destination); else source.CopyTo(destination); + SHA256.HashData(destination, digest); + if (!CryptographicOperations.FixedTimeEquals(digest, nso.AsSpan(160 + i * 32, 32))) throw Invalid(); + } + return Find(image, segments[0], segments[1]); + } finally { CryptographicOperations.ZeroMemory(image); } + } + + static bool Fits(int offset, long length, int total) => length >= 0 && length <= int.MaxValue && Fits(offset, (int)length, total); + + // Raw LZ4 blocks as used by NSO segments. Bounds are checked before every + // literal/match; overlapping matches deliberately copy forward. + static void DecodeLz4(ReadOnlySpan source, Span output) { + int input = 0, written = 0; + while (input < source.Length) { + byte token = source[input++]; + int literals = Length(source, ref input, token >> 4, output.Length - written); + if (!Fits(input, literals, source.Length) || !Fits(written, literals, output.Length)) throw Invalid(); + source.Slice(input, literals).CopyTo(output.Slice(written)); input += literals; written += literals; + if (input == source.Length) { if (written != output.Length) throw Invalid(); return; } + if (!Fits(input, 2, source.Length)) throw Invalid(); + int distance = BinaryPrimitives.ReadUInt16LittleEndian(source.Slice(input, 2)); input += 2; + if (distance == 0 || distance > written || output.Length - written < 4) throw Invalid(); + int match = Length(source, ref input, token & 15, output.Length - written - 4) + 4; + for (int j = 0; j < match; j++) output[written + j] = output[written + j - distance]; + written += match; + } + if (written != output.Length) throw Invalid(); + } + static int Length(ReadOnlySpan source, ref int cursor, int initial, int maximum) { + int length = initial; + if (length > maximum) throw Invalid(); + if (initial == 15) { + byte extra; + do { + if (cursor == source.Length) throw Invalid(); extra = source[cursor++]; + if (extra > maximum - length) throw Invalid(); length += extra; + } while (extra == 255); + } + return length; + } + + static byte[] Find(byte[] image, Segment text, Segment ro) { + var groups = new Dictionary>(); + var publicConstants = new HashSet(); + int end = text.Address + text.Length; + for (int pc = text.Address; pc < end; pc += 4) { + uint instruction = Word(image, pc); + // The public SHA-256 IV halves and HMAC pad values corroborate the + // algorithm; these are not Nintendo signing keys. + if ((instruction & 0xff800000u) == 0xd2800000u || (instruction & 0xff800000u) == 0xf2800000u || + (instruction & 0xff800000u) == 0x52800000u || (instruction & 0xff800000u) == 0x72800000u) + publicConstants.Add((ushort)(instruction >> 5)); + if (!Adr(instruction, pc, out int table, out int register) || + table < ro.Address || !Fits(table - ro.Address, 256, ro.Length)) continue; + bool indexed = false; int argumentSizes = 0, hmac = -1; + for (int next = pc + 4; next < end && next <= pc + 18 * 4; next += 4) { + uint w = Word(image, next); + // ADD X4, table, index, LSL #5. + if ((w & 0xffe0fc1fu) == 0x8b001404u && ((w >> 5) & 31) == register) indexed = true; + if ((w & 0xffe00000u) == 0x52800000u && ((w >> 5) & 0xffff) == 32) { + int rd = (int)(w & 31); if (rd == 1) argumentSizes |= 1; if (rd == 3) argumentSizes |= 2; if (rd == 5) argumentSizes |= 4; + } + if ((w & 0xfc000000u) == 0x94000000u) { + int delta = (int)(w & 0x03ffffff); if ((delta & 0x02000000) != 0) delta -= 0x04000000; + long target = (long)next + (long)delta * 4; + if (target >= text.Address && target < end) hmac = (int)target; + break; + } + } + if (!indexed || argumentSizes != 7 || hmac < 0 || !IndexGuard(image, Math.Max(text.Address, pc - 24 * 4), pc)) continue; + var key = new Candidate(table, hmac); + if (!groups.TryGetValue(key, out var uses)) groups[key] = uses = new List(); + uses.Add(pc); + } + foreach (ushort constant in new ushort[] { 0x6a09, 0xbb67, 0x3c6e, 0xa54f, 0x510e, 0x9b05, 0x1f83, 0x5be0, 0x3636, 0x6a6a }) + if (!publicConstants.Contains(constant)) throw Invalid(); + Candidate? found = null; + foreach (var pair in groups) if (pair.Value.Count == 3) { + if (found != null) throw Invalid(); found = pair.Key; + } + if (found == null) throw Invalid(); + var material = image.AsSpan(found.Value.Table, 256); + for (int i = 0; i < 8; i++) { + var entry = material.Slice(i * 32, 32); bool nonzero = false; + foreach (byte value in entry) nonzero |= value != 0; + if (!nonzero) throw Invalid(); + for (int j = 0; j < i; j++) if (entry.SequenceEqual(material.Slice(j * 32, 32))) throw Invalid(); + } + return material.ToArray(); + } + static bool Adr(uint w, int pc, out int target, out int register) { + target = 0; register = (int)(w & 31); + if ((w & 0x9f000000u) != 0x10000000u) return false; + int relative = (int)(((w >> 5) & 0x7ffff) << 2 | ((w >> 29) & 3)); + if ((relative & 0x100000) != 0) relative -= 0x200000; + long address = (long)pc + relative; + if (address < 0 || address > int.MaxValue) return false; target = (int)address; return true; + } + static bool IndexGuard(byte[] image, int start, int end) { + for (int pc = start; pc < end; pc += 4) { + uint w = Word(image, pc); + // CMP Wn/Xn, #7 (SUBS immediate with destination zero register). + if ((w & 0x7ffffc1fu) == 0x71001c1fu) return true; + // AND Wd/Xd, Wn/Xn, #7: immr=0, imms=2; N is set for X. + if ((w & 0xfffffc00u) == 0x12000800u || (w & 0xfffffc00u) == 0x92400800u) return true; + } + return false; + } +} diff --git a/dm/tools/friends_keyring/Program.cs b/dm/tools/friends_keyring/Program.cs new file mode 100644 index 0000000000..985b12de35 --- /dev/null +++ b/dm/tools/friends_keyring/Program.cs @@ -0,0 +1,21 @@ +// Read only a privately supplied, decrypted friends NSO; publish no firmware or key bytes. +using System; +using System.IO; +using System.Security.Cryptography; +class Program { + static int Main(string[] args) { + if (args.Length != 2) { Console.Error.WriteLine("Usage: friends_keyring "); return 2; } + byte[] input = null, keys = null; + try { + var info = new FileInfo(args[0]); + if (!info.Exists || info.Length < 256 || info.Length > 64 * 1024 * 1024) throw new InvalidDataException(); + input = File.ReadAllBytes(args[0]); keys = FriendsPlayHistoryResources.Extract(input); + var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, Share = FileShare.None }; + if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + using (var output = new FileStream(args[1], options)) { output.Write(keys); output.Flush(true); } + Console.WriteLine("Verified local play-history resource written. Keep this file private."); return 0; + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is CryptographicException) { + Console.Error.WriteLine("Resource unavailable, unsupported or output already exists. No key values are logged."); return 1; + } finally { if (input != null) CryptographicOperations.ZeroMemory(input); if (keys != null) CryptographicOperations.ZeroMemory(keys); } + } +} diff --git a/dm/tools/friends_keyring/friends_keyring.csproj b/dm/tools/friends_keyring/friends_keyring.csproj new file mode 100644 index 0000000000..249992930f --- /dev/null +++ b/dm/tools/friends_keyring/friends_keyring.csproj @@ -0,0 +1 @@ +Exenet10.0 diff --git a/dm/tools/nextendo_bcat.py b/dm/tools/nextendo_bcat.py new file mode 100644 index 0000000000..b980b1a22b --- /dev/null +++ b/dm/tools/nextendo_bcat.py @@ -0,0 +1,114 @@ +"""Prepare and stage private public-calendar snapshots with the native verifier. + +I keep provider ZIPs, configuration files and extracted calendars outside Git. +The shared Mac/iOS backend verifies catalog signatures, paths, CRCs and formats. +""" +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import uuid +import warnings + +TITLES = {'0100f8f0000a2000', '01003bc0000a0000', '01003c700009c800'} + + +# The titles hle_bcat_apple.m supports and the one with no DebugUnderPilot files (Splatoon 2's regions): the host takes them from the build, not its source +TITLE_FLAGS = ('-DDM_BCAT_TITLES=@"0100f8f0000a2000",@"01003bc0000a0000",@"01003c700009c800"', '-DDM_BCAT_PLAIN_TITLE=@"01003c700009c800"') +def helper(repository): + repository = Path(repository) + override = os.environ.get('DM_OPENSSL_ROOT') + if not override: + raise ValueError('Set DM_OPENSSL_ROOT to the reviewed static OpenSSL prefix before preparing calendars') + root = Path(override) + sources = [repository / 'dm/tools/bcat_prepare.m', repository / 'dm/host/hle_bcat_apple.m', repository / 'dm/host/nextendo_bcat.h'] + compiler = subprocess.check_output(['xcrun', 'clang', '--version']) + identity = hashlib.sha256(b''.join(p.read_bytes() for p in sources) + compiler + os.fsencode(root)).hexdigest()[:24] + cache = Path.home() / 'Library/Application Support/nxnative/BCAT/tools' + if cache.is_symlink(): raise ValueError('Unsafe calendar tool cache') + cache.mkdir(parents=True, exist_ok=True, mode=0o700) + executable = cache / ('bcat-' + identity) + if not executable.is_file() or executable.is_symlink(): + with tempfile.TemporaryDirectory(dir=cache) as temporary: + output = Path(temporary) / 'bcat' + subprocess.run(['xcrun', 'clang', '-O1', '-fobjc-arc', '-Wall', '-Wextra', '-Wno-unused-parameter', '-DDM_OPENSSL_X509', *TITLE_FLAGS, + '-I' + str(root / 'include'), str(sources[0]), str(sources[1]), str(root / 'lib/libcrypto.a'), + '-lz', '-framework', 'Foundation', '-o', str(output)], check=True, capture_output=True) + output.chmod(0o700); output.replace(executable) + return executable + + +def private_directory(path): + path = Path(path).absolute() + current = Path(path.anchor) + for part in path.parts[1:]: + current /= part + if current.is_symlink() or (current.exists() and not current.is_dir()): raise ValueError('Unsafe calendar directory component') + current.mkdir(exist_ok=True, mode=0o700) + return path + + +def recipe(source, title_id, version): + """A recipe descriptor is not a successful or populated delivery cache.""" + if title_id.lower() not in TITLES or version != '5.5.2': raise ValueError('Unsupported calendar recipe version') + source = private_directory(source) + setup = {'formatVersion': 1, 'titleID': title_id.lower(), 'version': version} + temporary = source / ('.setup-' + uuid.uuid4().hex) + try: + with temporary.open('xb') as stream: stream.write((json.dumps(setup, sort_keys=True) + '\n').encode()) + temporary.chmod(0o600); temporary.replace(source / 'setup.json') + finally: temporary.unlink(missing_ok=True) + return source + + +def prepare(repository, title_id, version, catalog, destination): + """No recipe means no synthetic success: return None for unrelated games.""" + title_id = title_id.lower() + if title_id not in TITLES: return None + destination = recipe(Path(destination).absolute(), title_id, version) + result = subprocess.run([str(helper(repository)), title_id, version, str(catalog), str(destination)], capture_output=True, text=True) + if result.returncode: + retained = subprocess.run([str(helper(repository)), 'validate', title_id, version, str(destination)], capture_output=True) + if retained.returncode: raise ValueError(result.stderr.strip() or 'Calendar preparation failed') + warnings.warn('Calendar refresh failed; retaining the previous validated snapshot for this exact game/version', RuntimeWarning, stacklevel=2) + return destination + + +def stage(repository, source, destination, title_id, version=None, allow_missing=False): + """Copy only one complete, revalidated immutable snapshot, never loose files.""" + source, destination = Path(source).absolute(), Path(destination).absolute() + if source.is_symlink() or not source.is_dir() or destination.exists() or destination.is_symlink(): + raise ValueError('Unsafe calendar staging location') + setup_path = source / 'setup.json' + if setup_path.is_symlink() or not setup_path.is_file() or setup_path.stat().st_size > 4096: raise ValueError('Invalid calendar setup') + setup = json.loads(setup_path.read_bytes()) + if type(setup.get('formatVersion')) is not int or setup['formatVersion'] != 1 or setup.get('titleID') != title_id.lower() or setup.get('version') != (version or setup.get('version')): + raise ValueError('Calendar belongs to another game/version') + version = setup['version'] + if title_id.lower() not in TITLES or version != '5.5.2': raise ValueError('Unsupported calendar recipe') + validated = subprocess.run([str(helper(repository)), 'validate', title_id.lower(), version, str(source)], capture_output=True).returncode == 0 + if not validated and not allow_missing: raise ValueError('No complete validated calendar snapshot') + pointer: str | None = None + if validated: + candidate = json.loads((source / 'current.json').read_bytes())['snapshot'] + if not isinstance(candidate, str) or not re.fullmatch('[a-f0-9]{64}', candidate): raise ValueError('Invalid calendar pointer') + pointer = candidate + private_directory(destination.parent) + with tempfile.TemporaryDirectory(prefix='.bcat-stage-', dir=destination.parent) as temporary: + temporary = Path(temporary) / 'data'; temporary.mkdir() + shutil.copyfile(source / 'setup.json', temporary / 'setup.json') + if pointer is not None: + (temporary / 'snapshots').mkdir() + # The verifier rejects symlinks and unexpected files in this snapshot. + shutil.copytree(source / 'snapshots' / pointer, temporary / 'snapshots' / pointer, symlinks=True) + shutil.copyfile(source / 'current.json', temporary / 'current.json') + subprocess.run([str(helper(repository)), 'validate', title_id.lower(), version, str(temporary)], check=True, capture_output=True) + # A recipe-only seed is explicitly incomplete. The runtime cannot mount + # it, but can retry the authenticated public download after startup. + + temporary.replace(destination) + return destination diff --git a/dm/tools/nextendo_login.m b/dm/tools/nextendo_login.m new file mode 100644 index 0000000000..a2b8e4e907 --- /dev/null +++ b/dm/tools/nextendo_login.m @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: MIT +// nextendo_login: the Mac's Nextendo sign-in for nxnative's online play (dm/host/nextendo_login_apple.inc). +// nextendo_login sign-in shows Nextendo's sign-in page in the browser and saves the sign-in on this Mac +// nextendo_login status fetches a game token as a game would and names the account +// nextendo_login sign-out deletes the saved sign-in +// DM_NEXTENDO_CLIENT_ID names the Nextendo application it signs in as (nextendo_login_apple.inc). +// Build: make -C dm/host nextendo_login. It prints the account's name and PID, never a token. The iPhone app signs in on its +// settings screen instead (dm/ios/Sources/NextendoSignIn.m). +#import +#import "../host/nextendo_login_apple.inc" +#include + +static int print_result(NSDictionary *record, NSString *why) { + if (!record) { fprintf(stderr, "nextendo_login: %s\n", why.UTF8String); return 1; } + NSDate *expiry = [NSDate dateWithTimeIntervalSince1970:[record[@"expires_at"] doubleValue]]; + NSString *when = [NSDateFormatter localizedStringFromDate:expiry dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle]; + printf("Signed in to Nextendo as %s (PID %s). A game token is available, valid until %s.\n", + [record[@"identity"][@"username"] UTF8String], [[record[@"identity"][@"pid"] stringValue] UTF8String], when.UTF8String); + return 0; +} + +static int sign_in(void) { + if (!nxl_client_id()) { fprintf(stderr, "nextendo_login: %s\n", kNxNoClient.UTF8String); return 1; } + NSString *verifier = nxl_random_urlsafe(32), *state = nxl_random_urlsafe(16); + if (!verifier || !state) { fputs("nextendo_login: no random bytes\n", stderr); return 1; } + uint16_t port = 0; + int listener = nxl_listen_loopback(&port); + if (listener < 0) { perror("nextendo_login: loopback listener"); return 1; } + NSString *redirect = [NSString stringWithFormat:@"http://127.0.0.1:%u/callback", port]; + NSURL *page = nxl_authorize_url(redirect, state, verifier); + printf("Opening Nextendo's sign-in page in your browser (waiting up to 5 minutes). If it does not open, go to:\n%s\n", page.absoluteString.UTF8String); + [NSWorkspace.sharedWorkspace openURL:page]; + NSDictionary *query = nxl_wait_callback(listener, state, 300, NULL); + close(listener); + if (!query) return print_result(nil, @"no answer from the sign-in page in 5 minutes"); + NSString *why = nil; + NSDictionary *record = nxl_finish_sign_in(query, verifier, redirect, &why); + return print_result(record, why); +} + +int main(int argc, char **argv) { @autoreleasepool { + const char *command = argc == 2 ? argv[1] : ""; + if (!strcmp(command, "sign-in")) return sign_in(); + if (!strcmp(command, "status")) { NSString *why = nil; NSDictionary *record = nxl_game_record(&why); return print_result(record, why); } + if (!strcmp(command, "sign-out")) { + if (!nxl_write_refresh(nil)) { perror("nextendo_login: sign-out"); return 1; } + puts("Signed out of Nextendo on this Mac."); + return 0; + } + fputs("usage: nextendo_login sign-in | status | sign-out\n", stderr); + return 2; +} } diff --git a/dm/tools/nextendo_patches.py b/dm/tools/nextendo_patches.py new file mode 100644 index 0000000000..b4b5e39288 --- /dev/null +++ b/dm/tools/nextendo_patches.py @@ -0,0 +1,204 @@ +"""From RobiiAragon/NX-Port-Studio dm/tools/nextendo_patches.py @ bd13a49b (MIT). + +Signed IPS32 adapter for private, mode-specific native builds. + +Provider patches are downloaded as data, never imported as executable scripts. +Exact 32-byte NSO build identity, complete guards and bounds are mandatory. +The original input and the offline/LAN rewrite are never modified. +""" +import base64 +import hashlib +import json +from pathlib import Path +import struct +import subprocess +import tempfile +import urllib.request + +import nso + +ENDPOINT = 'https://nextendo.network/service-catalog/v1/npln-patches' +MAX_DOCUMENT = 2 * 2**20 +MAX_IMAGE = 512 * 2**20 + + +def strict_json(data): + def unique(pairs): + output = {} + for key, value in pairs: + if key in output: raise ValueError('Duplicate signed document field') + output[key] = value + return output + return json.loads(data, object_pairs_hook=unique, parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Invalid JSON number'))) + + +def verified_catalog(repository, cache, games=False): + cache = Path(cache) + if cache.is_symlink(): raise ValueError('Unsafe patch cache') + cache.mkdir(parents=True, exist_ok=True, mode=0o700) + source = Path(repository) / 'dm/tools/nextendo_verify.swift' + compiler = subprocess.check_output(['xcrun', 'swiftc', '--version']) + key = hashlib.sha256(source.read_bytes() + compiler).hexdigest()[:24] + verifier = cache / ('verify-' + key) + if not verifier.is_file() or verifier.is_symlink(): + with tempfile.TemporaryDirectory(dir=cache) as work: + binary = Path(work) / 'verifier' + subprocess.run(['xcrun', 'swiftc', '-parse-as-library', str(source), '-o', str(binary)], check=True, capture_output=True) + binary.replace(verifier) + envelope = cache / ('game-catalog.json' if games else 'npln-patches.json') + minimum = cache / ('game-highest-revision.json' if games else 'highest-revision.json') + arguments = ['games'] if games else [] + validate = validate_games if games else validate_catalog + with tempfile.TemporaryDirectory(dir=cache) as work: + work = Path(work); payload = work / 'payload.json' + # Verify the cached signature and expiry again, even when offline. + if envelope.is_file() and not envelope.is_symlink() and envelope.stat().st_size <= MAX_DOCUMENT: + result = subprocess.run([str(verifier), str(envelope), str(payload), *arguments], capture_output=True) + if result.returncode == 0: + value = validate(strict_json(payload.read_bytes())) + if minimum.is_file() and value['revision'] < strict_json(minimum.read_bytes())['revision']: + raise ValueError('Signed patch catalog rollback') + return value + endpoint = 'https://nextendo.network/service-catalog/v1/game-catalog' if games else ENDPOINT + request = urllib.request.Request(endpoint, headers={'User-Agent': 'nxnative'}) + with urllib.request.urlopen(request, timeout=20) as response: data = response.read(MAX_DOCUMENT + 1) + if len(data) > MAX_DOCUMENT: raise ValueError('Signed patch document is too large') + strict_json(data) + incoming = work / 'incoming.json'; incoming.write_bytes(data) + subprocess.run([str(verifier), str(incoming), str(payload), *arguments], check=True, capture_output=True) + value = strict_json(payload.read_bytes()) + if minimum.is_file() and value['revision'] < strict_json(minimum.read_bytes())['revision']: + raise ValueError('Signed patch catalog rollback') + value = validate(value) + incoming.chmod(0o600); incoming.replace(envelope) + revision = work / 'revision.json'; revision.write_text(json.dumps({'revision': value['revision']})); revision.chmod(0o600); revision.replace(minimum) + return value + + +def validate_games(document): + import re + rows = document.get('games') + if type(document.get('revision')) is not int or not isinstance(rows,list) or len(rows)>10000: + raise ValueError('Invalid signed game catalog') + seen=set() + for row in rows: + ids=row.get('title_ids') + if not isinstance(ids,list) or not 1<=len(ids)<=32 or type(row.get('enabled')) is not bool: + raise ValueError('Invalid signed game policy') + protocol=row.get('protocol') + if protocol is not None and (not isinstance(protocol,str) or not re.fullmatch('[a-z0-9._-]{1,64}',protocol)): + raise ValueError('Invalid signed service family') + for title in ids: + if not isinstance(title,str) or not re.fullmatch('[a-fA-F0-9]{16}',title) or not int(title,16) or title.lower() in seen: + raise ValueError('Invalid signed regional identity') + seen.add(title.lower()) + return document + + +def supported(patch): + # The one patch format this adapter applies. Nextendo adds others for other games (revision 10 brought a Splatoon 3 patch with + # patch_version 2): validate_catalog leaves those alone, and apply_image refuses a build whose own patch is one of them + return patch.get('module') == 'main' and patch.get('patch_version') == 1 and patch.get('offset_basis') == 'nso_header_included' and patch.get('required_capabilities') == ['npln.ips32.v1'] + + +def validate_catalog(document): + patches = document.get('patches') + if type(document.get('revision')) is not int or not isinstance(patches, list) or len(patches) > 4096: + raise ValueError('Unsupported signed patch catalog') + identities = set() + for patch in patches: + title, build = patch.get('title_id', ''), patch.get('build_id', '') + if len(title) != 16 or len(build) != 64: + raise ValueError('Invalid patch identity') + try: bytes.fromhex(title); bytes.fromhex(build) + except ValueError: raise ValueError('Invalid patch identity') from None + identity = (title.lower(), build.lower(), patch.get('id')) + if identity in identities: raise ValueError('Duplicate signed patch identity') + identities.add(identity) + if type(patch.get('enabled')) is not bool: raise ValueError('Unsupported signed patch policy') + if supported(patch): records(patch) + return document + + +def records(patch): + encoded = patch.get('ips32_base64', '') + data = base64.b64decode(encoded, validate=True) + if len(data) > MAX_DOCUMENT or hashlib.sha256(data).hexdigest() != patch.get('sha256') or not data.startswith(b'IPS32'): + raise ValueError('Invalid signed IPS32 integrity') + offset, output, covered = 5, [], set() + while offset + 4 <= len(data) and data[offset:offset + 4] != b'EEOF': + if offset + 6 > len(data): raise ValueError('Truncated IPS32 record') + start, length = struct.unpack_from('>IH', data, offset); offset += 6 + if not length: + if offset + 3 > len(data): raise ValueError('Truncated IPS32 run') + length = struct.unpack_from('>H', data, offset)[0]; value = data[offset + 2:offset + 3] * length; offset += 3 + else: + if offset + length > len(data): raise ValueError('Truncated IPS32 bytes') + value = data[offset:offset + length]; offset += length + if not length or start < 0x100 or start + length > MAX_IMAGE + 0x100 or len(output) >= 4096: + raise ValueError('IPS32 bounds exceeded') + positions = set(range(start, start + length)) + if covered & positions: raise ValueError('Overlapping IPS32 records') + covered |= positions; output.append((start - 0x100, value)) + if data[offset:] != b'EEOF' or not output: raise ValueError('Invalid IPS32 termination') + guards = patch.get('guards') + if not isinstance(guards, list) or not 0 < len(guards) <= 4096: raise ValueError('Missing IPS32 preimage guards') + originals, replacements = {}, {} + for guard in guards: + start = guard.get('offset'); original = bytes.fromhex(guard.get('original_hex', '')); changed = bytes.fromhex(guard.get('patched_hex', '')) + if type(start) is not int or start < 0x100 or not original or len(original) != len(changed) or len(original) > 65536: + raise ValueError('Invalid IPS32 guard') + for i, (a, b) in enumerate(zip(original, changed)): + if start + i in originals: raise ValueError('Overlapping IPS32 guards') + originals[start + i] = a; replacements[start + i] = b + expected = {start + 0x100 + i: byte for start, value in output for i, byte in enumerate(value)} + if replacements != expected: raise ValueError('IPS32 bytes are not completely guarded') + return output, originals + + +def apply_image(image, title_id, build_id, document): + validate_catalog(document) + matches = [p for p in document['patches'] if p['enabled'] and p['title_id'].lower() == title_id.lower() and p['build_id'].lower() == build_id.lower()] + if not matches: return None, [] + if not all(supported(p) for p in matches): raise ValueError('Unsupported signed patch policy for this game build') + if len(image) > MAX_IMAGE: raise ValueError('NSO image exceeds patch bounds') + changed = bytearray(image); all_positions = set() + for patch in matches: + edits, guards = records(patch) + for position, original in guards.items(): + position -= 0x100 + if position >= len(image) or image[position] != original: raise ValueError('Nextendo patch preimage differs from the exact game build') + if position in all_positions: raise ValueError('Conflicting signed game patches') + all_positions.add(position) + for start, value in edits: + if start + len(value) > len(image): raise ValueError('Signed patch exceeds this NSO image') + changed[start:start + len(value)] = value + return changed, [p['id'] for p in matches] + + +def prepare_nso(source, destination, title_id, document): + data = Path(source).read_bytes() + if len(data) < 0x100 or len(data) > MAX_IMAGE or data[:4] != b'NSO0': raise ValueError('Expected a bounded NSO module') + flags = struct.unpack_from(' MAX_IMAGE: raise ValueError('NSO virtual layout exceeds patch bounds') + module = nso.load(data, str(source)) + changed, applied = apply_image(module.image, title_id, module.build_id.hex(), document) + if changed is None: return [] + for patch in document['patches']: + if patch.get('id') in applied: + for offset in records(patch)[1]: + position = offset - 0x100 + if not any(mo <= position < mo + size for mo, size in module.segments): + raise ValueError('A signed patch targets an unmapped NSO gap') + header = bytearray(data[:0x100]); struct.pack_into('.der, from dm/net/nextendo-pins) and manifest.json into a folder. + +Only public service facts, the provider's authenticated public CA and certificates Nextendo's servers present to any client are used. +No Nintendo files, account tokens, game patches or system trust changes. +""" +from pathlib import Path +import base64 +import hashlib +import ipaddress +import json +import re +import urllib.request + + +def contract(repository): + value = json.loads((Path(repository) / 'dm/net/nextendo-services.json').read_text()) + if value.get('formatVersion') != 1: raise ValueError('Unsupported Nextendo service contract') + for name in ('server', 'nat'): + address = ipaddress.IPv4Address(value['provider'][name]) + if address.is_unspecified or address.is_multicast or address.is_loopback: raise ValueError('Invalid public Nextendo service address') + if not re.fullmatch('[0-9a-f]{64}', value['provider']['caSHA256']): raise ValueError('Invalid provider CA digest') + return value + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def provider_ca(value): + cache = Path.home() / 'Library/Application Support/nxnative/nextendo/public-provider-ca.der' + if cache.is_file() and not cache.is_symlink() and cache.stat().st_size <= 65536: + data = cache.read_bytes() + if hashlib.sha256(data).hexdigest() == value['provider']['caSHA256']: return data + url = value['provider']['caURL'] + # The web UI's raw link can return 403; the API serves the same file at the pinned revision. The SHA-256 below is the trust, not the host. + if not re.fullmatch(r'https://git\.nextendo\.network/api/v1/repos/NextendoNetwork/Prelude-Nextendo/raw/' + r'romfs/sd/rootCA\.pem\?ref=[0-9a-f]{40}', url): + raise ValueError('The provider CA must come from its official source') + request = urllib.request.Request(url, headers={'User-Agent': 'nxnative'}) + with urllib.request.build_opener(_NoRedirect).open(request, timeout=15) as response: encoded = response.read(65537) + if len(encoded) > 65536: raise ValueError('Provider CA exceeds its bounds') + match = re.fullmatch(rb'\s*-----BEGIN CERTIFICATE-----\s*([A-Za-z0-9+/=\r\n]+)\s*-----END CERTIFICATE-----\s*', encoded) + if not match: raise ValueError('Expected exactly one public provider certificate') + der = base64.b64decode(re.sub(rb'\s', b'', match[1]), validate=True) + if hashlib.sha256(der).hexdigest() != value['provider']['caSHA256']: + raise ValueError('The public provider CA integrity check failed') + cache.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + if not cache.is_symlink(): + import tempfile + with tempfile.NamedTemporaryFile(dir=cache.parent, prefix='.ca-', delete=False) as out: + temporary = Path(out.name) + try: out.write(der); out.close(); temporary.chmod(0o600); temporary.replace(cache) + finally: temporary.unlink(missing_ok=True) + return der + + +PINS = 'dm/net/nextendo-pins' # .der: a server certificate a pinned-exact route accepts, byte for byte (hle_nextendo_x509.c dm_nextendo_x509_verify_pin) + + +def rules(value, title_id, protocol=None): + """routes.tsv. A pinned-exact route is for a TLS service whose certificate no CA signs (Nextendo's NEX server for Mario Kart 8 Deluxe + serves a self-signed one with no host name): it accepts exactly the certificate named by certificateSHA256, from PINS. Its address + also gets a pinned-address route with the same certificate, as a NEX secure server can be handed to the game by address""" + title_id = title_id.lower() + if not re.fullmatch('[0-9a-f]{16}', title_id) or int(title_id, 16) == 0: raise ValueError('Invalid game title identity') + families = value.get('titleFamilies', {}) + family = protocol or families.get(title_id, 'nex') + items = list(value['base']) + value.get('families', {}).get(family, []) + value.get('titles', {}).get(title_id, []) + seen, output, aliases = set(), [], {} + for item in items: + kind, host = item['match'], item['host'].lower() + if kind not in ('exact', 'suffix', 'label', 'pinned-exact') or len(host) > 253: + raise ValueError('Invalid service route pattern') + pin = item.get('certificateSHA256') + if (kind == 'pinned-exact') != (pin is not None) or (pin is not None and (not item['tls'] or not re.fullmatch('[0-9a-f]{64}', pin))): + raise ValueError('A pinned route needs TLS and exactly one certificate digest') + pattern = host.replace('*', 'x') + if not re.fullmatch(r'[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?', pattern) or '..' in pattern: + raise ValueError('Invalid service route hostname') + if (kind == 'label' and host.count('*') != 1) or (kind != 'label' and '*' in host): + raise ValueError('Invalid service label wildcard') + if (kind, host) in seen: continue + seen.add((kind, host)) + address = value['provider'][item['server']] + if pin: # the routes loader takes a pin only for its own host name + output.append('\t'.join([kind, host, address, host, pin + '.der', pin])) + if aliases.setdefault(address, (host, pin))[1] != pin: raise ValueError('One address with two pinned certificates') + continue + tail = ['@host', 'provider-ca.der', value['provider']['caSHA256']] if item['tls'] else ['-', '-', '-'] + output.append('\t'.join([kind, host, address] + tail)) + for address, (host, pin) in aliases.items(): output.append('\t'.join(['pinned-address', address, address, host, pin + '.der', pin])) + if not 0 < len(output) <= 128: raise ValueError('Invalid service route count') + return 'NXNEXTENDO_ROUTES_2\n' + '\n'.join(output) + '\n' + + +def prepare(repository, title_id, destination, protocol=None, ca=None): + value = contract(repository); ca = provider_ca(value) if ca is None else ca + if hashlib.sha256(ca).hexdigest() != value['provider']['caSHA256']: raise ValueError('Invalid provider CA') + text = rules(value, title_id, protocol) + files = {'routes.tsv': text.encode(), 'provider-ca.der': ca} + for line in text.splitlines()[1:]: + fields = line.split('\t') + if fields[0] != 'pinned-exact': continue + data = (Path(repository) / PINS / fields[4]).read_bytes() + if hashlib.sha256(data).hexdigest() != fields[5]: raise ValueError('A pinned server certificate does not match its digest') + files[fields[4]] = data + manifest = {'formatVersion': 1, 'titleID': title_id.lower(), 'protocol': protocol, + 'identity': value.get('identities', {}).get(title_id.lower(), {'account':'pid','friends':'pid'}), + 'routeCount': len(text.splitlines()) - 1, + 'files': {name: hashlib.sha256(data).hexdigest() for name, data in files.items()}} + files['manifest.json'] = (json.dumps(manifest, sort_keys=True) + '\n').encode() + destination = Path(destination) + if destination.is_symlink(): raise ValueError('The service profile must not be a symbolic link') + destination.mkdir(parents=True, exist_ok=True, mode=0o700) + for name, data in files.items(): + path = destination / name + if path.is_symlink(): raise ValueError('A service profile file must not be a symbolic link') + temporary = destination / ('.' + name + '.partial') + if temporary.exists() or temporary.is_symlink(): raise ValueError('A service profile preparation is already in progress') + try: + with temporary.open('xb') as output: output.write(data) + temporary.chmod(0o600); temporary.replace(path) + finally: temporary.unlink(missing_ok=True) + return destination + + +if __name__ == '__main__': + import argparse + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('repository', type=Path); parser.add_argument('title_id'); parser.add_argument('destination', type=Path) + parser.add_argument('--protocol') + args = parser.parse_args() + try: print(prepare(args.repository, args.title_id, args.destination, args.protocol)) + except (OSError, ValueError) as error: raise SystemExit('Nextendo services could not be prepared: ' + str(error)) from None diff --git a/dm/tools/nextendo_verify.swift b/dm/tools/nextendo_verify.swift new file mode 100644 index 0000000000..ca04fd234a --- /dev/null +++ b/dm/tools/nextendo_verify.swift @@ -0,0 +1,39 @@ +// From RobiiAragon/NX-Port-Studio dm/tools/nextendo_verify.swift @ bd13a49b (MIT). Build: xcrun swiftc -parse-as-library nextendo_verify.swift (dm/tools/nextendo_patches.py does) +// Original offline signature boundary for public provider build documents. +import Foundation +import CryptoKit + +@main struct VerifyNextendoDocument { + static func main() { + do { + guard (3...4).contains(CommandLine.arguments.count) else { throw Failure.invalid } + let games = CommandLine.arguments.count == 4 && CommandLine.arguments[3] == "games" + if CommandLine.arguments.count == 4 && !games { throw Failure.invalid } + let input = URL(fileURLWithPath: CommandLine.arguments[1]) + guard let size = try input.resourceValues(forKeys: [.fileSizeKey]).fileSize, (1...2_097_152).contains(size) + else { throw Failure.invalid } + let envelope = try Data(contentsOf: input) + guard let outer = try JSONSerialization.jsonObject(with: envelope) as? [String: Any], + outer["key_id"] as? String == (games ? "catalog-key-1" : "npln-patches-key-1"), + let encoded = outer["payload"] as? String, let payload = Data(base64Encoded: encoded), payload.base64EncodedString() == encoded, + let signature = outer["signature"] as? String, let bytes = Data(base64Encoded: signature), bytes.count == 64, + bytes.base64EncodedString() == signature else { throw Failure.invalid } + let key = try Curve25519.Signing.PublicKey(rawRepresentation: Data(base64Encoded: games ? "xI+atR6VesrCH89ZDZD4t3WQLcYOFEhk5F0HLMzgWk4=" : "LAI+Pi+GZtj3p4DpNM5ORBraw1cbZCVSMFgUmAVWNeA=")!) + guard key.isValidSignature(bytes, for: payload) else { throw Failure.invalid } + guard let object = try JSONSerialization.jsonObject(with: payload) as? [String: Any], + object["document_type"] as? String == (games ? "game_catalog" : "npln_patch_catalog"), + let schema = object["schema_version"] as? NSNumber, CFGetTypeID(schema) != CFBooleanGetTypeID(), schema == 1, + let revision = object["revision"] as? NSNumber, CFGetTypeID(revision) != CFBooleanGetTypeID(), Int64(revision.stringValue).map({ $0 > 0 }) == true, + let issued = date(object["issued_at"]), let expires = date(object["expires_at"]), + issued <= Date().addingTimeInterval(300), expires > Date(), expires > issued, + expires.timeIntervalSince(issued) <= 86_400 else { throw Failure.invalid } + try payload.write(to: URL(fileURLWithPath: CommandLine.arguments[2]), options: .atomic) + } catch { fputs("Nextendo's signed patch document could not be verified.\n", stderr); exit(1) } + } + enum Failure: Error { case invalid } + static func date(_ value: Any?) -> Date? { + guard let text = value as? String, text.count <= 40, text.hasSuffix("Z") else { return nil } + let parser = ISO8601DateFormatter(); parser.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return parser.date(from: text) + } +} diff --git a/dm/tools/tests/friends_firmware_fixture/.gitignore b/dm/tools/tests/friends_firmware_fixture/.gitignore new file mode 100644 index 0000000000..cd42ee34e8 --- /dev/null +++ b/dm/tools/tests/friends_firmware_fixture/.gitignore @@ -0,0 +1,2 @@ +bin/ +obj/ diff --git a/dm/tools/tests/friends_firmware_fixture/FriendsFirmwareTests.csproj b/dm/tools/tests/friends_firmware_fixture/FriendsFirmwareTests.csproj new file mode 100644 index 0000000000..09c2c0905d --- /dev/null +++ b/dm/tools/tests/friends_firmware_fixture/FriendsFirmwareTests.csproj @@ -0,0 +1,12 @@ + + + Exe + net10.0 + false + true + + + + + + diff --git a/dm/tools/tests/friends_firmware_fixture/Program.cs b/dm/tools/tests/friends_firmware_fixture/Program.cs new file mode 100644 index 0000000000..0a1baa37e5 --- /dev/null +++ b/dm/tools/tests/friends_firmware_fixture/Program.cs @@ -0,0 +1,111 @@ +// Entirely synthetic NSO / ARM64 / LZ4 fixtures. No firmware, Nintendo code, +// identities or signing material is stored in this test project. +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; + +static class Program { + static int checks; + static void Check(bool value, string label) { checks++; if (!value) throw new Exception(label); } + static void Reject(byte[] input, string label) { + try { FriendsPlayHistoryResources.Extract(input); } + catch (InvalidDataException error) { Check(!error.Message.Contains("0x"), label + " has a metadata-only error"); return; } + throw new Exception("Accepted invalid fixture: " + label); + } + static void Put(byte[] b, int offset, uint value) => BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(offset, 4), value); + static uint Get(byte[] b, int offset) => BinaryPrimitives.ReadUInt32LittleEndian(b.AsSpan(offset, 4)); + static byte[] FixtureMaterial(int seed = 0) { + var value = new byte[256]; + for (int i = 0; i < value.Length; i++) value[i] = (byte)(1 + (i + i / 32 * 17 + seed) % 251); + return value; + } + static void Reference(byte[] text, int pc, int table, int hmac = 0x800, bool guard = true) { + // Public ARM64 encodings for a non-executable metadata fixture. + Put(text, pc - 4, guard ? 0xf1001d1fu : 0xd503201fu); // CMP X8,#7 or NOP + uint relative = (uint)(table - pc) & 0x1fffff; + Put(text, pc, 0x10000009u | ((relative & 3) << 29) | ((relative >> 2) << 5)); // ADR X9,table + Put(text, pc + 4, 0x8b000004u | (8u << 16) | (5u << 10) | (9u << 5)); // ADD X4,X9,X8,LSL#5 + Put(text, pc + 8, 0x52800001u | (32u << 5)); + Put(text, pc + 12, 0x52800003u | (32u << 5)); + Put(text, pc + 16, 0x52800005u | (32u << 5)); + Put(text, pc + 20, 0x94000000u | ((uint)((hmac - pc - 20) / 4) & 0x03ffffffu)); + } + static (byte[] Text, byte[] Ro, byte[] Data) Segments(bool ambiguous = false) { + byte[] text = new byte[0x1000], ro = new byte[0x400], data = new byte[32]; + Array.Fill(data, (byte)65); + for (int i = 0; i < 3; i++) Reference(text, 0x100 + i * 0x40, 0x2080); + if (ambiguous) for (int i = 0; i < 3; i++) Reference(text, 0x300 + i * 0x40, 0x2180); + int at = 0x900; + foreach (ushort value in new ushort[] { 0x6a09, 0xbb67, 0x3c6e, 0xa54f, 0x510e, 0x9b05, 0x1f83, 0x5be0, 0x3636, 0x6a6a }) { + Put(text, at, 0xd2800000u | ((uint)value << 5)); at += 4; + } + FixtureMaterial().CopyTo(ro, 0x80); + if (ambiguous) FixtureMaterial(13).CopyTo(ro, 0x180); + return (text, ro, data); + } + static byte[] Literal(byte[] input) { + var output = new List { (byte)(Math.Min(input.Length, 15) << 4) }; + if (input.Length >= 15) { int left = input.Length - 15; while (left >= 255) { output.Add(255); left -= 255; } output.Add((byte)left); } + output.AddRange(input); return output.ToArray(); + } + static byte[] Pack(byte[] text, byte[] ro, byte[] data, byte[] compressedText = null, byte[] compressedData = null) { + byte[][] decoded = { text, ro, data }, stored = { compressedText ?? text, ro, compressedData ?? data }; + var output = new byte[0x100 + stored[0].Length + stored[1].Length + stored[2].Length]; + Put(output, 0, 0x304f534e); Put(output, 12, (compressedText != null ? 1u : 0u) | (compressedData != null ? 4u : 0u)); + int file = 0x100; + for (int i = 0; i < 3; i++) { + Put(output, 16 + i * 16, (uint)file); Put(output, 20 + i * 16, (uint)(i == 0 ? 0 : i == 1 ? 0x2000 : 0x3000)); + Put(output, 24 + i * 16, (uint)decoded[i].Length); Put(output, 96 + i * 4, (uint)stored[i].Length); + SHA256.HashData(decoded[i]).CopyTo(output, 160 + i * 32); stored[i].CopyTo(output, file); file += stored[i].Length; + } + return output; + } + static byte[] Pack((byte[] Text, byte[] Ro, byte[] Data) s) => Pack(s.Text, s.Ro, s.Data); + static byte[] Mutate(byte[] source, int offset, uint value) { var b = (byte[])source.Clone(); Put(b, offset, value); return b; } + + static void Main() { + var segments = Segments(); var valid = Pack(segments); + byte[] before = (byte[])valid.Clone(); + Check(FriendsPlayHistoryResources.Extract(valid).AsSpan().SequenceEqual(FixtureMaterial()), "uncompressed semantic extraction"); + Check(valid.AsSpan().SequenceEqual(before), "input NSO stays unchanged"); + Check(FriendsPlayHistoryResources.Extract(Pack(segments.Text, segments.Ro, segments.Data, Literal(segments.Text))) + .AsSpan().SequenceEqual(FixtureMaterial()), "LZ4 literal extension"); + // One literal and an overlapping distance-one match produce 32 A's. + byte[] overlap = { 0x1f, 65, 1, 0, 12, 0 }; + Check(FriendsPlayHistoryResources.Extract(Pack(segments.Text, segments.Ro, segments.Data, null, overlap)) + .AsSpan().SequenceEqual(FixtureMaterial()), "LZ4 overlapping match"); + Reject(null, "null input"); Reject(Array.Empty(), "empty input"); + foreach (int n in new[] { 4, 0xff, 0x100, valid.Length - 1 }) Reject(valid.AsSpan(0, n).ToArray(), "truncated NSO"); + Reject(Mutate(valid, 0, 0), "wrong magic"); Reject(Mutate(valid, 4, 1), "unsupported NSO version"); + Reject(Mutate(valid, 12, 64), "unknown flags"); + Reject(Mutate(valid, 24, uint.MaxValue), "segment allocation bound"); + Reject(Mutate(valid, 20, 128u * 1024 * 1024), "image bound"); + Reject(Mutate(valid, 60, uint.MaxValue), "BSS allocation bound"); + Reject(Mutate(valid, 16, uint.MaxValue), "file offset bound"); + Reject(Mutate(valid, 16, 0), "segment overlaps header"); + Reject(Mutate(valid, 32, Get(valid, 16)), "file segments overlap"); + Reject(Mutate(valid, 36, 0), "virtual segments overlap"); + Reject(Mutate(valid, 20, 1), "unaligned text"); + for (int i = 0; i < 3; i++) { + var bad = (byte[])valid.Clone(); bad[160 + 32 * i] ^= 1; Reject(bad, "each segment hash verified"); + bad = (byte[])valid.Clone(); bad[(int)Get(valid, 16 + i * 16)] ^= 1; Reject(bad, "segment corruption"); + } + foreach (byte[] malformed in new[] { + new byte[] { 0xf0 }, new byte[] { 0xf0, 255 }, new byte[] { 0x20, 65 }, + new byte[] { 0x10, 65, 0, 0 }, new byte[] { 0x10, 65, 2, 0 }, + new byte[] { 0x1f, 65, 1, 0, 255 }, new byte[] { 0x10, 65, 1 }, + new byte[] { 0x1f, 65, 1, 0, 28 }, new byte[] { 0x10, 65 } + }) Reject(Pack(segments.Text, segments.Ro, segments.Data, null, malformed), "malformed LZ4"); + Reject(Pack(Segments(true)), "ambiguous resource tables"); + var changed = Segments(); Reference(changed.Text, 0x100, 0x2080, guard: false); Reject(Pack(changed), "index guard missing"); + changed = Segments(); Reference(changed.Text, 0x100, 0x2080, hmac: 0x804); Reject(Pack(changed), "HMAC targets disagree"); + changed = Segments(); Put(changed.Text, 0x10c, 0x52800003u | (31u << 5)); Reject(Pack(changed), "HMAC size mismatch"); + changed = Segments(); Reference(changed.Text, 0x100, 0x23f0); Reject(Pack(changed), "table crosses rodata boundary"); + changed = Segments(); Put(changed.Text, 0x900, 0); Reject(Pack(changed), "SHA-256 algorithm evidence missing"); + changed = Segments(); changed.Ro.AsSpan(0x80, 32).Clear(); Reject(Pack(changed), "empty entry"); + changed = Segments(); changed.Ro.AsSpan(0x80, 32).CopyTo(changed.Ro.AsSpan(0xa0, 32)); Reject(Pack(changed), "duplicate entry"); + Console.WriteLine($"Friends firmware extraction: {checks} synthetic checks passed."); + } +} diff --git a/dm/tools/tests/test_launcher_settings.py b/dm/tools/tests/test_launcher_settings.py index ed6ce7f8c6..ff36dc0fd0 100644 --- a/dm/tools/tests/test_launcher_settings.py +++ b/dm/tools/tests/test_launcher_settings.py @@ -89,6 +89,14 @@ def test_defaults_follow_each_platform_host(self): self.assertEqual((ios['DM_PSO_MTL4']['default'], ios['DM_NVN_ENC_THREAD']['default']), (ios_pso, '1')) self.assertEqual((mac['DM_PSO_MTL4']['default'], mac['DM_NVN_ENC_THREAD']['default']), ('1', '0')) + def test_network_offers_nextendo_only_in_a_nextendo_build(self): # build_ipa.sh DM_NEXTENDO / DM_NETWORK (the NSP script's --nextendo) + values = lambda rows: [o[0] for o in rows['DM_NETWORK']['options']] + plain = build(WONDER, 'nvn') + self.assertEqual((values(plain), plain['DM_NETWORK']['default']), (['offline', 'lan', 'ldn'], 'offline')) + with patch.dict(os.environ, {'DM_NEXTENDO': '1', 'DM_NETWORK': 'nextendo'}): + online = build(WONDER, 'nvn') + self.assertEqual((values(online), online['DM_NETWORK']['default']), (['offline', 'lan', 'ldn', 'nextendo'], 'nextendo')) + def test_unknown_platform_is_rejected(self): with self.assertRaisesRegex(SystemExit, 'SETTINGS_PLATFORM must be ios or mac'): build(WONDER, 'nvn', 'mca') diff --git a/dm/tools/tests/test_nextendo_bcat.py b/dm/tools/tests/test_nextendo_bcat.py new file mode 100644 index 0000000000..2755515f6b --- /dev/null +++ b/dm/tools/tests/test_nextendo_bcat.py @@ -0,0 +1,51 @@ +"""An offline seed is a retry recipe, never a successful delivery cache.""" +from pathlib import Path +import json +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import nextendo_bcat as bcat + +class CalendarSeeds(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory(); self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.source = bcat.recipe(self.root / 'source', '0100f8f0000a2000', '5.5.2') + self.repo = Path(__file__).resolve().parents[3] + + def test_missing_crypto_prefix_never_builds_or_downloads_a_helper(self): + with mock.patch.dict(bcat.os.environ, {}, clear=True), mock.patch.object(bcat.subprocess, 'check_output') as compiler: + with self.assertRaisesRegex(ValueError, 'DM_OPENSSL_ROOT'): + bcat.helper(self.repo) + compiler.assert_not_called() + + def test_missing_snapshot_is_an_error_in_strict_staging(self): + with mock.patch.object(bcat, 'helper', return_value=Path('/original-test-verifier')), \ + mock.patch.object(bcat.subprocess, 'run', return_value=subprocess.CompletedProcess([], 1)): + with self.assertRaises(ValueError): bcat.stage(self.repo, self.source, self.root / 'strict', '0100f8f0000a2000', '5.5.2') + self.assertFalse((self.root / 'strict').exists()) + + def test_explicit_offline_seed_preserves_only_recipe_and_drops_corrupt_payloads(self): + (self.source / 'current.json').write_text('{"snapshot":"../unverified"}') + (self.source / 'unverified.data').write_text('original fixture, not a delivered resource') + with mock.patch.object(bcat, 'helper', return_value=Path('/original-test-verifier')), \ + mock.patch.object(bcat.subprocess, 'run', return_value=subprocess.CompletedProcess([], 1)): + output = bcat.stage(self.repo, self.source, self.root / 'retry', '0100f8f0000a2000', '5.5.2', allow_missing=True) + self.assertEqual({p.name for p in output.iterdir()}, {'setup.json'}) + self.assertEqual(json.loads((output / 'setup.json').read_text()), {'formatVersion': 1, 'titleID': '0100f8f0000a2000', 'version': '5.5.2'}) + + def test_identity_or_version_cannot_be_promoted_to_another_recipe(self): + for title, version in (('01003bc0000a0000','5.5.2'),('0100f8f0000a2000','5.5.1')): + with self.subTest(title=title, version=version), mock.patch.object(bcat,'helper') as helper: + with self.assertRaises(ValueError): bcat.stage(self.repo,self.source,self.root/'wrong',title,version,allow_missing=True) + helper.assert_not_called() + + def test_recipe_refuses_symlink_ancestors(self): + link = self.root / 'link'; link.symlink_to(self.source,target_is_directory=True) + with self.assertRaises(ValueError): bcat.recipe(link/'child','0100f8f0000a2000','5.5.2') + self.assertFalse((self.source/'child').exists()) + +if __name__ == '__main__': unittest.main() diff --git a/dm/tools/tests/test_nextendo_patches.py b/dm/tools/tests/test_nextendo_patches.py new file mode 100644 index 0000000000..8f25fb1dc9 --- /dev/null +++ b/dm/tools/tests/test_nextendo_patches.py @@ -0,0 +1,104 @@ +"""Synthetic signed-catalog policy/IPS32/NSO tests; no console or game files.""" +import base64 +import copy +import hashlib +from pathlib import Path +import struct +import sys +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import Mock, patch + +REPO = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(REPO / 'dm/tools')) +import nextendo_patches as p +import nso +TITLE = '0100000000001000'; BUILD = '12' * 32 + +def catalog(offset=0x104, original=b'abcd', changed=b'WXYZ', rle=False): + record = struct.pack('>IH', offset, 0 if rle else len(changed)) + record += struct.pack('>H', len(changed)) + changed[:1] if rle else changed + data = b'IPS32' + record + b'EEOF' + return {'revision':1,'patches':[{'id':'synthetic','title_id':TITLE,'build_id':BUILD,'module':'main', + 'patch_version':1,'offset_basis':'nso_header_included','enabled':True,'required_capabilities':['npln.ips32.v1'], + 'sha256':hashlib.sha256(data).hexdigest(),'ips32_base64':base64.b64encode(data).decode(), + 'guards':[{'offset':offset,'original_hex':original.hex(),'patched_hex':changed.hex()}]}]} + +class NextendoPatchTests(unittest.TestCase): + def test_exact_full_identity_preimages_and_original_preservation(self): + image = bytearray(b'0000abcd0000'); saved = bytes(image) + changed, ids = p.apply_image(image,TITLE,BUILD,catalog()) + self.assertEqual(changed, b'0000WXYZ0000'); self.assertEqual(ids,['synthetic']); self.assertEqual(image,saved) + self.assertEqual(p.apply_image(image,TITLE,'12'*16+'34'*16,catalog()),(None,[])) + self.assertEqual(p.apply_image(image,'0100000000002000',BUILD,catalog()),(None,[])) + with self.assertRaises(ValueError): p.apply_image(b'0000abce0000',TITLE,BUILD,catalog()) + def test_disabled_patch_does_not_modify_image(self): + doc=catalog(); doc['patches'][0]['enabled']=False + self.assertEqual(p.apply_image(b'0000abcd0000',TITLE,BUILD,doc),(None,[])) + def test_unknown_policy_digest_and_incomplete_guard_fail(self): + for field, value in [('sha256','0'*64),('enabled',1),('guards',[]),('build_id','12'*16)]: + with self.subTest(field=field): + doc=catalog(); doc['patches'][0][field]=value + with self.assertRaises(ValueError): p.validate_catalog(doc) + # A patch in another format is left alone in the catalog, and refused only for the game build it is for + for field, value in [('offset_basis','unknown'),('module','sdk'),('required_capabilities',[]),('patch_version',2)]: + with self.subTest(field=field): + doc=catalog(); doc['patches'][0][field]=value + p.validate_catalog(doc) + with self.assertRaises(ValueError): p.apply_image(b'0000abcd0000',TITLE,BUILD,doc) + self.assertEqual(p.apply_image(b'0000abcd0000','0100000000002000',BUILD,doc),(None,[])) + doc=catalog(); doc['patches'][0]['guards'][0]['patched_hex']='00'*4 + with self.assertRaises(ValueError): p.validate_catalog(doc) + def test_overlapping_guard_and_conflicting_patches_rejected(self): + doc=catalog(); doc['patches'][0]['guards']*=2 + with self.assertRaises(ValueError): p.validate_catalog(doc) + doc=catalog(); other=copy.deepcopy(doc['patches'][0]); other['id']='conflicting'; doc['patches'].append(other) + with self.assertRaises(ValueError): p.apply_image(b'0000abcd0000',TITLE,BUILD,doc) + def test_rle_and_bounds_and_trailing_bytes(self): + doc=catalog(changed=b'WWWW',rle=True) + self.assertEqual(p.apply_image(b'0000abcd',TITLE,BUILD,doc)[0],b'0000WWWW') + with self.assertRaises(ValueError): p.apply_image(b'0000abc',TITLE,BUILD,doc) + for data in [b'IPS32EEOFextra',b'IPS32'+struct.pack('>IH',0,4)+b'WXYZEEOF',b'IPS32'+struct.pack('>IH',0x104,4)+b'WXY']: + bad=catalog(); bad['patches'][0].update(ips32_base64=base64.b64encode(data).decode(),sha256=hashlib.sha256(data).hexdigest()) + with self.assertRaises(ValueError): p.validate_catalog(bad) + def test_nso_copy_preserves_build_and_updates_segment_integrity(self): + with tempfile.TemporaryDirectory() as folder: + root=Path(folder); source=root/'main'; out=root/'online/main' + header=bytearray(0x100); header[:4]=b'NSO0'; header[0x40:0x60]=bytes.fromhex(BUILD) + chunks=[b'0000abcd',b'ro00',b'data'] + for i,(memory,chunk) in enumerate(zip([0,0x1000,0x2000],chunks)): + struct.pack_into('.nup: 2 base packages`, `base program ID 040015100B514001 is not a base title ID`, or `010015100B515001 is not a DLC of 040015100B514001`, from a NUP of a Switch 1 game's Nintendo Switch 2 Edition (PR #2692). Packed by hand on its own RomFS, the Switch 2 program crashed within a second of `nnMain` on a null `this` in a constructor: with no heap sizes the engine's heaps were never made. With an add-on older than the program: `[RED] game asks to show an error: its upgrade add-on content is older than this program needs`, then `CRASH sig=4` at the game's own trap (before the hook, a crash in `sdk` under `nn::applet::StartLibraryAppletImmediately`). → [A Switch 2 Edition NUP stops at "2 base packages" or "is not a base title ID"](../reference/packing.md#a-switch-2-edition-nup-stops-at-2-base-packages-or-is-not-a-base-title-id) - the survey of a Switch 2 game says `SDK: ?` and `no SDK version string found`, and its provisional profile has `app_pool 0xCD500000`. → [A provisional profile of a Switch 2 game shows no SDK and a Switch 1 memory pool](../reference/packing.md#a-provisional-profile-of-a-switch-2-game-shows-no-sdk-and-a-switch-1-memory-pool) +- a Nextendo build with no cached provider CA stops while preparing its service profile with `HTTP Error 403: Forbidden`. → [An uncached Nextendo CA download returns HTTP 403](../reference/packing.md#an-uncached-nextendo-ca-download-returns-http-403) - after the NSP script was stopped in Spyder (its interrupt), or by a front end's SIGTERM, the tool it was running went on: a shader build or `build_ipa.sh`'s `xcodebuild` kept the CPU busy and wrote into the build folder that the next build reads, and the script could wait for it with no end. A regression run (`regress.py`) stopped during a shader build whose direct child ignored SIGTERM for 10 s left the build's workers running. A tool's child still writing after the tool's own exit was taken for a finished step. → [Stopping a build left its tools running](../reference/packing.md#stopping-a-build-left-its-tools-running) - after the terminal running the NSP script or `regress.py` was closed, the tool the script was running (a shader build, `xcodebuild`, a game under the harness) went on running with no parent, writing into the build folder; the script itself had gone without its cleanup. → [Closing the terminal left a build's tools running](../reference/packing.md#closing-the-terminal-left-a-builds-tools-running) - none seen on a game. An interrupt, a SIGTERM or a failed delete while the NSP script replaced one of its outputs (an extraction, the rewritten modules, the NROs, a DLC folder, a shader capture, the shader package) could leave that output half deleted at its real path, and a reuse check that looks for a few files (`extract`'s: `ExeFS/main`, `RomFS.img`, the RomFS marker) could take it for a finished output on the next run. → [Stopping a build while it replaced an output left that output half deleted](../reference/packing.md#stopping-a-build-while-it-replaced-an-output-left-that-output-half-deleted) @@ -480,6 +481,19 @@ One line per symptom in the [subsystem references](../reference/): what you see - the game ends right after `nnMain`, with a crash in its own cleanup on an object it had not created yet (DRAGON QUEST BUILDERS 2: `CRASH sig=11 addr=0x60db0` at `main+0x2676c8`, x0 = 0, the callers `main+0x85210` and `main+0x7fabf8`). No red line. → [Creating an ssl context needs no network](../reference/services.md#creating-an-ssl-context-needs-no-network) - `abort` under `grpc_init` at startup, with no red line: `game called nn::diag abort: Result 0, call site sdk+0xb8fe8`, backtrace `sdk+0xba138 sdk+0x7bd670 sdk+0x777f30 main+0x21f0c80`, just after `fs mount _npln:` (Ocarina of Time). → [`EventFd` needs no network](../reference/services.md#eventfd-needs-no-network) - `CRASH sig=10` (SIGBUS) in a network thread right after start (Minecraft's `NetherNet Network`, `main+0x18b2ae8`, `x0=0x4000`), at a load from its own stack. → [Event descriptors in an `fd_set`](../reference/services.md#event-descriptors-in-an-fd_set) +- in Nextendo mode a game finds its network service account unavailable, and the log says `nextendo: no game credential`. → [A Nextendo account needs a sign-in on the Mac](../reference/services.md#a-nextendo-account-needs-a-sign-in-on-the-mac) +- with `DM_NETWORK=nextendo` and a sign-in, the game still cannot reach Nextendo: every Nintendo host name is refused (no `DM_NEXTENDO_ROUTES`), or the game connects and then fails because its own code still expects Nintendo's servers. → [A game online on Nextendo needs its route profile and Nextendo's game patch](../reference/services.md#a-game-online-on-nextendo-needs-its-route-profile-and-nextendos-game-patch) +- in Nextendo mode, with the sign-in working, a NEX game's online menu shows an error (Mario Kart 8 Deluxe: 2306-0502). With `DM_SSL_TRACE=1` the log has the name lookup and connect to its game server (`g2b309e01-lp1.s.n.srv.nintendo.net`), then `[ssl-trace] stage=5 ... result=0x000002a2 native=-9841`: the certificate check failed. → [Nextendo's NEX server presents a self-signed certificate](../reference/services.md#nextendos-nex-server-presents-a-self-signed-certificate) +- in Nextendo mode, past the certificate check, a NEX game's online menu shows 2306-08xx (Mario Kart 8 Deluxe: 2306-0807, `game asks to show an error (ErrorResultVariant): state 2 ... as an error code 2306-0807`). The game wrote its WebSocket upgrade to the game server, read the answer and gave up about 4 s later, with no UDP socket opened. → [A NEX login refused by Nextendo carries no reason](../reference/services.md#a-nex-login-refused-by-nextendo-carries-no-reason) +- `scripts/build_ipa_from_nsp.py --nextendo` stops at `[5/10] Nextendo game patch` with `[RED] Nextendo game patch could not be verified, no game code was changed: Unsupported signed patch policy`, for a game whose patch did not change or that has no patch at all (Mario Kart 8 Deluxe). → [A Nextendo build stops at "Unsupported signed patch policy"](../reference/services.md#a-nextendo-build-stops-at-unsupported-signed-patch-policy) +- a Nextendo build stops while decoding compressed `main`, even when the exact build has no catalog patch. → [A signed Nextendo patch check stops on a ZBIC module](../reference/services.md#a-signed-nextendo-patch-check-stops-on-a-zbic-module) +- in Nextendo mode the log has `[RED] nextendo: /api/me answered HTTP 401` (and `/api/friends answered HTTP 401`) while the game's own online login works. Or, after the first fix below, `[RED] nextendo: /api/profile answered HTTP 401`, `/api/history answered HTTP 401` and `online status could not be asked: Session invalide ou expirée.`, and Nextendo's site keeps showing no play time. → [Nextendo's account routes take different tokens](../reference/services.md#nextendos-account-routes-take-different-tokens) +- in Nextendo mode on a device whose time was set by hand, `nextendo: no game credential: the game token is past its expiry` though the sign-in just worked, or a game's own online login is refused while the account may play. → [A device clock that is off fails the Nextendo sign-in](../reference/services.md#a-device-clock-that-is-off-fails-the-nextendo-sign-in) +- sign-in can wait on a stalled HTTP request, or accept more data than a sign-in reply needs. → [A Nextendo sign-in request has no total deadline](../reference/services.md#a-nextendo-sign-in-request-has-no-total-deadline) +- in Nextendo mode the game's Mii list has only the six default Miis though the account has a Mii, and friends see the game's name with nothing about what the player is doing. Nextendo's site shows no play time and no games played for the game. → [The Nextendo account's Mii and activity, and no play time](../reference/services.md#the-nextendo-accounts-mii-and-activity-and-no-play-time) +- in Nextendo mode, changing menus in an online game takes a moment longer than offline, most on the first visit or on a slow network. → [A Nextendo presence update holds the game's thread](../reference/services.md#a-nextendo-presence-update-holds-the-games-thread) +- in Nextendo mode, Mario Kart 8 Deluxe finds a Worldwide race and starts it, then shows a communication error during the race (on the second lap here) and returns to the menu. The log has no error line from the host. → [An online race ends in a communication error with nothing in the log](../reference/services.md#an-online-race-ends-in-a-communication-error-with-nothing-in-the-log) +- with `DM_NETWORK` set to a network mode, a game that uses gRPC (`nn::npln`) aborts in `grpc_init` as it does offline without event descriptors, or its poller never wakes while it polls its sockets. → [`EventFd` in a network mode shares the socket numbering](../reference/services.md#eventfd-in-a-network-mode-shares-the-socket-numbering) - New Game stays on the loading artwork with an empty progress bar while rendering and loading tips continue (Divinity: Original Sin 2). Both `nn::socket::Socket(AF_INET, SOCK_DGRAM, 0)` calls fail, so RakNet never completes initialization. → [UDP loopback works offline](../reference/services.md#udp-loopback-works-offline) - `Break#1 reason=0 Result=0` right after the first save is created, then exit 42; the stack has `nn::diag::detail::OnAssertionFailure` under `nn::image::JpegDecoder::Decode` (`sdk+0x394e4`), called from the game (Burnout Paradise Remastered, SDK 9.3). → [The local user's profile image](../reference/services.md#the-local-users-profile-image) - `[RED] sf: the game connects to service mii:e … mii:u itself`, then an abort. → [Mii database answered by the host](../reference/services.md#mii-database-answered-by-the-host) @@ -494,6 +508,8 @@ One line per symptom in the [subsystem references](../reference/): what you see - `[RED] sf: the game connects to service nsd:a itself, which the host does not serve` (also `nsd:u`), then `game called nn::diag abort: Result 0xe8d` and exit 134 during startup. → [Server environment queries without nsd](../reference/services.md#server-environment-queries-without-nsd) - `[RED] sf: the game connects to service bt itself, which the host does not serve`, then `game called nn::diag abort` at `sdk+0x16ba48` and exit 134, a second after the audio renderer starts. With `bt` and `btm:u` served as zeroed host sessions the abort moves to `nn::btm::user::InitializeBtmUserInterface` (`sdk+0xb8eb4`), before either session gets a request. → [Bluetooth LE at boot](../reference/services.md#bluetooth-le-at-boot) - the boot sits at a black loading screen for good, CPU nearly idle, every thread waiting, about 1 boot in 6 (3 in 4 with four Mac hosts at once); the title movie is never opened, and the save files are never probed. → [Network requests stay on hold before they settle](../reference/services.md#network-requests-stay-on-hold-before-they-settle) +- a real UDP/TCP receive returns guest `EFAULT` (14) when its otherwise valid destination belongs to a graphics-tracked read-only page. → [Socket receive into write-protected tracked guest pages](../reference/services.md#socket-receive-into-write-protected-tracked-guest-pages) +- `GetSockOpt` returns guest `EFAULT` (14) for an otherwise valid result buffer on a graphics-tracked read-only page. → [Socket option output into tracked write-protected guest pages](../reference/services.md#socket-option-output-into-tracked-write-protected-guest-pages) - one thread at 100% CPU from boot, with one SVC in 99 s (`NexusRevolution Socket`, `main+0x92c7c4`, the game's network thread). → [Socket `Poll` and `Select` with nothing to wait on](../reference/services.md#socket-poll-and-select-with-nothing-to-wait-on) - the first comparison in `nnMain` aborted in `sm`. → [Language codes](../reference/services.md#language-codes) - `DM_LANG=zh-Hans` or `zh-Hant` reaches the game unchanged, but its startup menu falls back to Japanese; the older `zh-CN` or `zh-TW` spelling selects Chinese. → [Chinese language aliases in settings comparisons](../reference/services.md#chinese-language-aliases-in-settings-comparisons) @@ -516,6 +532,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - on a phone, `GetSharedFontLoadState` would report "not loaded". → [Shared fonts on iOS](../reference/services.md#shared-fonts-on-ios) - a crash after the shared fonts load, looking up the "?" glyph (`nro0+0xaef8a8`, a null pointer from nn::font's texture cache), with `ScalableFontEngine::LoadFont` returning 201 on one engine and 0 on another, and `SetFont` 301. → [Shared font stand-ins sized for the game's font engines](../reference/services.md#shared-font-stand-ins-sized-for-the-games-font-engines) - saves dated 18:00:02 31/12/1969 (`ToCalendarTime: first conversion 2 → 1969-12-31 18:00`), and Continue, which takes the newest save, loads an older one. → [Time zone rules, calendar conversion and the network clock](../reference/services.md#time-zone-rules-calendar-conversion-and-the-network-clock) +- the game reports that it cannot load its current calendar even when the data is present and the host has an accurately synchronized clock. → [Network clock availability rejects a synchronized host](../reference/services.md#network-clock-availability-rejects-a-synchronized-host) - times a game shows through the C library are off by the host's UTC offset: Hades II's load screen dated a save made at 01:44 KST (UTC+9) 16:44 the day before, its UTC time. The save file itself holds the right time. → [The C library's local time is UTC, as on a Switch](../reference/services.md#the-c-librarys-local-time-is-utc-as-on-a-switch) - SDK calls that reach the time service, each aborting in `sm::Initialize` (or found in the imports before they were met). → [Steady clock, clock snapshots and user clocks](../reference/services.md#steady-clock-clock-snapshots-and-user-clocks) - after a normal game restart on the same Mac, Pokémon Brilliant Diamond can record a new time penalty and skip daily or weekly events. → [A game restart reports a user clock change](../reference/services.md#a-game-restart-reports-a-user-clock-change) @@ -555,10 +572,22 @@ One line per symptom in the [subsystem references](../reference/): what you see - a null read in `nn::os::SdkMutexType::Lock`, at `sdk+0x151fb0`, called from `nn::gs::sdk::QueryApplicationGpuTimeSpan` after the first rendered frame. → [Application GPU scheduling time](../reference/services.md#application-gpu-scheduling-time) - a null read at boot in `nn::os::SdkMutexType` under `nn::gs::sdk::SetGraphicsFrameLengthMode`, called from `nn::oe::SetGraphicsTargetFrameRate`. → [The target frame rate (graphics frame length)](../reference/services.md#the-target-frame-rate-graphics-frame-length) - a Switch 2 game presents at 720p, with its upscaler at the matching low size. → [The display's largest buffer](../reference/services.md#the-displays-largest-buffer) +- a native port cannot create or join a game's LAN or local-wireless room because its socket and LDN service hooks always return unavailable. → [Opt-in native LAN sockets and LDN over IP](../reference/services.md#opt-in-native-lan-sockets-and-ldn-over-ip) +- the SDK's cancellable `GetHostByName` path reaches an unavailable resolver service or cannot retire its pending lookup when canceled or finalized. → [SDK DNS cancellation cannot retire an in-flight lookup](../reference/services.md#sdk-dns-cancellation-cannot-retire-an-in-flight-lookup) +- in a network mode, Super Mario Bros. Wonder's online menu shows error 2321-4992 (gRPC's UNAVAILABLE) on its first NPLN request. The log has gRPC's event descriptors and polls, but no socket, connect or name lookup. → [gRPC's name lookup and reads fail before its first socket](../reference/services.md#grpcs-name-lookup-and-reads-fail-before-its-first-socket) +- in a network mode, the game opens its socket and connects, then closes the socket without sending anything. Super Mario Bros. Wonder's online menu shows 2321-4992, and its gRPC reports `tcp_client_posix.cc:299` "Address family not supported by protocol". → [gRPC gives up a connection on a stale errno](../reference/services.md#grpc-gives-up-a-connection-on-a-stale-errno) +- a calendar-dependent title can boot with no delivery data or read an older snapshot before an asynchronous refresh finishes. → [Optional calendar data is stale or absent at the first guest read](../reference/services.md#optional-calendar-data-is-stale-or-absent-at-the-first-guest-read) - `registered NROs not found` from `nro_collect.py` in a game whose RomFS has an NRR, or `[RED] ro::LoadModule: no rewritten NRO with SHA-256 …`. `main` is small (about 600 KB of code) beside a data segment of random-looking bytes. → [A game that decodes its code at run time](../reference/services.md#a-game-that-decodes-its-code-at-run-time) - a crash in `ro::RegisterModuleInfo`, or an NRR that seems to register millions of hashes: the words at +0x340 and +0x344 are random. → [NRR version 1](../reference/services.md#nrr-version-1) - Xenoblade Chronicles 2's Japanese release 2.0.2 (`0100F3400332C000`, main `e3938fa78579c1cab27fb0ecef1314e8`) hits its bounds assertion at `main+0x6979dc`, called from `main+0x6ae53c`, just after the first frames. → [Legacy settings language lists before SDK 4](../reference/services.md#legacy-settings-language-lists-before-sdk-4) +## Optional online-service backend + +- an enabled native socket connects, but the SDK's TLS context is still an unavailable-service cut. → [Native client TLS](../reference/online-services.md#native-client-tls) +- `DM_SSL_TRACE=1` reports the same verify failure for a rejected chain and for a chain that passes platform trust but fails strict X.509. → [A scoped CA failure does not say which TLS check rejected it](../reference/online-services.md#a-scoped-ca-failure-does-not-say-which-tls-check-rejected-it) +- a service template reaches native DNS unchanged, or an IP handoff loses the logical TLS service identity. → [Explicit routing and NSD](../reference/online-services.md#explicit-routing-and-nsd) +- a service transport works but the SDK has no usable account identity/token or friends snapshot. → [Account and social providers](../reference/online-services.md#account-and-social-providers) + ## Movies - AAC samples after a seek or loop differ from a fresh decode of the same packets; the old position's overlap can contaminate the beginning of the new position. → [Audio decoder history survives a movie seek](../reference/movies.md#audio-decoder-history-survives-a-movie-seek) diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv index 2537429fe7..22dcbc0439 100644 --- a/docs/env_switches.tsv +++ b/docs/env_switches.tsv @@ -19,6 +19,7 @@ DM_AUDIO_MUTE switch `=1` runs the real Core Audio output path (callback pacing, DM_AUDREN_RT diagnostic `0` keeps ordinary scheduling for the in-process audio renderer so its default real-time policy can be compared against it DM_AUDREN_TRACE diagnostic When set, the CPU audio renderer logs every update with the number of frames rendered since the previous one DM_AV1_DAV1D switch `=1` decodes AV1 movies with dav1d even where VideoToolbox decodes AV1 (Apple M3 and A17 Pro on), to compare the two or to check the path older chips take (`hle_movie_av1.c`) +DM_BCAT_TEST_SANITIZE test 1 builds the synthetic BCAT launch fixture with AddressSanitizer and UndefinedBehaviorSanitizer; not a runtime game switch DM_BOOTPROF diagnostic When set, logs boot timing: the loader's breakdown (mapping, relocation, probes), Metal library loading, pipeline creation, texture uploads and the first present DM_BUNDLE_ID switch Overrides the iOS app's bundle ID in `build_ipa.sh` (default `org.nxnative.`) DM_CHEATS path Folder of Atmosphère cheat files: `<folder>/<build ID>.txt` or an SD-card layout (`atmosphere/contents/<title ID>/cheats/`) under it (default `<DM_ROOT>/cheats`); the Mac menu lists and toggles them @@ -123,6 +124,7 @@ DM_KEYS switch Scripted input: `<seconds or f<frame>>:<key>[+key][~hold or ~f<fr DM_LANG player Game language as a language code (default `en-US`; the iOS app sets the one the IPA was packed with) DM_LAUNCHER switch `0` skips the iOS settings screen or the Mac settings window and starts the game at once, with the saved choices (on the Mac also `--no-launcher`) DM_LAUNCH_PARAM path File whose bytes `oe::TryPopLaunchParameter` returns once; `oe::ExecuteProgram` sets it for the program it starts; a relaunch removes it +DM_LDN_TRACE diagnostic Log LDN bridge sessions and protocol events DM_LINK_VTICK switch `0` keeps the system's display-link rate on 144 or 165 Hz Mac screens; by default the link counts only the refreshes nearest a steady 1/60 s clock DM_LOADHASH diagnostic `=1` logs an address-independent SHA-256 per module after loading DM_LONGFRAME diagnostic `0` turns off the long-frame log (on by default), a line for a frame over 20 ms or with GPU time over 16.7 ms that is clearly above recent frames @@ -145,7 +147,18 @@ DM_MOTION_LOG diagnostic `=1` logs player 1's mapped motion sample once a second DM_MOVIE_TRACE diagnostic When set, the movie decoder logs every call with its thread and decoder (by default the first 12 calls, then every 2^k-th) DM_MSL_DIR path Parent folder of the shader libraries: NVN loads from `b-<chain version>/` or the one file `b-<chain version>.img` beneath it, Vulkan from `vk/`, GL from `gl/`; the app and the Mac launcher set it DM_NDVE_ENGINE switch `0` runs nn::ndve's movie network (Ocarina of Time's title and opening movies) as the game's 12 translated dispatches after its colour conversion instead of the host's kernels (dm/gfx/msl/ndve_engine.metal, on by default: the same output, about half the frame's GPU time on an M4 Pro); `ab` alternates with DM_AB; `check` runs the game's dispatches and the host's network beside them and logs every 300 frames how many texels of the two differ. The host's kernels take only the model they were written for, bound by its shaders' keys and its weights' layout (docs/reference/shaders.md, The NDVE movie network by the host) -DM_NICK switch The account nickname the game sees (default `Player`) +DM_NETWORK player auto routes LAN, LDN and configured online calls by service; offline, lan, ldn and nextendo are explicit overrides. nextendo enables scoped online services; auto adds them only with an explicit service profile (DM_NEXTENDO_ROUTES) +DM_NETWORK_INTERFACE player IPv4 interface name for local sockets; otherwise use the actual default route +DM_NET_DISCOVERY_PEER player Optional discovery relay IPv4 endpoint; automatic local discovery requires no entered address +DM_NET_TRACE diagnostic Log native socket and local-network translation details +DM_NEXTENDO_BCAT_DIR path Private exact-title/version calendar recipe and optional validated seed; absent or invalid recipes never query the network +DM_NEXTENDO_BIRTHDAY player Birthday a game reads from the Nintendo Account info in Nextendo mode, as YYYY-MM-DD, when the Nextendo account gives none. The launcher sets it from the picker under the Nextendo account; without either the game gets 2000-01-01 +DM_NEXTENDO_CLIENT_ID switch The Nextendo application (a public PKCE client registered at nextendo.network/developers) the sign-in uses: read on the Mac, and written into the iPhone app's Info.plist as DMNextendoClientID at build time. Without one nobody can sign in +DM_NEXTENDO_COUNTRY player Two-letter country a game reads from the Nintendo Account info in Nextendo mode when the Nextendo account has none. The launcher sets it from the device region +DM_NEXTENDO_LOGIN_DIR path Folder of the Mac's stored Nextendo sign-in (dm/tools/nextendo_login.m; default ~/Library/Application Support/nxnative/nextendo); tests point it at a temporary folder +DM_NEXTENDO_ROUTES path Explicit local public service policy TSV; AUTO enables online services only when nonempty, and configured invalid policies fail closed. +DM_NEXTENDO_SERVICES path `=<folder>` (the NSP script's `--nextendo`) makes `build_ipa.sh` pack that public Nextendo service profile into the app as `dm/nextendo-services`; `main.m` hands it to the host as `DM_NEXTENDO_ROUTES` +DM_NICK switch The account nickname the game sees, at most 32 bytes (default: the Nextendo username in Nextendo mode, else `Player`). The launcher sets it from its Player name field while Network is not offline DM_NRO switch `0` turns off loading of the NRO modules the game's NRR files register (on by default): every `nn::ro::LoadModule` then fails DM_NRO_CAPTURE diagnostic folder: a `nn::ro::LoadModule` with no rewritten copy writes the image to `<folder>/<SHA-256>.nro` and ends the run (the NSP script's capture of an NRO the game decodes at run time) DM_NRO_DIR path folder of NROs the shader split reads like `main`, and in which it finds a CRA archive's file table (the NSP script sets it for a captured NRO) @@ -311,6 +324,7 @@ DM_OODLE_HOST path The Mac host binary that `shader_split.py` runs in its Oodle DM_OODLE_JOB path `=<job file>`: the host runs the game's own Oodle decoder on every record of the job file right before `nnMain`, writes `<job file>.out` and exits (Unreal shader archives) DM_OODLE_MODULES path The rewritten modules the Mac host's Oodle tool mode loads when `shader_split.py` decodes Trinity packs; set by the NSP script DM_OODLE_SERVE switch `=1`: the host answers decode requests on stdin / stdout with the game's own Oodle (or LZ5) decoder from the guest main thread before the SDK starts, until stdin ends +DM_OPENSSL_ROOT path Reviewed static OpenSSL prefix for optional online/BCAT helper compilation; no crypto dependency is downloaded by BCAT DM_OPMODE player The operation mode the game sees: `0` handheld, `1` console (default: the profile's `op_mode`, console unless set); read once at startup DM_PAD_IDENTICAL switch `0` stops reading identical pads here when GameController lists fewer of their model than IOKit has, such as two Pro Controllers over USB (each a player of its own: a Pro Controller from its report 0x30, another model from its HID elements; `pad_hid_mac.h`, `pad_pro.h`); `DM_HID_PADS=0` stops it too; Mac only DM_PAD_MERGE switch `=1` merges every controller into player 1, as before, instead of giving each controller a player of its own (Mac and iOS) @@ -427,6 +441,7 @@ DM_SPIN switch `0` makes the rewriter's spin gate return at once, so guest poll DM_SPIN_LIST diagnostic `=1` makes `patch_nso.py` print every guest poll loop it found and sends through a spin gate DM_SPIN_POLL switch `=<µs>`: how long a spin-gate wait polls before it sleeps with the yield back-off (default 2000; `0` yields on every pass) DM_SPLIT_REGISTERED_MAP path Registered `shader_map.tsv` used by the splitter to keep a known source label when the same shader is found in several places +DM_SSL_TRACE diagnostic 1 logs at most 128 TLS state events with numeric fields and fixed verify failure labels; no hosts, pointers, certificates, credentials or stream data. DM_SVC diagnostic `=1` logs memory SVCs (`SetHeapSize`, `MapMemory`, `Map`/`UnmapPhysicalMemory`) with their addresses and sizes DM_SW2 player `=1` turns on Switch 2 controllers over Bluetooth LE (Joy-Con 2, Pro Controller 2): the settings window's Switch 2 controllers. Off, no Bluetooth client is created and macOS asks nothing. The host also stays off when the app's Info.plist has no NSBluetoothAlwaysUsageDescription, without which macOS ends the process at the first Bluetooth scan DM_SW2_GYRO_DPS diagnostic `=<degrees per second per count>` is the Switch 2 controllers' gyro scale (default 0.0607, measured on a left and a right Joy-Con 2; the Switch family's nominal 0.070 turned a 90 degree tilt into 104) @@ -436,6 +451,7 @@ DM_SW2_MOTION switch `=0` leaves out the motion of Switch 2 controllers (buttons DM_SW2_MOTION_SIDE switch `=L` takes a Joy-Con 2 pair's motion from the left Joy-Con instead of the right one DM_SW2_VERBOSE diagnostic `=1` logs the first report of each second of every Switch 2 controller: buttons, sticks, raw sensors, battery, and the bytes the parser does not read (0x18..0x2F and past 0x3C, in hex: whether a report carries the sensor's own timestamp or more than one sample is not known) DM_SYMCHECK diagnostic `=1` checks every hashed module symbol lookup against a linear search and logs a red line for each mismatch +DM_SYSTEM_DATA_DIR path Private imported firmware resources, including the certificate store the online backend reads (`0100000000000800/files/ssl_TrustedCerts.bdf`; else `DM_SYSTEM_DIR`'s `sysdata/0100000000000800/`); never console keys or resources in the public source tree DM_SYSTEM_DIR path The player's own console files, for every game: `sysdata/<16 hex digits>/` a system data archive's RomFS files, `save/8000000000000030/MiiDatabase.dat` the Mii database (docs/reference/services.md, A console's own Mii database and system data), and the host writes `host/MiiDatabase.dat`, the Miis `AppendMii` made; the Mac launcher sets `~/Library/Application Support/nxnative/system`, the iOS app `Documents/system`; default `$DM_ROOT/run/platform/system` DM_TBUF_ALIGN diagnostic `=<bytes>` uses that value as the linear-texture alignment when it is larger than the device's `minimumLinearTextureAlignmentForPixelFormat`, for buffer textures and for linear textures on a pool's buffer: a Mac can then reproduce a phone's larger alignment (a 64-byte one fails the buffers and linear textures a device with 64 bytes cannot view), to check `tbuf_as_2d`'s aligned-row copy and the upload of unaligned linear textures (`linear_fit`) DM_TEAM_ID switch Apple team ID for the per-game Xcode project, used when `--team-id` / `TEAM_ID` is not given; `build_ipa.sh` uses the placeholder `0000000000` (unsigned) when unset diff --git a/docs/reference/README.md b/docs/reference/README.md index 53dd29d1a9..8f957b319a 100644 --- a/docs/reference/README.md +++ b/docs/reference/README.md @@ -9,6 +9,8 @@ How the host meets each part of a Switch game, and every failure met so far, one | [memory.md](memory.md) | Guest layout, heap and application pool, virtual address memory and the alias region (the SDK's node area), engine allocators, mapping SVCs, running out of memory | | [threads.md](threads.md) | Thread creation and cores, address arbitration, yields and spin waits, events | | [services.md](services.md) | SDK calls and system services: sm connections, names that changed between SDKs, file system and saves, add-on content, input, keyboard and applets, display and operation mode, accounts and network, settings and fonts, C library and time, modules | +| [online-services.md](online-services.md) | Optional native TLS, private service policy/NSD, and explicit account/social providers; no authorization UI | +| [nextendo-bcat.md](nextendo-bcat.md) | Optional signed-eligibility calendar preparation, pre-guest refresh, immutable delivery snapshots and offline failure behavior | | [movies.md](movies.md) | The SDK's movie library: decoder lifecycle, output slots, native-texture output, demuxers and codecs, game movie players | | [audio.md](audio.md) | The audio renderer and its command lists by SDK, AudioOut and devices, codecs, timing | | [frame-rate.md](frame-rate.md) | The host's frame step, engine frame limiters, present intervals and display rates, CPU cost | diff --git a/docs/reference/nextendo-bcat.md b/docs/reference/nextendo-bcat.md new file mode 100644 index 0000000000..c076ffa586 --- /dev/null +++ b/docs/reference/nextendo-bcat.md @@ -0,0 +1,34 @@ +# Optional BCAT calendar delivery + +I separated this backend from my application's interface for the [online-service scope discussion](https://github.com/seedds/nxnative/issues/951). I keep the service interfaces independent of an account or authorization UI. I have not established gameplay on this newly based upstream branch. + +## Startup and offline behavior + +`main.c` calls `dm_bcat_pre_guest_start` on the guest boot thread, before SDK initialization and the game's first filesystem read. The weak `dm_bcat_online_enabled()` provider returns zero. A configured online-service backend may override it only after checking explicit online mode and a valid local service profile. That capability does not authenticate a calendar: the signed catalog and content checks remain mandatory. + +I require a separate exact-title/version recipe, `bcat/setup.json` beside the modules or under `DM_NEXTENDO_BCAT_DIR`. No recipe, an invalid title/version, an absent online provider, or a build without the optional signature verifier causes **zero HTTP requests**. An offline launch may select a previously validated bundled or private cached snapshot; missing data remains unavailable. I do not report an empty delivery mount or a disabled synchronization as successful delivery. Oodle helper modes do not initialize calendars. + +Every online process checks again, even if another launch just refreshed the cache. I use one **12-second monotonic network budget** across the catalog, archive and optional static requests. Failure or timeout retains the last validated snapshot and reports freshness as unconfirmed. Later guest sync requests use an actual background job; observers retain that job's lifetime, status, result and byte count. A later successful job changes future delivery opens, while the RomFS overlay stays fixed for the current game session. + +## Validation and storage + +I verify canonical Base64 and Ed25519 signatures, reject duplicate JSON fields and unknown required capabilities, enforce catalog identity, time bounds, revision/issue rollback rules, title eligibility and accepted versions. Verification uses the shared static OpenSSL prefix under `DM_OPENSSL_X509`; without that capability I reject catalogs and cached snapshots. This branch does not add or download a cryptography implementation. The separate TLS/online series supplies its reviewed static library and licenses. + +The first provider recipe supports only Splatoon 2's three regional IDs and **5.5.2**. This is a recipe boundary, not a compatibility claim for all three executables. The calendar ZIP is unsigned: I require normal HTTPS authentication and use the signed game catalog for eligibility, not as a signature over archive bytes. I pin static recipe resources by public commit and SHA-256. + +I bound downloads, entry counts and expanded sizes; reject redirects, encryption, unsupported compression, traversal, duplicate/case-alias names, symlinks and overlapping/local-versus-central inconsistencies; verify CRCs and required resource structures. Published snapshots contain their signed catalog, provenance and per-file hashes. I serialize publication under a nonblocking interprocess lock and atomically replace the current pointer only after complete validation. I do not prune a running session's referenced snapshot. Atomic visibility and file synchronization do not constitute a separately tested whole-directory power-loss transaction. + +`hle_fs.c` merges the selected immutable overlay read-only with existing RomFS overlays and mounts real delivery files at `bcat:`. Unmount hides new path opens while already opened file descriptors remain valid. SDK delivery objects retain their own files, directory snapshots and synchronization observers. `GetDigest` returns the actual 16-byte MD5 value in both AAPCS64 return registers through the existing large-stack entry; the digest is not an authentication signature. + +The preparation API in `dm/tools/nextendo_bcat.py` writes an exact recipe, invokes the same native verifier and stages one complete validated snapshot. A deliberately recipe-only offline seed is explicitly incomplete; it is never promoted into successful delivery. The tool requires `DM_OPENSSL_ROOT`, and its private helper/cache belongs under `Library/Application Support/nxnative/BCAT`, not the source tree. I include no real calendar archive, game resource, SDK, firmware, account credential or enrolled certificate. + +## Checks and limits + +I ran the native signed-policy/store, bounded ZIP, SDK lifetime/ABI and real temporary-filesystem fixtures in normal and ASan/UBSan builds. The synthetic downloader exercises 20 new-process scenarios, including changed data before the first open, ETag/304, responses without ETags, shared timeout, interruption, cache preservation, all zero-request gates, a separately linked online-provider override and a real background refresh that preserves the session overlay and old open descriptor while advancing delivery opens. These fixtures use original resource bytes, fixture-only signing keys and isolated temporary home directories; they never contact a provider or use the account/cache of the person running them. + +```sh +make -C dm/host/tests GAME=0100152000022000 DM_OPENSSL_ROOT='/reviewed/static/openssl' bcat bcat-sanitize +DM_BCAT_TEST_SANITIZE=1 make -C dm/host/tests DM_OPENSSL_ROOT='/reviewed/static/openssl' bcat-launch +``` + +In my originating fork I tested real calendar refresh and Splatoon 2 EUR 5.5.2 reaching the Mac online lobby and Territorial queue. I deferred the match test because too few players were available during my attempt. That does not qualify this rebased branch, a completed match, peer-to-peer play, another title/region or iOS gameplay. I have not run new hardware/game regression sessions for this extraction; their absence remains explicit before a final upstream submission. diff --git a/docs/reference/online-services.md b/docs/reference/online-services.md new file mode 100644 index 0000000000..9fb1e95065 --- /dev/null +++ b/docs/reference/online-services.md @@ -0,0 +1,56 @@ +# Optional online-service backend + +This backend is independent of a game library or authorization interface. I extracted the engine changes from my originating fork for the [scope discussion](https://github.com/seedds/nxnative/issues/951). Default builds remain offline. No game, firmware, service certificate, account document, password, OAuth token or observed leaf certificate is distributed here. + +### Native client TLS + +- **Symptom:** an enabled native socket connects, but the SDK's TLS context is still an unavailable-service cut. +- **Cause:** a raw TCP transport does not implement the SSL service, its object ABI, certificate verification or asynchronous socket ownership. +- **Fix:** `hle_ssl.c` adapts the C/C++ service entry points to `hle_ssl_apple.m`. Opaque guest objects key bounded owned registries. The backend duplicates a guest descriptor with its generation, preserving the underlying connection through guest close/reuse; destroy/finalize invalidate the owned objects. Blocking methods use the guest-aware HLE wait path. The implementation handles real handshake/read/write/poll, nonblocking progress, server-certificate buffers, client PKCS#12 data and ALPN. Unsupported operations fail rather than claiming a session. Contexts accept normal system PKI and explicitly imported server anchors, always retaining hostname verification. +- **Private PKI:** a configured peer may supply a private anchor, scoped to that peer/connection. `hle_nextendo_x509.c` uses strict X.509 purpose, SAN, chain, current-time and strength checks without default trust paths or a verification bypass. Optional explicit leaf enrollment accepts only identical DER for one enrolled logical identity, with self-signature, validity, server purpose and key/signature strength checks. It neither adopts an observed certificate automatically nor changes system trust. A numeric NEX handoff is allowed only by an explicit alias paired to the same exact identity, address and enrolled certificate. +- **Build:** `dm/tools/apple_crypto.py` pins OpenSSL source by SHA-256 and builds static libcrypto for the selected Apple SDK. The DM_OPENSSL_ROOT build variable may point to an already prepared target-compatible prefix. The iOS source/flags generator propagates the static archive to both real and smoke links; a Mac archive is not an iPhone dependency. The [OpenSSL license and provenance](../../dm/third_party/notices/OpenSSL/PROVENANCE.md) must accompany redistributed linked applications. No OpenSSL binary is committed. +- **Check:** I exercised real loopback TLS through the guest's registered C/C++ gates using ephemeral test certificates: SNI/hostname failures, nonblocking progression, data, polling, certificate buffers, descriptor generation/close ownership, context IDs, ALPN and lifecycle. The private verifier separately rejects malformed DER, wrong purposes/names/anchors, weak/invalid signatures, expired/future leaves and an unpaired/rotated enrolled certificate. No user account or public game server is involved in these fixtures. + +### A scoped CA failure does not say which TLS check rejected it + +- **Symptom:** `DM_SSL_TRACE=1` reports the same verify failure for a rejected chain and for a chain that passes platform trust but fails strict X.509. +- **Cause:** the verify trace kept only the combined outcome. +- **Fix:** append `verify=platform-trust` or `verify=strict-x509` to the existing failure event for this path. Neither label carries peer data or changes the verification result. +- **Found on:** loopback TLS with an untrusted CA and with a trusted chain for the wrong name. + +### Explicit routing and NSD + +- **Symptom:** a service template reaches native DNS unchanged, or an IP handoff loses the logical TLS service identity. +- **Cause:** Horizon NSD expansion, host DNS and TLS identity policy are different layers. Redirecting DNS alone cannot provide either NSD semantics or trustworthy SNI. +- **Fix:** `hle_nsd_backend.c` expands a bounded retail Fqdn template and documented account aliases before the socket resolver consults a startup DNS provider. `hle_nextendo_routes.c` publishes a bounded immutable policy only after validating the complete configuration and its certificate hashes. It registers separate DNS admission, TLS admission, scoped-CA and enrolled-leaf callbacks. Failed loading publishes no partial table. Explicit retry can recover an unconfigured process; it cannot replace an already published policy. +- **Opt-in:** `DM_NETWORK=nextendo` enables the service boundary explicitly, including fail-closed behavior without a usable policy. `DM_NETWORK=auto` enables Nextendo only when `DM_NEXTENDO_ROUTES` is nonempty; without a profile it retains ordinary local DNS and local sockets. An explicitly supplied invalid path still fails closed rather than silently becoming unrestricted. LAN/LDN modes do not enable the online account or service policy. The optional `dm_bcat_online_enabled()` capability additionally requires a fully published nonempty profile; it performs no account or network request. +- **Private configuration:** `DM_NEXTENDO_ROUTES` names an absolute local TSV. A directory, table and referenced DER file must not be symlinks or group/world-writable; owners, regular-file types, lengths and SHA-256 are checked. V1 starts with `NXNEXTENDO_ROUTES_1` and has five tab-separated fields: logical host, IPv4 address, TLS verification name (or `-`), DER filename (or `-`), SHA-256 (or `-`). V2 starts with `NXNEXTENDO_ROUTES_2` and prepends `exact`, `suffix`, `label`, `pinned-exact` or `pinned-address`. `@host` preserves the matched logical name for TLS. Longest exact/label/suffix precedence is deterministic. Leaf enrollment is exact-only; numeric aliases cannot authorize a new identity or certificate. Supply provider endpoint facts and trust separately; no enrollment is downloaded here. +- **Profile:** `scripts/build_ipa_from_nsp.py --platform mac --nextendo` writes the public profile for one game and puts it in the run command (services.md, *A game online on Nextendo needs its route profile and Nextendo's game patch*). +- **Composition:** a cancellable `GetHostByNameCancel` adapter must use the same `net_resolver_name` admission before its numeric fast path or native DNS job. Otherwise that ABI could bypass the policy enforced by `GetAddrInfo`. The separate cancellation contribution and this provider contribution must retain that shared boundary when stacked. +- **Check:** the route fixtures exercise complete/invalid/partial tables, ownership/permissions, hashes, DNS/NSD normalization, ABI pointer layouts, canonical logical names, precedence, immutable publication, explicit recovery and actual loopback TLS with scoped CA/enrolled-leaf/numeric handoff. `t_online_policy` proves that unconfigured AUTO keeps local DNS, configured AUTO consults the provider, explicit Nextendo fails closed and negative admission preserves the previous guest errno. + +### Account and social providers + +- **Symptom:** a service transport works but the SDK has no usable account identity/token or friends snapshot. +- **Cause:** a saved OAuth social token is not a NEX game credential, and a desktop authorization workflow is not part of the service ABI. +- **Fix:** an embedding host registers `dm_nextendo_set_credential_provider` before guest startup. The callback copies a bounded schema-1 document from its already authorized private storage; it must not open UI or wait for user authorization. There is no implicit Keychain/document reader, command-line credential, child preflight process or browser flow. Without a provider, availability is false and credential operations fail normally. Disabled modes never call the provider. The local user/24-byte host UserHandle contract remains unchanged; online hooks check both the issued handle and actual local UID. +- **Credential contract:** the document contains `schema_version: 1`, `token_kind: "nex"`, the provider's original `nx2` proof, an `identity` object (`pid` and `username`), numeric `created_at`/`expires_at`, and a bounded string `scopes` array. Local checks enforce canonical proof encoding/shape, matching identity and coherent unexpired times. The host cannot verify the provider's private HMAC; the service authenticates that original proof. A syntactically coherent local record is not evidence of server login. OAuth-only, missing, malformed, incoherent and expired records are rejected. Never publish this document or put it in an environment variable. +- **Game token:** `dm_nextendo_set_game_version` supplies the installed version; otherwise the bundle's version is read. The ID token has the shape Nextendo's own clients send (Ryujinx-Nextendo `GenerateIdToken`, Mush8 `id_token`): kid `nextendo-baas-key-1`, type `id_token`, Nintendo BaaS's issuer, audience and certificate URL, random user, device and device-account IDs fixed for the process, `hm` (the online-membership claim) set, the unchanged NEX proof in `nnex` and the version in `tv`. The server authenticates the NEX proof. The RSA signature is the process's own key, which Nextendo does not check (Mush8 sends random bytes there), so it never stands in for the proof. A real game update is still needed where the provider requires one. +- **Lifecycle:** account/friend async contexts use owned state, real operation results, generation-checked cancellation, move/swap/destruction and lifetime-bound system events. Guest event construction remains on the callback-capable HLE path; blocking service methods use WAIT gates. Pending/destroyed contexts do not publish successful results or signal reused event bindings. +- **Social data:** the bounded native HTTPS boundary admits only the canonical provider's `me`, `friends` and `presence` resources. It disables cookies, credential storage and redirects and retains normal system TLS. Snapshots validate schema, bounds and identity, expire on their monotonic cache deadline and remain owned by each caller. Friend/Presence object writes are admitted only after verifying SDK constructor/getter semantics; unknown layouts fail instead of guessing. Invitations and unsupported profile operations remain unavailable. A user-facing authorization/settings interface belongs in an embedding application. +- **Check:** I used synthetic unauthenticatable NEX-shaped records and an injected HTTP transport to verify negative credential cases, correct output bounds/identity, local signatures, provider absence, disabled modes, real async result/event/cancel/reuse semantics, friend layouts and malformed/identity-changing social responses. These fixtures do not establish real server authentication or a playable online match. + +## Validation and limits + +From an Apple-silicon checkout, with a target-compatible static crypto prefix: + +```sh +make -C dm/host/tests GAME=010015100B514000 ssl ssl-sanitize +make -C dm/host/tests GAME=010015100B514000 nsd nsd-sanitize online-policy online-policy-sanitize +make -C dm/host/tests GAME=010015100B514000 nextendo-routes nextendo-routes-sanitize nextendo-x509 nextendo-x509-sanitize +make -C dm/host/tests GAME=010015100B514000 nextendo-account nextendo-account-sanitize nextendo-api nextendo-api-sanitize nextendo-social nextendo-social-sanitize +``` + +`DM_SSL_TRACE=1` enables at most 128 state events with numeric fields and fixed verify failure labels, and preserves errno. It never prints names, addresses, pointers, certificates, credentials or stream contents. `DM_SYSTEM_DATA_DIR` can point at the player's private original system resources for the certificate store (`0100000000000800/files/ssl_TrustedCerts.bdf`); without it the host reads the CertStore archive's file from `DM_SYSTEM_DIR`'s `sysdata/0100000000000800/` (the iOS app's `Documents/system`). None is distributed here. With no store file in either place, a stand-in CA set with `dm_ssl_set_builtin_fallback` answers the built-in requests under each ID asked for: in Nextendo mode, the service profile's CA (`hle_nextendo_routes.c`), so the sign-in is all a game's own TLS needs. A store that is there but rejected still fails. The first outcome of each kind is logged (`ssl: certificate store: ...`, which place and how many certificates, or why none), and every built-in certificate request once (`ssl: built-in certificates ...`, IDs and result only). + +In my originating fork I validated the Mario Kart 8 Deluxe 4.0.1 online connection path on Mac (not a completed Nextendo race), a Smash 13.0.5 arena on Mac, and Splatoon 2 EUR 5.5.2 reaching its lobby and Territorial queue. Those configurations used separately reviewed service trust policies; no observed leaf is part of this contribution. I did not complete a Splatoon match. These historical tests do not qualify every game, iOS online, a new upstream shader chain or this rebased extraction. I have not repeated the five-game graphical regression on this backend-only branch; the no-GUI fixtures, HLE registry and Apple compile checks are separate evidence. diff --git a/docs/reference/packing.md b/docs/reference/packing.md index d3f7b19079..6725eec8b3 100644 --- a/docs/reference/packing.md +++ b/docs/reference/packing.md @@ -85,6 +85,13 @@ ## Build tools +### An uncached Nextendo CA download returns HTTP 403 + +- **Symptom:** a Nextendo build with no cached provider CA stops while preparing its service profile with `HTTP Error 403: Forbidden`. +- **Cause:** the Git server's web raw link refuses the download. +- **Fix:** fetch the same file and commit through Forgejo's raw API without following redirects. The DER SHA-256 check and per-route trust still apply. +- **Found on:** an uncached public CA fetch and a network-free service profile fixture. + ### Stopping a build left its tools running - **Symptom:** after the NSP script was stopped in Spyder (its interrupt), or by a front end's SIGTERM, the tool it was running went on: a shader build or `build_ipa.sh`'s `xcodebuild` kept the CPU busy and wrote into the build folder that the next build reads, and the script could wait for it with no end. A regression run (`regress.py`) stopped during a shader build whose direct child ignored SIGTERM for 10 s left the build's workers running. A tool's child still writing after the tool's own exit was taken for a finished step. diff --git a/docs/reference/services.md b/docs/reference/services.md index b22d43fbd4..6183104e82 100644 --- a/docs/reference/services.md +++ b/docs/reference/services.md @@ -1211,7 +1211,7 @@ Most service calls can be found before they crash, before the first boot or the ### Account, friends, play data and Nintendo Account calls - **Symptom:** a null read at `sdk+0x336ccc` in `pdm::QueryApplicationPlayStatistics` (Pokémon Sword, the second boot); undefined `nn::account::` / `nn::friends::` imports with no hook, found from the import list ([Listing a game's unhooked imports before they are met](#listing-a-games-unhooked-imports-before-they-are-met)) before they were met. -- **Fix:** hooked (`hle_account.c`, `hle_friends.c`, `hle_offline.c`): `account::ListAllUsers`; `account::PushOpenUsers` (nothing to hand over); `account::LoadCachedNintendoAccountInfo` (fails: no Nintendo Account; Big Brain Academy then skips the birthday and country getters); `friends::GetBlockedUserList`, `DeclareOpen` / `DeclareCloseOnlinePlaySession` (unavailable); `friends::StartFacedFriendRequest` / `StartSendingFriendRequest` (fail); the Nintendo Account request's `GetAuthorizationCode` and `GetState` (both fail, as `GetIdToken`); `pdm::QueryApplicationPlayStatistics`, which asks how often this user launched two other games and reads only the launch count, so each is never played. +- **Fix:** hooked (`hle_account.c`, `hle_friends.c`, `hle_offline.c`): `account::ListAllUsers`; `account::PushOpenUsers` (nothing to hand over); `account::LoadCachedNintendoAccountInfo` (offline it fails, as no Nintendo Account is linked, and Big Brain Academy then skips the birthday and country getters; in Nextendo mode it loads, and the host answers the four getters: the Nextendo account's country, else the device's region, and the birthday picked in the launcher, else 2000-01-01); `friends::GetBlockedUserList`, `DeclareOpen` / `DeclareCloseOnlinePlaySession` (unavailable); `friends::StartFacedFriendRequest` / `StartSendingFriendRequest` (fail); the Nintendo Account request's `GetAuthorizationCode` and `GetState` (both fail, as `GetIdToken`); `pdm::QueryApplicationPlayStatistics`, which asks how often this user launched two other games and reads only the launch count, so each is never played. - **Found on:** [Super Mario 3D World + Bowser's Fury](../../dm/games/010028600EBDA000/README.md) (SDK 10, `ListAllUsers`); [Octopath Traveler 0](../../dm/games/01005270232F2000/README.md) (`PushOpenUsers`); [DRAGON QUEST XI S](../../dm/games/01006C300E9F0000/README.md) (the friends calls); [DRAGON QUEST VII Reimagined](../../dm/games/0100A9D01C446000/README.md) (the Nintendo Account request); [Pokémon Sword](../../dm/games/0100ABF008968000/README.md) (SDK 7, `pdm`); [The Great Ace Attorney Chronicles](../../dm/games/010036E00FB20000/README.md) (SDK 10.4.1: the friend requests); [Big Brain Academy: Brain vs. Brain](../../dm/games/0100620012D6E000/README.md) (SDK 11.4.3: `LoadCachedNintendoAccountInfo`). - **Note:** [Super Mario Odyssey](../../dm/games/0100000000010000/README.md)'s `account::OpenPreselectedUser` and `account::GetLastOpenedUser` are in [SDK calls that open a system service through sm](#sdk-calls-that-open-a-system-service-through-sm); SDK 6's `OpenPreselectedUser` in [SDK 6's `account::OpenPreselectedUser` returns a Result](#sdk-6s-accountopenpreselecteduser-returns-a-result); SDK 4's `GetBlockedUserList` without a `Uid` in [SDK 4's `friends::GetBlockedUserList` without a `Uid`](#sdk-4s-friendsgetblockeduserlist-without-a-uid); the save thumbnail calls in [Directory, file data cache and save-thumbnail calls](#directory-file-data-cache-and-save-thumbnail-calls). @@ -1293,6 +1293,108 @@ Most service calls can be found before they crash, before the first boot or the - **Check:** `t_net_eventfd` (`make -C dm/host/tests GAME=<id> run`). - **Found on:** Minecraft (Bedrock Edition, 1.21.120). +### A Nextendo account needs a sign-in on the Mac + +- **Symptom:** in Nextendo mode a game finds its network service account unavailable, and the log says `nextendo: no game credential`. +- **Cause:** the online backend (`hle_nextendo_apple.m`) takes the account from a credential provider the embedding app installs, and reads nothing itself. The host had none, so no game token was ever available. +- **Fix:** `dm/tools/nextendo_login.m` signs the Mac in: Nextendo's sign-in page in the browser (OAuth with PKCE, a `127.0.0.1` redirect), then the refresh token in a private file (`DM_NEXTENDO_LOGIN_DIR`). The host's provider (`hle_nextendo_login_apple.m`; the iPhone app signs in on its settings screen, `dm/ios/Sources/NextendoSignIn.m`) turns it into a fresh game token when a game asks, and builds the record from the token's own payload, so the backend's identity and expiry checks see what Nextendo issued. A failed fetch is retried after 30 s and the account stays unavailable meanwhile. The sign-in is MIT. It signs in as the OAuth client the build names: `DM_NEXTENDO_CLIENT_ID` on the Mac, `DMNextendoClientID` in the iPhone app's Info.plist (`build_ipa.sh` writes it from the same variable). Without one nobody can sign in and the error says so; a builder registers a public application at nextendo.network/developers. The game token must belong to the signed-in account (`/api/oauth/userinfo`). Build the tool with `make -C dm/host nextendo_login`, then run `dm/host/nextendo_login sign-in`; `status` and `sign-out` do what they say. +- **Check:** `make -C dm/host/tests GAME=<id> nextendo-account` (the record passes the backend's decoder; the stored sign-in is owner-only and no link stands in for it; the tool compiles). +- **Found on:** Super Mario Bros. Wonder 1.2.1 online, on an iPhone. Nextendo issues the game token only to an account with a confirmed e-mail and a linked Discord account. + +### A game online on Nextendo needs its route profile and Nextendo's game patch + +- **Symptom:** with `DM_NETWORK=nextendo` and a sign-in, the game still cannot reach Nextendo: every Nintendo host name is refused (no `DM_NEXTENDO_ROUTES`), or the game connects and then fails because its own code still expects Nintendo's servers. +- **Cause:** the backend routes only the hosts a profile names and trusts only the provider CA the profile carries (`hle_nextendo_routes.c`), and the repository shipped no profile. Some games also need a small patch to their own code before they talk to Nextendo; Nextendo publishes these for exact builds as a signed catalog (Super Mario Bros. Wonder 1.2.1 has one, an NPLN game). +- **Fix:** `scripts/build_ipa_from_nsp.py --nextendo` (`--platform ios` or `mac`) does both, after NX-Port-Studio's build (MIT). `dm/tools/nextendo_services.py` writes the public profile from `dm/net/nextendo-services.json` into `<id>_build/nextendo-services` (`routes.tsv`, the provider CA it downloads and checks by SHA-256, and `manifest.json`, whose identity namespaces `hle_nextendo_api_apple.m` reads). `dm/tools/nextendo_patches.py` fetches the catalog, checks its Ed25519 signature and expiry with `dm/tools/nextendo_verify.swift`, and refuses a rollback. When it lists the game's exact main build (all 32 bytes of the build ID) and every guarded byte matches, it patches a copy of main, which `patch_nso.py` rewrites into `patched_<ver>/nextendo`. With Nextendo on, the loader maps main from there (`loader.c` `nextendo_main`). Offline, LAN and LDN keep the original main, and a build Nextendo lists no patch for runs its original main online. On the Mac, the run command the build prints then has `DM_NETWORK=nextendo` and `DM_NEXTENDO_ROUTES`. The iPhone app carries the second main as module `nmain` (`gen_embed.py`) and the profile as `dm/nextendo-services`, which `main.m` hands to the host, with Nextendo as the launcher's Network default. A Mac app does not carry the second main yet, so `--nextendo` refuses `--platform mac-app`. +- **Check:** `dm/tools/tests/test_nextendo_patches.py` (synthetic catalogs: exact identity, guards, IPS32 bounds, an NSO copy with its build ID and segment hashes) and `dm/tools/tests/test_nextendo_services.py` (routes and manifest for Wonder). +- **Found on:** Super Mario Bros. Wonder 1.2.1 on an iPhone: with the catalog's patch, sign-in, the online menu, creating a room and searching for rooms work. Mario Kart 8 Deluxe 4.0.1 is listed with no patch. + +### Nextendo's NEX server presents a self-signed certificate + +- **Symptom:** in Nextendo mode, with the sign-in working, a NEX game's online menu shows an error (Mario Kart 8 Deluxe: 2306-0502). With `DM_SSL_TRACE=1` the log has the name lookup and connect to its game server (`g2b309e01-lp1.s.n.srv.nintendo.net`), then `[ssl-trace] stage=5 ... result=0x000002a2 native=-9841`: the certificate check failed. +- **Cause:** for that host Nextendo's second server (the profile's `nat` address) presents one self-signed certificate, `CN=nintendo-private-server`, with no host name in it and no chain to the provider CA. The route asked for the provider CA, so the check refused it. Mush8 accepts any certificate there; the host does not. +- **Fix:** the route is `pinned-exact` (`dm/net/nextendo-services.json` `certificateSHA256`, the certificate in `dm/net/nextendo-pins/<SHA-256>.der`). `dm/tools/nextendo_services.py` writes it, with a `pinned-address` route for the server's address, since a NEX secure server can be handed to the game by address. `hle_nextendo_x509.c` `dm_nextendo_x509_verify_pin` then takes exactly that certificate, byte for byte, still checking its dates, server purpose, key and signature strength and self-signature. The iPhone app copies every file of the profile (`main.m`). If Nextendo replaces the certificate, the same trace line comes back, and the pin needs updating. +- **Check:** `dm/tools/tests/test_nextendo_services.py` (`test_pinned_routes_carry_their_certificate`). +- **Found on:** Mario Kart 8 Deluxe 4.0.1 on an iPhone, 2026-11-14. The certificate was read from the server (RSA 2048, SHA-256, valid 2026-07-13 to 2036-07-10). A session past the pin has not run yet. + +### A NEX login refused by Nextendo carries no reason + +- **Symptom:** in Nextendo mode, past the certificate check, a NEX game's online menu shows 2306-08xx (Mario Kart 8 Deluxe: 2306-0807, `game asks to show an error (ErrorResultVariant): state 2 ... as an error code 2306-0807`). The game wrote its WebSocket upgrade to the game server, read the answer and gave up about 4 s later, with no UDP socket opened. +- **Cause:** 2306-08xx is the game's NEX authentication failing. Nextendo's game servers ask the account server whether the account may play before they accept a login (an unconfirmed e-mail, no linked Discord account, the account online on another device, a disabled account), and a refusal reaches the game as a generic NEX error. The NEX protocol has no field for the reason, so neither the game nor the log could say which it was. +- **Fix:** the host asks Nextendo itself. `hle_nextendo_login_apple.m` `dm_nextendo_login_online_check` sends the nx2 game token to `/api/online-status` (it answered 401 to the sign-in's OAuth access token) and logs `Nextendo allows online play for this account`, the refusal in words, or why it could not ask, once per change of answer. It asks once off the game's thread after the first game credential, and again when the game shows a 2306-08xx error in Nextendo mode (`hle_offline.c` `nextendo_refusal`). No token is logged. +- **Check:** none without a device; the next Mario Kart 8 Deluxe run in Nextendo mode logs the answer. +- **Found on:** Mario Kart 8 Deluxe 4.0.1 on an iPhone, 2026-11-14, with an account that plays Super Mario Bros. Wonder online. Which gate refuses it, if any, is not known yet. + +### A Nextendo build stops at "Unsupported signed patch policy" + +- **Symptom:** `scripts/build_ipa_from_nsp.py --nextendo` stops at `[5/10] Nextendo game patch` with `[RED] Nextendo game patch could not be verified, no game code was changed: Unsupported signed patch policy`, for a game whose patch did not change or that has no patch at all (Mario Kart 8 Deluxe). +- **Cause:** `dm/tools/nextendo_patches.py` `validate_catalog` refused the whole signed catalog when any one patch was in a format it does not apply. Nextendo's catalog revision 10 added a Splatoon 3 patch with `patch_version` 2, which stopped every build. +- **Fix:** `supported` names the one format the adapter applies (main module, `patch_version` 1, `nso_header_included`, `npln.ips32.v1`). `validate_catalog` still checks the signature, every patch's identity and `enabled`, and the full IPS32 records and guards of each supported patch, and leaves patches in another format alone. `apply_image` refuses a build whose own enabled patch is in another format (`Unsupported signed patch policy for this game build`), so a game is never built without the patch it needs. +- **Check:** `PYTHONUTF8=1 python -m unittest dm.tools.tests.test_nextendo_patches` (an unknown format is left alone for another game and refused for its own). +- **Found on:** the controls-12 builds of Mario Kart 8 Deluxe and Super Mario Bros. Wonder, 2026-11-15; catalog revision 10 had 22 patches, one of them `patch_version` 2. + +### A signed Nextendo patch check stops on a ZBIC module + +- **Symptom:** a Nextendo build stops while decoding compressed `main`, even when the exact build has no catalog patch. +- **Cause:** the patch adapter always used LZ4 on compressed segments, including ZBIC. +- **Fix:** use `nso.load`. No matching patch means no copy. A matching patch writes an uncompressed copy with fresh hashes and no ZBIC or segment compression flags. +- **Found on:** a synthetic ZBIC NSO with a mocked decoder, with and without a matching catalog entry. + +### Nextendo's account routes take different tokens + +- **Symptom:** in Nextendo mode the log has `[RED] nextendo: /api/me answered HTTP 401` (and `/api/friends answered HTTP 401`) while the game's own online login works. Or, after the first fix below, `[RED] nextendo: /api/profile answered HTTP 401`, `/api/history answered HTTP 401` and `online status could not be asked: Session invalide ou expirée.`, and Nextendo's site keeps showing no play time. +- **Cause:** every account request went with one token. `/api/me` and `/api/friends` answered 401 to the nx2 game token, so all of them were moved to the sign-in's OAuth access token, and the routes added later were never checked against the server. Asked with both tokens on 2026-11-15, nextendo.network answered: `/api/me`, `/api/friends`, `/api/oauth/userinfo` and a `/api/history` read take the access token only; a `/api/history` write (PUT or POST) and `/api/online-status` take the nx2 game token only; `/api/profile` answered 401 to both: the wiki's scope table puts it under the `profil` scope, which this client may ask for (its authorize page accepts it). The sign-in asks for it since 2026-11-15; a sign-in made before then still lacks it. A renewal does not end the previous access token. So the play time was read and every write refused, and the online status was never asked. Later the same day Nextendo closed history writes to every third-party app: the nx2 token got 403 `Le jeton de jeu d'une application tierce n'ouvre pas cette route`, and its developer wiki says writing the history is not open to OAuth tokens. +- **Fix:** `hle_nextendo_apple.m` `dm_nextendo_api_bearer(resource)` picks the token per route: the nx2 game token for `online-status`, and for the rest the access token the sign-in's last refresh got (`dm_nextendo_login_access`, renewed after 50 minutes, kept in memory only), the game token only without one. `/api/profile` still answers 401, so the account's Mii is not read; it would need Nextendo to take an OAuth token there. +- **Check:** `make -C dm/host/tests GAME=<id> nextendo-account` (`bearer_tests`); on a device the online-status line is `Nextendo allows online play for this account`. +- **Found on:** Super Mario Bros. Wonder 1.2.1 and Mario Kart 8 Deluxe 4.0.1 on an iPhone, 2026-11-14; the per-route answers from nextendo.network itself on 2026-11-15, with the account's own sign-in and read-only requests plus an empty history write. On a device (Mario Kart 8 Deluxe, controls-14) the online status was allowed and the history write answered 403. + +### A device clock that is off fails the Nextendo sign-in + +- **Symptom:** in Nextendo mode on a device whose time was set by hand, `nextendo: no game credential: the game token is past its expiry` though the sign-in just worked, or a game's own online login is refused while the account may play. +- **Cause:** the game token's expiry is Nextendo's time, and the id token a game hands to Nextendo's game servers carries times (`iat`, `nbf`, `exp`) they judge by their own clock. The host judged and stamped both by the device's clock, so a device far enough ahead found every new token expired, and one ahead or behind sent times the server's clock disagrees with. +- **Fix:** every answer from nextendo.network to the sign-in carries an HTTP `Date` header. `nextendo_login_apple.inc` `nxl_note_server_date` keeps Nextendo's clock less the device's (0 below 2 s, since the header has whole seconds), and the record's checks (`nxl_now`, `hle_nextendo_login_apple.m`) and the id token (`hle_nextendo_apple.m`, through `dm_nextendo_clock_offset`) use the device's clock plus that offset. An offset of a minute or more is logged as `[RED] nextendo: this device's clock is N min behind / ahead of Nextendo's`, again when its whole minutes change. +- **Check:** none without a device; a device with its clock set by hand shows the line. +- **Found on:** a review of where the host trusts the device's own state, 2026-11-14. No device with a wrong clock has been seen. + +### A Nextendo sign-in request has no total deadline + +- **Symptom:** sign-in can wait on a stalled HTTP request, or accept more data than a sign-in reply needs. +- **Cause:** the request timeout is an idle timeout, and the synchronous caller waited indefinitely for a completion that buffered the whole response. +- **Fix:** cap the total wait at 12 seconds per request, cancel on timeout and stop buffering at 64 KiB, even without a content length. +- **Found on:** synthetic HTTP replies with no completion and with advertised or streamed oversize bodies. + +### The Nextendo account's Mii and activity, and no play time + +- **Symptom:** in Nextendo mode the game's Mii list has only the six default Miis though the account has a Mii, and friends see the game's name with nothing about what the player is doing. Nextendo's site shows no play time and no games played for the game. +- **Cause:** the host sent none of it. Nextendo keeps each game's total seconds per account (`/api/history`), but since 2026-11-15 only its own emulator may write them: a third-party app's tokens are refused (see "Nextendo's account routes take different tokens"). It also keeps the account's Mii as the base64 of a Switch StoreData (`/api/profile`) and a line of activity beside the game's name (presence `app_detail`). The presence went with `app_detail` empty. +- **Fix:** at the start of a Nextendo session (`dm_nextendo_session_start` in `hle_nextendo_social_apple.m`, from `loader.c` `nextendo_main` or, when the modules loaded before the launcher set `DM_NETWORK`, from the game's first Nextendo credential in `hle_nextendo_login_apple.m`) the host asks for the account's profile. It sends no play time: a one-minute play-time sender ran from 2026-11-14 until Nextendo closed history writes, and was removed. The account's Mii joins the console's Miis in the game's database (`hle_mii.c` `mii_account_add`) when its data CRC holds and no console Mii has its create ID. Nothing is uploaded: Nextendo's site has no Mii maker, and a profile write replaces the whole profile. `app_detail` is the game's own description: `UserPresence::SetDescription` writes it into the presence's application field, NUL-terminated key and value strings in turn, under `sys_description` (Mario Kart 8 Deluxe's `PresenceAccessor::SearchKey`, `sdk+0x11c950`). +- **Check:** `make -C dm/host/tests GAME=<id> nextendo-api` (profile read; history is refused before any request) and `nextendo-social` (the description from the field, a field that does not end its strings). +- **Found on:** Mario Kart 8 Deluxe 4.0.1 and Super Mario Bros. Wonder 1.2.1 on an iPhone, 2026-11-14. On a device both games showed one minute that did not grow: Mario Kart's run had loaded its modules before the launcher set `DM_NETWORK`, so no session started, and Wonder's history requests were refused (`/api/history answered HTTP 401`, see "Nextendo's account routes take different tokens"). With the game token the write answered 403 on 2026-11-15, and the sender was removed. The account's Mii was not read on a device: `/api/profile` needs the `profil` scope, which the sign-in asks for only since 2026-11-15 and which no device run has used yet (see "Nextendo's account routes take different tokens"). + +### A Nextendo presence update holds the game's thread + +- **Symptom:** in Nextendo mode, changing menus in an online game takes a moment longer than offline, most on the first visit or on a slow network. +- **Cause:** `UserPresence::Commit` and `DeclareOpenOnlinePlaySession` / `DeclareCloseOnlinePlaySession` sent the presence to `/api/presence` and waited for the answer on the game's thread, up to the request's 15 s timeout. On a console these calls hand the presence to the friends service, which uploads it in the background, and the game is never told how the upload went. Each request also opened a new HTTPS connection. +- **Fix:** `hle_nextendo_social_apple.m` `dm_nextendo_social_publish` checks the sign-in, queues the presence and returns. One serial queue sends it and the 45 s repeats, and only the newest presence still waiting is sent. A failed send is logged once (`nextendo: presence not sent`) until one succeeds. `hle_nextendo_api_apple.m` sends every account API request through one `NSURLSession`, so the connection to nextendo.network is kept between them. +- **Check:** `make -C dm/host/tests GAME=<id> nextendo-social` (the description reaches the server after the queue drains, a refused upload is not the game's failure and the next publish is still sent). +- **Found on:** Mario Kart 8 Deluxe 4.0.1 and Super Mario Bros. Wonder 1.2.1 on an iPhone, 2026-11-14: a short delay between online menus on the first visits. Found by reading the code; the frame times in the log had no stall. + +### An online race ends in a communication error with nothing in the log + +- **Symptom:** in Nextendo mode, Mario Kart 8 Deluxe finds a Worldwide race and starts it, then shows a communication error during the race (on the second lap here) and returns to the menu. The log has no error line from the host. +- **Cause:** not known yet. The race is the game's own peer-to-peer UDP (Pia), and a peer that stops answering only times out inside the game. The host logged no socket traffic unless `DM_NET_TRACE=1`, which logs every call and is too much for a race. +- **Fix (diagnostic):** `hle_net_backend.c` watches every UDP socket in a network mode: a socket that has received datagrams and then gets none for 2 s logs `net: UDP socket <n>: no datagram for 2 s after <in> in (<out> sent so far)`, and `datagrams again after <s> s` when they come back. A host send or receive error logs `net: UDP send failed on the host: <reason>` the first time each errno appears. No addresses are logged, since the peers are other players. +- **Check:** none without a device; the next race that fails shows whether datagrams stopped arriving, stopped leaving, or the host refused a send. +- **Found on:** Mario Kart 8 Deluxe 4.0.1 on an iPhone, 2026-11-14, a Worldwide race on Nextendo. + +### `EventFd` in a network mode shares the socket numbering + +- **Symptom:** with `DM_NETWORK` set to a network mode, a game that uses gRPC (`nn::npln`) aborts in `grpc_init` as it does offline without event descriptors, or its poller never wakes while it polls its sockets. +- **Cause:** a network mode sends sockets to the transport (`hle_net_backend.c`), which numbers them from 0 in its own table, while the host's event descriptors had a second table, also from 0. In a network mode `EventFd` failed, so gRPC had no wakeup descriptor, and if it had made one, its number could have been a socket's: `Poll` goes to the transport, which knew nothing of it. +- **Fix:** in a network mode an event descriptor is a slot of the transport's socket table (`dm_net_eventfd`): one numbering for both, lowest free first, and `Poll`, `Select`, `Close` and the generation checks treat it as any descriptor. Its host descriptor is the read end of a local socket pair that holds one byte while the counter is above zero, so a poll sees it readable exactly then. Socket operations on it fail with ENOTSOCK. Offline the counter table above is unchanged. +- **Check:** `t_net` (`make -C dm/host/tests GAME=<id> run`): an event descriptor and a UDP socket in one `Poll` and one `Select`, the semaphore and nonblocking flags, a read blocked across a write, close and reuse. +- **Found on:** Super Mario Bros. Wonder 1.2.1 online (`nn::npln`), on an iPhone. + ### UDP loopback works offline - **Symptom:** New Game stays on the loading artwork with an empty progress bar while rendering and loading tips continue (Divinity: Original Sin 2). Both `nn::socket::Socket(AF_INET, SOCK_DGRAM, 0)` calls fail, so RakNet never completes initialization. @@ -1403,6 +1505,22 @@ Most service calls can be found before they crash, before the first boot or the - **Check:** 12 of 12 boots with four hosts at once reached the title, with both fixes; a host that answers at once hung 1 of 4 in the same test. - **Note:** how it was found: the hung boots' logs diverged from good ones at the save probe (`DM_FS=1`), the thread dumps showed nothing but idle waits, and `DM_PROBE` on the state machine, then `peek` lines in a hung run's `DM_CTL` file, followed the pointers to the status word (a probe on the hot path slowed the boot enough to hide the race: 8 of 8 good). +### Socket receive into write-protected tracked guest pages + +- **Symptom:** a real UDP/TCP receive returns guest `EFAULT` (14) when its otherwise valid destination belongs to a graphics-tracked read-only page. +- **Cause:** kernel `recvfrom` copyout does not execute the host's write-fault signal hook. Unlike file reads, the socket path did not invoke `dm_guest_write_prepare`. Preparing only on entry is insufficient: readiness waits and partial `WAITALL` reads let the renderer protect the pending destination again. +- **Fix:** `dm_net_recv` prepares only its remaining destination immediately before every native receive attempt. The existing dirty tracker admits only its registered ranges, unprotects them and advances their generation; it does not make an unrelated read-only/invalid mapping writable. UDP/TCP, address/flag/errno and descriptor behavior are unchanged. An `EFAULT` is not blindly retried, because a datagram might already have been consumed. +- **Check:** I reproduced the failure with the production backend and real `nvn_dirty.c`, no GPU/game: already protected TCP/UDP destinations fail without preparation; an entry-only control still fails after protection during a readiness wait. `make -C dm/host/tests GAME=010015100B514000 net-write net-write-sanitize` also checks partial stream offsets, dirty generations, preserved guest errno, unrelated read-only/`PROT_NONE`/invalid destinations, flags, closed descriptors and zero-length datagrams. Other ordinary-buffer socket fixtures provide an explicit no-tracker hook; production keeps its required registered dispatcher. +- **Limits:** this synthetic result does not establish an observed game disconnect's cause. It does not make preparation atomic with a concurrent re-protection between the hook and kernel copyout; that narrow race remains separate from the demonstrated missing preparation and wait boundary. + +### Socket option output into tracked write-protected guest pages + +- **Symptom:** `GetSockOpt` returns guest `EFAULT` (14) for an otherwise valid result buffer on a graphics-tracked read-only page. +- **Cause:** `getsockopt` writes its result through kernel copyout, which does not invoke the host's dirty-page fault handler. The adapter passed the guest output directly without the pre-write preparation used by file reads and socket receives. +- **Fix:** after validating the descriptor, translated option and capacity, I prepare only the option's native result span immediately before `getsockopt`. The output size and errno translation remain unchanged. `SetSockOpt` still reads its input without preparing it as a write; unrelated read-only, inaccessible and invalid destinations retain their real failures. There is no retry or new memory-permission policy. +- **Check:** the production backend with real `nvn_dirty.c` reproduces the failure for `SO_TYPE`, `SO_ERROR` and an eight-byte `SO_LINGER` result crossing two protected pages. `net-write` and `net-write-sanitize` check exact prepared spans, dirty generations, result lengths, canaries and preserved guest errno; invalid descriptors/options/capacities and unrelated read-only/`PROT_NONE`/invalid destinations remain rejected. A protected TCP option input still succeeds without pre-write preparation. These checks need no GPU, game, account or external network. +- **Limits:** I reproduced this in a synthetic fixture, not a game. This correction does not establish a game disconnect's cause. Preparation is not atomic with another thread re-protecting the page before kernel copyout, as in the [receive path](#socket-receive-into-write-protected-tracked-guest-pages). + ### Socket `Poll` and `Select` with nothing to wait on - **Symptom:** one thread at 100% CPU from boot, with one SVC in 99 s (`NexusRevolution Socket`, `main+0x92c7c4`, the game's network thread). @@ -1595,10 +1713,18 @@ Most service calls can be found before they crash, before the first boot or the - **Symptom:** saves dated 18:00:02 31/12/1969 (`ToCalendarTime: first conversion 2 → 1969-12-31 18:00`), and Continue, which takes the newest save, loads an older one. - **Cause:** the host failed `time::StandardNetworkSystemClock::GetCurrentTime`, and the game kept the PosixTime it had (2). A Switch keeps its network clock from its last time sync, so one that has ever been online reads it offline too. The SDK's `StandardNetworkSystemClock::now()` never calls `GetCurrentTime`: it reads the time service once its own initialized flag is set, which the host's `Initialize` take-over never sets, and returns 0 (1970) otherwise ([Ocarina of Time](../../dm/games/0400486024DEC000/README.md)'s `sdk+0x5d8490`). -- **Fix:** the network clock is the host's clock, as the user clock (`DM_FIXED_TIME` included), since the host's clock is set from the network: `GetCurrentTime`, `now()`, and the network fields of the host's clock snapshots ([below](#steady-clock-clock-snapshots-and-user-clocks)). `t_time` checks all three. Also hooked: `time::ToPosixTime` (host `mktime`), and `time::ToPosixTime` with an explicit rule (the host's zone, as for `ToCalendarTime`); `time::LoadTimeZoneRule` and the `ToCalendarTime` overload with a rule (the host's zone is used); `time::StandardNetworkSystemClock::IsAccuracySufficient` (no: the host does not know when its clock last synced). The network clock's context and the adjustable clocks follow the same rule ([below](#the-adjustable-network-clock-aborts-in-adjust)). `time::GetDayOfWeek` is a pure computation and needs nothing. +- **Fix:** the network clock is the host's clock, as the user clock (`DM_FIXED_TIME` included), since the host's clock is set from the network: `GetCurrentTime`, `now()`, and the network fields of the host's clock snapshots ([below](#steady-clock-clock-snapshots-and-user-clocks)). `t_time` checks all three. Also hooked: `time::ToPosixTime` (host `mktime`), and `time::ToPosixTime` with an explicit rule (the host's zone, as for `ToCalendarTime`); `time::LoadTimeZoneRule` and the `ToCalendarTime` overload with a rule (the host's zone is used); `time::StandardNetworkSystemClock::IsAccuracySufficient` follows the [checked kernel NTP state](#network-clock-availability-rejects-a-synchronized-host). The network clock's context and the adjustable clocks follow the same rule ([below](#the-adjustable-network-clock-aborts-in-adjust)). `time::GetDayOfWeek` is a pure computation and needs nothing. - **Reach:** `main` calls the network clock in [Breath of the Wild](../../dm/games/01007EF00011E000/README.md), [Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md), [Mario Kart World](../../dm/games/0400C3F00006E000/README.md), [Minecraft Dungeons II](../../dm/games/0100A7C01B792000/README.md), [PRAGMATA](../../dm/games/0400C76024710000/README.md), Super Mario Party and [Ocarina of Time](../../dm/games/0400486024DEC000/README.md) (`now()` too); [Pokémon Sword](../../dm/games/0100ABF008968000/README.md) and [Shield](../../dm/games/01008DB008C2C000/README.md), [Brilliant Diamond](../../dm/games/0100000011D90000/README.md) and [Animal Crossing: New Horizons](../../dm/games/01006F8002326000/README.md) import it. - **Found on:** [Divinity: Original Sin 2](../../dm/games/010027400CDC6000/README.md) (SDK 8.2.0; first brought up in DroidPlay Core, an Android fork that shares this host, from [PR #2359](https://github.com/seedds/nxnative/pull/2359): the network clock); [13 Sentinels: Aegis Rim](../../dm/games/01003FC01670C000/README.md) (SDK 11, `ToPosixTime`); [Monster Hunter Rise](../../dm/games/0100B04011742000/README.md) (SDK 11, the rest); [Octopath Traveler 0](../../dm/games/01005270232F2000/README.md) (`GetDayOfWeek`); [Pokémon Legends: Z-A](../../dm/games/0100F43008C44000/README.md) (19.3.11, `ToPosixTime` with an explicit rule, found in the imports before it was met). +### Network clock availability rejects a synchronized host + +- **Symptom:** the game reports that it cannot load its current calendar even when the data is present and the host has an accurately synchronized clock. +- **Cause:** the network-clock getter and accuracy query always failed; the availability task signaled shared static event storage and returned failure without consulting the clock. Reading its finish event could also signal it before a task started. +- **Fix:** for `IsAccuracySufficient` and the availability task, `hle_network_clock.c` reads the host kernel's NTP discipline using `ntp_gettime`, requiring `TIME_OK`, valid timestamps and nonnegative maximum/estimated error of at most one second. User time, fixed-clock overrides and a network mode are not synchronization evidence. Missing, stale or inaccurate kernel state fails. The clock's time itself (`GetCurrentTime`, `now()`) is the host's clock, as [above](#time-zone-rules-calendar-conversion-and-the-network-clock): a Switch reads its network clock unsynchronized too. An opaque bounded task registry owns a separate SDK-created event per object: initialization leaves it unsignaled, `StartTask` records the actual query result before signaling its binding lifetime, and `GetFinishEvent` only returns the event. Destruction closes the SDK event; reused object/handle storage cannot accept a stale completion. Contended service locks release the caller's guest core while an SDK callback performs a same-core handoff. +- **Checks:** the synthetic kernel-state fixture uses production thread/event/SVC bindings to cover success, error/precision boundaries, independent clear modes, restart, destruction/reuse, capacity and concurrent callers, plus the pinned-peer SDK callback handoff. It opens no network connection, changes no system clock and consumes no game or account data. +- **Found on:** I traced this failure in my private Splatoon 2 EUR 5.5.2 bring-up (SDK 3.4.1). The calendar warning disappeared with the checked clock implementation; that observation does not establish an online match or qualify an upstream game profile. + ### The C library's local time is UTC, as on a Switch - **Symptom:** times a game shows through the C library are off by the host's UTC offset: Hades II's load screen dated a save made at 01:44 KST (UTC+9) 16:44 the day before, its UTC time. The save file itself holds the right time. @@ -1896,6 +2022,47 @@ Most service calls can be found before they crash, before the first boot or the - **Fix:** `hle_vi.c` answers as a Switch 2 does: in handheld mode its own 1080p screen; in console mode the largest of the four that the display the game is shown on holds, as a docked Switch 2 does with its TV. The display's size comes from the front end (`front_display_pixels`: on the Mac the window's screen in its current mode, an iPhone's or iPad's screen), 1080p when it is not known. The host logs the answer once. - **Found on:** [Fire Emblem Fortune's Weave](../../dm/games/04007EF01F8AE000/README.md): its DLSS output is 2048x1152 for 1440p and for 4K, from 1024x576; for 1080p it renders 960x540 into 1920x1080, a fifth fewer pixels at each stage, and the output matches the screen. +### Opt-in native LAN sockets and LDN over IP + +- **Symptom:** a native port cannot create or join a game's LAN or local-wireless room because its socket and LDN service hooks always return unavailable. +- **Cause:** local IP LAN and Horizon LDN are separate protocols. A socket transport alone supplies neither LDN membership/events nor the local play-history registration key that Mario Kart checks during mesh setup. +- **Fix:** `DM_NETWORK=auto` enables local sockets and LDN independently, selected by the game menu. `lan` or `ldn` can restrict the path; unset, unknown and `offline` retain offline behavior. `hle_net_backend.c` translates the two Horizon socket ABIs to native IPv4 TCP/UDP with generation-safe descriptor borrowing, real adapter information, bounded discovery queues and explicit error translation. `HLE_FORCE_WAIT` publishes an immutable guest register frame on the thread's separate gate stack before blocking on the large host stack; nested native waits retain that outer frame. `hle_ldn.c` owns scan/host/station membership and events over the public ldn_mitm wire. Online account, friends, NSD and TLS fallbacks remain upstream's offline implementations. +- **Discovery:** native broadcast remains available where the OS permits it. Verified Pia queries on UDP 30000 and LDN scans on UDP 11452 can also use bounded unicast discovery on the real contiguous /20-or-narrower adapter subnet. Ordinary payloads are never fanned out. A manually entered address is not required on supported local networks. `DM_NETWORK_INTERFACE` chooses an actual adapter; `DM_NET_DISCOVERY_PEER` is an optional advanced override. iOS still requires local-network permission. Without Apple's multicast entitlement, call `dm_net_set_multicast_allowed(0)` before guest startup (the iOS default); this bridge does not grant that entitlement. +- **Local identity:** `DM_SYSTEM_DATA_DIR/010000000000000e/files/play-history.keyring` privately supplies the eight signing resources. Nothing is compiled into the host. An embedding application may instead register `dm_friends_history_set_key_provider` before startup. The original bounded decoder can extract this resource from the owner's decrypted friends NSO: `dotnet run --project dm/tools/friends_keyring -- <private-friends.nso> <new-private-output>`. Place the output at the path above; keep it out of source control. Missing or unsupported resources fail, clear the output key and do not invent an online identity. UUIDs are persisted atomically per local user under `DM_ROOT/friends-history`. No firmware or signing material is supplied with the project. +- **Checks:** `make -C dm/host/tests GAME=0100152000022000 local-network-tests` checks the real register/SIMD ABI and an 8 KiB guarded guest stack, TCP/UDP and both resolver layouts, two-process LDN discovery/join/rejoin/disconnect, event close/reuse, malformed packets, deterministic fuzz input, concurrent UUID creation and synthetic HMAC vectors. The same target accepts `SAN='-fsanitize=address,undefined -mllvm -asan-globals=0 -fno-omit-frame-pointer' B=build/local-asan`. `dotnet run --project dm/tools/tests/friends_firmware_fixture/ --configuration Release` tests only synthesized NSO layouts. `dmhost --validate-hle` validates the entire linked takeover table without a game or credentials. +- **Hardware report:** I tested Mario Kart 8 Deluxe 3.0.5 LAN and LDN play across native macOS/iOS ports and a physical Switch on October 31, 2026, in my originating fork. My modified console used a compatible LDN module. I completed a Mac/Switch LAN race and checked iPhone LAN hosting and joining. These results do not newly qualify this rebased upstream branch or every peer pairing. Built-in LAN can work with stock consoles that support that game mode; IP LDN needs a compatible module and is not direct proprietary local-wireless radio support. +- **Found on:** [Mario Kart 8 Deluxe](../../dm/games/0100152000022000/README.md) 3.0.5. Other games, IPv6, scatter/gather socket calls, Internet matchmaking and stock-console radio LDN remain outside this validation. + +### SDK DNS cancellation cannot retire an in-flight lookup + +- **Symptom:** the SDK's cancellable `GetHostByName` path reaches an unavailable resolver service or cannot retire its pending lookup when canceled or finalized. +- **Cause:** the native resolver had no cancellation identity or operation lifetime. A synchronous `getaddrinfo` call cannot implement the SDK's independently canceled host-name query; a cancellation flag alone would leave its native work and late completion alive. +- **Fix:** the cancellable C/C++ aliases use bounded IPv4 `DNSServiceGetAddrInfo` operations with the system's finite DNS timeout. Each reference is created, dispatched and deallocated on one serial queue. A cancellation ID is independent of a socket and reserves no job slot until resolution starts. Queries own their copied name, result batch and completion references; cancellation targets the current job generation, not a later query that reuses its ID. Finalization fences new jobs while retiring existing references. Native waits release the guest core, and blocking HLE entry preserves the guest register frame. Numeric addresses need no DNS request; unconfigured/offline networking still fails before starting one. The existing synchronous modern/legacy `GetAddrInfo` APIs are unchanged. +- **Checks:** original synthetic Apple callbacks cover batched answers, negative DNS results and retained errno, real API errors, cancellation before/after completion, late callbacks, ID reuse/exhaustion, registry capacity, concurrent callers and finalization. The optional `resolver-live` target uses only `localhost`; it is not part of offline CI. No provider, account data, routing override or authorization UI is included. +- **Found on:** I isolated this resolver path during my private Splatoon 2 EUR 5.5.2 bring-up (SDK 3.4.1). These backend fixtures do not qualify a game, an Internet service or a completed online match. +### gRPC's name lookup and reads fail before its first socket + +- **Symptom:** in a network mode, Super Mario Bros. Wonder's online menu shows error 2321-4992 (gRPC's UNAVAILABLE) on its first NPLN request. The log has gRPC's event descriptors and polls, but no socket, connect or name lookup. +- **Cause:** `nnsocketGetAddrInfo` returned EAI_FAIL for any SDK that exports both C++ `GetAddrInfo` overloads, because the host could not tell which result layout the C call wants. Wonder's SDK exports both. In Wonder 1.2.1's `sdk`, `nnsocketGetAddrInfo` (`sdk+0x1481c0`) branches through the PLT to the plain-`addrinfo` overload that takes resolver options. `DNSSerializer::FromBufferInternal<addrinfo>` (`sdk+0x1493f0`) stores the address at +0x20, and the `nn::socket::AddrInfo` one (`sdk+0x148f60`) stores it at +0x18. Past the lookup, gRPC's TCP endpoint reads and writes only through `RecvMsg` and `SendMsg`, which failed as unsupported. +- **Fix:** `hle_offline.c` gives the C resolver the plain `addrinfo` layout whenever the SDK has that overload, the `AddrInfo` layout only when it lacks it, and fails when it has neither. `RecvMsg` and `SendMsg` scatter and gather through one host buffer, using Horizon's 0x30-byte `msghdr` (FreeBSD's: SDK 16's `detail::RecvMsg`, `sdk+0x14cf70`, copies those 0x30 bytes into an `mmsghdr`). A receive reports no ancillary data, and a send that carries some fails with EOPNOTSUPP instead of dropping it. The buffer holds at most 16 MiB: a longer message on a stream socket moves in part, as a real socket may move less than asked, and a datagram that long fails with EMSGSIZE. A datagram longer than the iovecs is cut to them and reported with `MSG_TRUNC`. In a network mode every lookup is logged with its name and result, in red when it fails. Resolver options are logged once per key: setting one is accepted but not applied, and reading one fails. +- **Checks:** `t_net` gathers two iovecs into one UDP datagram to a native peer, scatters a reply across two with its sender's address, refuses ancillary data and a negative iovec count, fails an oversized datagram with EMSGSIZE, reports `MSG_TRUNC` for a datagram longer than the iovecs, and gives an SDK that exports both layouts the plain `addrinfo` one. +- **Found on:** [Super Mario Bros. Wonder](../../dm/games/010015100B514000/README.md) 1.2.1, on an iPhone. This is the first failure on its online path; it does not qualify a completed online session. + +### gRPC gives up a connection on a stale errno + +- **Symptom:** in a network mode, the game opens its socket and connects, then closes the socket without sending anything. Super Mario Bros. Wonder's online menu shows 2321-4992, and its gRPC reports `tcp_client_posix.cc:299` "Address family not supported by protocol". +- **Cause:** on Horizon, `nn::socket`'s errno is the C library's. `detail::SetLastErrno` and `GetLastErrno` write and read `*__errno_location()`, and code such as gRPC's reads `errno` itself. The host kept only its own copy. Wonder's gRPC sets errno to 97 (EAFNOSUPPORT) when it falls back from IPv6 (`main+0xb61480`), then reads errno after its non-blocking connect (`main+0xb61e38`). It took that stale 97 for the connect's EINPROGRESS and gave up the address. +- **Fix:** every socket hook that fails also writes the game's errno through its `__errno_location`, on the game's thread at the hook boundary. `nn::socket::GetLastErrno` reads it in a network mode. A game without `__errno_location` keeps only the host's copy. +- **Checks:** `t_net` gives the test its own errno cell. A failed socket call sets it, and `GetLastErrno` reads it back. +- **Found on:** [Super Mario Bros. Wonder](../../dm/games/010015100B514000/README.md) 1.2.1, on an iPhone, where sign-in, creating a room and searching for rooms then worked over Nextendo. + +### Optional calendar data is stale or absent at the first guest read + +- **Symptom:** a calendar-dependent title can boot with no delivery data or read an older snapshot before an asynchronous refresh finishes. +- **Cause:** the original offline host had no BCAT delivery backend; preparing a cache once does not make a later online launch current, and replacing loose files during a session can mix versions. +- **Fix:** I check an explicitly configured calendar recipe on the pre-guest boot thread with a shared 12-second network deadline. I authenticate eligibility with the signed catalog, validate every downloaded resource and select one immutable read-only overlay before SDK initialization. Failure retains the last validated snapshot and leaves freshness unconfirmed. Missing profile/provider/verifier is offline with zero HTTP requests; missing cache remains unavailable. Later real synchronization jobs change future delivery opens without changing that session's RomFS overlay. I describe the trust boundaries, provider hook, tool API and checks in [Optional BCAT calendar delivery](nextendo-bcat.md). +- **Found on:** Splatoon 2 EUR 5.5.2 in my originating fork; I reached its Mac lobby and Territorial queue, not a completed match. I have not qualified this newly rebased upstream branch or other regional executables; see [the backend scope discussion](https://github.com/seedds/nxnative/issues/951). + ### A game that decodes its code at run time - **Symptom:** `registered NROs not found` from `nro_collect.py` in a game whose RomFS has an NRR, or `[RED] ro::LoadModule: no rewritten NRO with SHA-256 …`. `main` is small (about 600 KB of code) beside a data segment of random-looking bytes. diff --git a/docs/settings.md b/docs/settings.md index b24b562e91..22e74d2043 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -3,7 +3,7 @@ The screen before the game starts shows the settings the game supports. A setting that only matters while another is on appears under it and disappears when that one is turned off. Tap **Play** to start; the app remembers your choices for the next start. All settings are on one scrollable screen, under **Game**, **Controls** and **Performance**. Tap a menu or move a slider there; no settings page needs opening. **Upscaling** is in **Game**, beside **Console mode**. A Mac app shows the same settings in a [window of its own](#the-mac-settings-window). - [Tested defaults](#tested-defaults) -- [Game](#game): [Frame rate](#frame-rate), [Render scale](#render-scale), [Console mode](#console-mode), [Upscaling](#upscaling), [Game's upscaler](#games-upscaler), [Game language](#game-language), [Picture](#picture), [Rotation](#rotation), [Frame-rate counter](#frame-rate-counter) +- [Game](#game): [Frame rate](#frame-rate), [Render scale](#render-scale), [Console mode](#console-mode), [Upscaling](#upscaling), [Game's upscaler](#games-upscaler), [Game language](#game-language), [Picture](#picture), [Rotation](#rotation), [Frame-rate counter](#frame-rate-counter), [Network](#network) - [Controls](#controls): [Touch feedback](#touch-feedback), [Game rumble](#game-rumble), [Rumble strength](#rumble-strength), [Rumble cutoff](#rumble-cutoff), [Press a button to join](#press-a-button-to-join) - [Performance](#performance): [Frame buffering](#frame-buffering), [Metal 4 pipelines](#metal-4-pipelines), [Pipeline prebuild](#pipeline-prebuild), [Encode thread](#encode-thread), [Hold frames when late](#hold-frames-when-late), [Performance HUD](#performance-hud), [Reset to tested defaults](#reset-to-tested-defaults) - [The Mac settings window](#the-mac-settings-window): [Display mode](#display-mode) @@ -99,6 +99,16 @@ iPhone and iPad. **Automatic**, the default, turns with the device as before: la Shows the frames per second at the top left. +### Network + +How the game reaches other players. **Offline** is the default and keeps the game off the network. **LAN** and **Local wireless** play with devices on the same Wi-Fi network: LAN for games with a LAN mode, Local wireless for the Switch's local play between consoles. + +**Nextendo (online)** is offered only by an app built with `--nextendo`, and is then the default. It plays online through Nextendo, a community service that stands in for Nintendo's servers. Sign in under **Online** below the settings first. Nextendo gives a game token only to an account with a confirmed e-mail and a linked Discord account. The app keeps the sign-in in its own storage, and signing out there forgets it. + +Signing in is all a game needs to go online: the app already carries Nextendo's certificate, so there is nothing to copy onto the phone. The game takes your name, country and, when the account has one, your birthday from your Nextendo account. Under **Online**, **Birthday, if Nextendo has none** is used only when the account gives none. + +**Player name** appears below the settings while Network is anything but Offline. It is the name other players see, up to 10 characters. Leave it empty to use your Nextendo username, or Player when you are not signed in. `DM_NICK` in `Documents/env.txt` does the same, and the field then shows it without letting you change it. + ## Controls **Microphone (Mac).** Apps that support microphone input have this switch off by default. Turn it on and press Play to grant macOS access. The first enabled launch can ask even if the settings window is hidden. Choose an input device while the switch is on. Microphone gain is under Advanced settings. diff --git a/scripts/build_ipa_from_nsp.py b/scripts/build_ipa_from_nsp.py index 408f704ca6..65b5ee9561 100755 --- a/scripts/build_ipa_from_nsp.py +++ b/scripts/build_ipa_from_nsp.py @@ -2985,6 +2985,43 @@ def mac_host(py, repo, work, env, logs, g): return host, font +def nextendo_build(py, repo, exe_dir, patched, work, env, logs, g): + """--nextendo (an iPhone or Mac-only build): the game's online parts, after NX-Port-Studio's build (MIT). Nextendo's signed patch catalog (dm/tools/nextendo_patches.py, checked offline with + dm/tools/nextendo_verify.swift) patches a copy of main when it lists this exact build, and the copy is rewritten into patched/nextendo, which the host maps in place of main when Nextendo + is on (loader.c nextendo_main; the iPhone's app embeds it as module nmain, dm/ios/tools/gen_embed.py); the offline and LAN main stays as it was. Then the public service profile + (dm/tools/nextendo_services.py) goes into <id>_build/nextendo-services. Returns the profile's routes.tsv (DM_NEXTENDO_ROUTES). No account data is read or written here: the player + signs in with dm/host/nextendo_login on the Mac, on the app's settings screen on the iPhone""" + import nextendo_patches, nextendo_services + PROG.add(2); PROG.stage('Nextendo game patch', step='signed patch catalog and exact main build') + destination, source = patched / 'nextendo', work / 'nextendo-source/main' + try: + catalog = nextendo_patches.verified_catalog(repo, work / 'nextendo-catalog') + applied = nextendo_patches.prepare_nso(exe_dir / 'main', source, g.id.lower(), catalog) + except (OSError, ValueError, subprocess.CalledProcessError) as error: + raise BuildError(f'Nextendo game patch could not be verified, no game code was changed: {error}') from error + if not applied: + rmtree(destination) + PROG.end('Nextendo publishes no patch for this exact build; the host runs the original main online') + else: + key = fingerprint(('files', [repo / 'dm/tools' / f for f in ('patch_nso.py', 'nso.py', 'nso_code.py', 'nso_asm.py', 'nso_match.py', 'nextendo_patches.py')] + + patch_files(repo, exe_dir, ['main'], env.get('DM_GAME')) + [source]), applied, {k: env.get(k) for k in ('DM_PATCH_FRONT', 'DM_GAME')}) + kf = destination / 'nextendo.key' + if (destination / 'main.patched.bin').is_file() and reused(kf, key) is not None: PROG.end(f'{", ".join(applied)}, reused (inputs unchanged)') + else: + tmp = patched / '.nextendo-partial'; rmtree(tmp); tmp.mkdir() + try: + run([py, repo / 'dm/tools/patch_nso.py', source, tmp, 'main'], logs / 'rewrite_nextendo_main.log', env=env) + (tmp / 'nextendo.key').write_text(f'{key}\ncatalog revision {catalog["revision"]}: {", ".join(applied)}\n') + rmtree(destination); tmp.rename(destination) + finally: rmtree(tmp) + PROG.end(f'{", ".join(applied)} (catalog revision {catalog["revision"]}) rewritten into {destination}; gameplay with it is unverified') + PROG.stage('Nextendo services', step='public service profile') + try: services = nextendo_services.prepare(repo, g.id.lower(), work / 'nextendo-services') + except (OSError, ValueError) as error: raise BuildError(f'Nextendo service profile could not be prepared: {error}') from error + PROG.end(str(services)) + return services / 'routes.tsv' + + def mac_run(work, game, patched, host, font, msl, aoc, gfx, lang, env, logs, g, env_file='', partial=False, parts=None, jit=False, nvn_runtime=None, romfs=None): """The command that runs the game in a window with sound after a Mac-only build (PLATFORM 'mac'; docs/development.md, Build by hand (Mac), step 5): its save and temporary storage in <id>_build/run (kept from run to run), the extracted RomFS, the Mac shader libraries (msl), the DLC, the profile's shader map (a host outside dm/host does not find it beside itself; @@ -3313,6 +3350,9 @@ def parse_args(argv): ap.add_argument('--no-heap-check', action='store_true', help='a provisional profile: skip the heap check and the address region check on the Mac (the alias / heap split stays a guess); a derived profile: skip the address region check') ap.add_argument('--progress', choices=('auto', 'bar', 'lines', 'json', 'off'), help='stage lines on the console: bar = one line per stage, redrawn in place; lines = a plain line every BEAT seconds; json = newline-delimited JSON events (no prompts); off = only each stage\'s start and end ' '(default: the PROGRESS setting; auto = bar in a terminal or Spyder, lines when the output goes to a file or a pipe)') + ap.add_argument('--nextendo', action='store_true', help='--platform ios or mac: also build for online play on Nextendo: the game patch Nextendo signs for this exact build (fetched from nextendo.network), ' + 'and the public service profile. The iPhone app then offers Network: Nextendo (the default) and a sign-in on its settings screen; the Mac run command has DM_NETWORK=nextendo, ' + 'after dm/host/nextendo_login sign-in (make -C dm/host nextendo_login)') return ap.parse_args(argv) @@ -3457,6 +3497,7 @@ def main(args=None): prepare_xcode = args.prepare_xcode or PREPARE_XCODE platform = args.platform or PLATFORM if platform not in ('ios', 'mac', 'mac-app'): raise BuildError(f'PLATFORM / --platform must be ios, mac or mac-app: {platform}') + if getattr(args, 'nextendo', False) and platform == 'mac-app': raise BuildError('--nextendo is for --platform ios or mac: a Mac app does not carry Nextendo\'s patched main yet') mac = platform in ('mac', 'mac-app') # the Mac's shaders and host only: no iOS shaders, Xcode project or IPA (mac_run prints the command; mac-app packs a Mac app, mac_app) mac_pack = platform == 'mac-app' seen_shaders = SEEN_SHADERS if args.seen_shaders is None else args.seen_shaders @@ -3666,6 +3707,7 @@ def main(args=None): patched = work / f'patched_{pkg_ver}' g = rewrite(py, repo, game / 'ExeFS', patched, env, logs, g, provisional) + routes = nextendo_build(py, repo, game / 'ExeFS', patched, work, env, logs, g) if getattr(args, 'nextendo', False) else None if nd := captured_nros(patched): env = dict(env, DM_NRO_DIR=str(nd)) chain_header(py, repo, env, logs) # before any host is built if provisional or derived: # (provisional) the heap check, then the region check (both only change keys the host is built with, not the rewrite or the shader steps) @@ -3746,6 +3788,9 @@ def derive_shader_tables(reason): # called only after the optional-content or parts = {'font': font} nvn_runtime = (py, repo / 'dm/gfx/tools/dmsh_live.py') if use_nvn_runtime else None cmd = mac_run(work, game, patched, host, font, ios, aoc, gfx, lang, env, logs, g, env_file, partial=seen_shaders, parts=parts, jit=jit, nvn_runtime=nvn_runtime, romfs=romfs) + if routes: # the Nextendo application the Mac signs in as comes from the build's environment (dm/host/nextendo_login_apple.inc) + client = os.environ.get('DM_NEXTENDO_CLIENT_ID', '') + cmd = cmd.replace(' && ', f' && DM_NETWORK=nextendo DM_NEXTENDO_ROUTES={shlex.quote(str(routes))} ' + (f'DM_NEXTENDO_CLIENT_ID={shlex.quote(client)} ' if client else ''), 1) rmtree(work / 'tmp') if getattr(args, 'in_programs', False): return parts programs = None if PROGRAM_INDEX else mac_programs(args, g, parts) @@ -3774,6 +3819,9 @@ def derive_shader_tables(reason): # called only after the optional-content or if icon: ipa_env['DM_ICON'] = str(icon); say(f'app icon: {icon}') # app icon (found above) else: say(('no game icon: the NUP carries none' if nup else 'no game icon: a dump folder has no control data') + '; the home-screen icon will be blank; --icon / ICON or --fallback-icon / FALLBACK_ICON gives it one' if dump else '[RED] no game icon in the extraction (an older extraction did not save it: delete extract/ and run again); the home-screen icon will be blank') if env_file: ipa_env['DM_ENV_FILE'] = str(Path(os.path.expanduser(env_file)).resolve()) + if routes: # --nextendo: the profile into the app, and Nextendo as the launcher's Network default (build_ipa.sh, dm/games/settings.tsv) + ipa_env.update(DM_NEXTENDO_SERVICES=str(routes.parent), DM_NEXTENDO='1', DM_NETWORK='nextendo') + say('Nextendo: online play is the Network default; sign in on the app\'s settings screen (Online)') show_fps = SHOW_FPS if args.show_fps is None else args.show_fps ipa_env['DM_SHOW_FPS'] = '1' if show_fps else '0' gpus = (args.gpu or PSO_GPUS).strip()