merge: bring feat/full-installer into SK-local
Integrates the aelrynth snapshot port (main), the full installer, the tmds.dbus advisory fix and all launcher/engine work into SK-local. Conflict resolutions: - Logging: keep SK-local's level-based logging (EngineLogLevel, ShouldLog, engine.json LoggingLevel) and adopt full-installer's tagged WRN/ERR, LastIssue and per-PID logs; the Desktop rolling log is superseded. - Launcher: keep the inject-all-sessions toggle and Logging level combo alongside the new stagger/crash-relaunch/stuck-client options; the LoggingLevel is now written through EngineJsonStore.SetString. - PluginManager: keep SK-local's basename/canonical-path de-duplication, drop the default-directory scan (opt-in via PluginPaths). - Injector, installer, CI workflow, BUILD.md: take full-installer. - Solution: add DesktopLog + Loader, drop the stale Plugins/RynthAi stub. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
commit
36ffa94252
256 changed files with 62130 additions and 3382 deletions
|
|
@ -12,8 +12,14 @@ namespace RynthCore.Injector;
|
|||
public sealed class EngineInjectionService
|
||||
{
|
||||
public const string DefaultAcProcessName = "acclient";
|
||||
public const string EngineDllName = "RynthCore.Engine.dll";
|
||||
/// <summary>The DLL we actually inject — RynthCore.Loader.dll, which then
|
||||
/// loads RynthCore.Engine.dll and can later FreeLibrary + reload it.</summary>
|
||||
public const string EngineDllName = "RynthCore.Loader.dll";
|
||||
/// <summary>Legacy filename — if the user's saved path points to this, we
|
||||
/// transparently redirect to the Loader sibling in the same directory.</summary>
|
||||
private const string LegacyEngineDllName = "RynthCore.Engine.dll";
|
||||
private const string InitExport = "RynthCoreInit";
|
||||
private const string DecalInitExport = "DecalStartup";
|
||||
private const string RuntimeDirectoryName = "Runtime";
|
||||
|
||||
private const uint ProcessAllAccess = 0x001F0FFF;
|
||||
|
|
@ -22,6 +28,10 @@ public sealed class EngineInjectionService
|
|||
private const uint MemReserve = 0x2000;
|
||||
private const uint MemRelease = 0x8000;
|
||||
private const uint PageReadWrite = 0x04;
|
||||
private const uint WaitObject0 = 0x00000000;
|
||||
private const uint WaitTimeout = 0x00000102;
|
||||
private const uint WaitFailed = 0xFFFFFFFF;
|
||||
private const uint StillActive = 259;
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);
|
||||
|
|
@ -167,8 +177,32 @@ public sealed class EngineInjectionService
|
|||
else
|
||||
log("MinHook found beside engine DLL.");
|
||||
|
||||
log($"{InitExport} RVA: 0x{initRva:X8}");
|
||||
return InjectDllAndCallExport(
|
||||
targetProcess,
|
||||
resolvedEnginePath,
|
||||
initRva,
|
||||
InitExport,
|
||||
stackLabel: "RynthCore",
|
||||
successMessage: "RynthCore injected successfully.",
|
||||
log);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Injects a generic DLL into <paramref name="targetProcess"/> via remote
|
||||
/// LoadLibraryA, then calls the export at <paramref name="exportRva"/> as a
|
||||
/// new thread (entry signature: <c>uint __stdcall(void)</c> — matches
|
||||
/// LPTHREAD_START_ROUTINE). Used by both the engine path and the Decal path.
|
||||
/// </summary>
|
||||
private InjectionResult InjectDllAndCallExport(
|
||||
Process targetProcess,
|
||||
string dllPath,
|
||||
uint exportRva,
|
||||
string exportName,
|
||||
string stackLabel,
|
||||
string successMessage,
|
||||
Action<string> log)
|
||||
{
|
||||
log($"{exportName} RVA: 0x{exportRva:X8}");
|
||||
log($"Target PID: {targetProcess.Id} ({targetProcess.ProcessName})");
|
||||
|
||||
IntPtr hProcess = OpenProcess(ProcessAllAccess, false, targetProcess.Id);
|
||||
|
|
@ -177,7 +211,7 @@ public sealed class EngineInjectionService
|
|||
return InjectionResult.Failure(
|
||||
1,
|
||||
$"OpenProcess failed (error {Marshal.GetLastWin32Error()}). Try running as Administrator.",
|
||||
resolvedEnginePath,
|
||||
dllPath,
|
||||
targetProcess.Id);
|
||||
}
|
||||
|
||||
|
|
@ -186,12 +220,12 @@ public sealed class EngineInjectionService
|
|||
IntPtr hKernel32 = GetModuleHandleA("kernel32.dll");
|
||||
IntPtr loadLibAddr = GetProcAddress(hKernel32, "LoadLibraryA");
|
||||
if (loadLibAddr == IntPtr.Zero)
|
||||
return InjectionResult.Failure(1, "Could not locate LoadLibraryA.", resolvedEnginePath, targetProcess.Id);
|
||||
return InjectionResult.Failure(1, "Could not locate LoadLibraryA.", dllPath, targetProcess.Id);
|
||||
|
||||
byte[] dllPathBytes = Encoding.ASCII.GetBytes(resolvedEnginePath + "\0");
|
||||
byte[] dllPathBytes = Encoding.ASCII.GetBytes(dllPath + "\0");
|
||||
IntPtr remoteStr = VirtualAllocEx(hProcess, IntPtr.Zero, (uint)dllPathBytes.Length, MemCommit | MemReserve, PageReadWrite);
|
||||
if (remoteStr == IntPtr.Zero)
|
||||
return InjectionResult.Failure(1, "VirtualAllocEx failed for remote DLL path.", resolvedEnginePath, targetProcess.Id);
|
||||
return InjectionResult.Failure(1, "VirtualAllocEx failed for remote DLL path.", dllPath, targetProcess.Id);
|
||||
|
||||
try
|
||||
{
|
||||
|
|
@ -200,26 +234,55 @@ public sealed class EngineInjectionService
|
|||
return InjectionResult.Failure(
|
||||
1,
|
||||
$"WriteProcessMemory failed (error {Marshal.GetLastWin32Error()}).",
|
||||
resolvedEnginePath,
|
||||
dllPath,
|
||||
targetProcess.Id);
|
||||
}
|
||||
|
||||
log("[1/2] Injecting engine DLL...");
|
||||
log($"[1/2] Injecting {stackLabel} DLL...");
|
||||
IntPtr loadThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, loadLibAddr, remoteStr, 0, out _);
|
||||
if (loadThread == IntPtr.Zero)
|
||||
{
|
||||
return InjectionResult.Failure(
|
||||
1,
|
||||
$"CreateRemoteThread for LoadLibraryA failed (error {Marshal.GetLastWin32Error()}).",
|
||||
resolvedEnginePath,
|
||||
dllPath,
|
||||
targetProcess.Id);
|
||||
}
|
||||
|
||||
uint loadLibResult;
|
||||
try
|
||||
{
|
||||
WaitForSingleObject(loadThread, 10000);
|
||||
// Deep-audit finding #6 (2026-06-18): the wait's return value was
|
||||
// discarded. On a timeout (WAIT_TIMEOUT, the thread still running
|
||||
// LoadLibraryA) GetExitCodeThread returns STILL_ACTIVE (259) — that
|
||||
// was then cast straight to remoteBase and handed to a second
|
||||
// CreateRemoteThread as a call target, i.e. jumping into address
|
||||
// 0x103 + rva inside the target process. Fail closed on anything
|
||||
// but a real WAIT_OBJECT_0 signal instead of falling through.
|
||||
uint waitResult = WaitForSingleObject(loadThread, 10000);
|
||||
if (waitResult != WaitObject0)
|
||||
{
|
||||
string reason = waitResult == WaitTimeout
|
||||
? "timed out after 10s"
|
||||
: $"wait failed (result 0x{waitResult:X8}, error {Marshal.GetLastWin32Error()})";
|
||||
return InjectionResult.Failure(
|
||||
1,
|
||||
$"LoadLibraryA remote thread {reason} — aborting rather than treating an unfinished call as success.",
|
||||
dllPath,
|
||||
targetProcess.Id);
|
||||
}
|
||||
GetExitCodeThread(loadThread, out loadLibResult);
|
||||
if (loadLibResult == StillActive)
|
||||
{
|
||||
// Belt-and-suspenders: even a WAIT_OBJECT_0 signal on a handle
|
||||
// that GetExitCodeThread still reports as STILL_ACTIVE must not
|
||||
// be treated as a valid module base.
|
||||
return InjectionResult.Failure(
|
||||
1,
|
||||
"LoadLibraryA remote thread signaled but exit code is STILL_ACTIVE — refusing to use it as a module base.",
|
||||
dllPath,
|
||||
targetProcess.Id);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -230,39 +293,58 @@ public sealed class EngineInjectionService
|
|||
{
|
||||
return InjectionResult.Failure(
|
||||
1,
|
||||
"LoadLibrary returned NULL. Check engine dependencies beside the DLL.",
|
||||
resolvedEnginePath,
|
||||
$"LoadLibrary returned NULL for {Path.GetFileName(dllPath)}. Check its dependencies beside the DLL.",
|
||||
dllPath,
|
||||
targetProcess.Id);
|
||||
}
|
||||
|
||||
IntPtr remoteBase = (IntPtr)loadLibResult;
|
||||
log($"[1/2] Engine mapped at 0x{remoteBase:X8}");
|
||||
log($"[1/2] {stackLabel} mapped at 0x{remoteBase:X8}");
|
||||
|
||||
log("[2/2] Calling RynthCoreInit...");
|
||||
IntPtr remoteInitAddr = IntPtr.Add(remoteBase, (int)initRva);
|
||||
log($"[2/2] Calling {exportName}...");
|
||||
IntPtr remoteInitAddr = IntPtr.Add(remoteBase, (int)exportRva);
|
||||
IntPtr initThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, remoteInitAddr, IntPtr.Zero, 0, out _);
|
||||
if (initThread == IntPtr.Zero)
|
||||
{
|
||||
return InjectionResult.Failure(
|
||||
1,
|
||||
$"CreateRemoteThread for {InitExport} failed (error {Marshal.GetLastWin32Error()}).",
|
||||
resolvedEnginePath,
|
||||
$"CreateRemoteThread for {exportName} failed (error {Marshal.GetLastWin32Error()}).",
|
||||
dllPath,
|
||||
targetProcess.Id);
|
||||
}
|
||||
|
||||
uint initResult;
|
||||
try
|
||||
{
|
||||
WaitForSingleObject(initThread, 10000);
|
||||
uint waitResult = WaitForSingleObject(initThread, 10000);
|
||||
if (waitResult != WaitObject0)
|
||||
{
|
||||
string reason = waitResult == WaitTimeout
|
||||
? "timed out after 10s"
|
||||
: $"wait failed (result 0x{waitResult:X8}, error {Marshal.GetLastWin32Error()})";
|
||||
return InjectionResult.Failure(
|
||||
1,
|
||||
$"{exportName} remote thread {reason} — the DLL is loaded but init did not confirm completion.",
|
||||
dllPath,
|
||||
targetProcess.Id);
|
||||
}
|
||||
GetExitCodeThread(initThread, out initResult);
|
||||
if (initResult == StillActive)
|
||||
{
|
||||
return InjectionResult.Failure(
|
||||
1,
|
||||
$"{exportName} remote thread signaled but exit code is STILL_ACTIVE — refusing to trust the result.",
|
||||
dllPath,
|
||||
targetProcess.Id);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseHandle(initThread);
|
||||
}
|
||||
|
||||
log(initResult == 0 ? "RynthCoreInit returned success." : $"RynthCoreInit returned {initResult}.");
|
||||
return InjectionResult.SuccessResult("RynthCore injected successfully.", resolvedEnginePath, targetProcess.Id, initResult);
|
||||
log(initResult == 0 ? $"{exportName} returned success." : $"{exportName} returned {initResult}.");
|
||||
return InjectionResult.SuccessResult(successMessage, dllPath, targetProcess.Id, initResult);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -275,17 +357,100 @@ public sealed class EngineInjectionService
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Injects Decal's <c>Inject.dll</c> into the target and invokes its
|
||||
/// <c>DecalStartup</c> export — the same recipe ThwargLauncher's bundled
|
||||
/// injector.dll uses. Resolves the DecalStartup RVA from the on-disk PE.
|
||||
/// </summary>
|
||||
public InjectionResult InjectDecalIntoProcess(Process targetProcess, string decalInjectDllPath, Action<string>? log = null)
|
||||
{
|
||||
log ??= _ => { };
|
||||
|
||||
if (string.IsNullOrWhiteSpace(decalInjectDllPath) || !File.Exists(decalInjectDllPath))
|
||||
return InjectionResult.Failure(1, $"Decal Inject.dll not found: {decalInjectDllPath}", decalInjectDllPath, targetProcess.Id);
|
||||
|
||||
log($"Decal DLL: {decalInjectDllPath}");
|
||||
|
||||
uint decalStartupRva;
|
||||
try
|
||||
{
|
||||
decalStartupRva = GetExportRva(decalInjectDllPath, DecalInitExport);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return InjectionResult.Failure(
|
||||
1,
|
||||
$"Could not locate {DecalInitExport} export in Decal Inject.dll: {ex.Message}",
|
||||
decalInjectDllPath,
|
||||
targetProcess.Id);
|
||||
}
|
||||
|
||||
return InjectDllAndCallExport(
|
||||
targetProcess,
|
||||
decalInjectDllPath,
|
||||
decalStartupRva,
|
||||
DecalInitExport,
|
||||
stackLabel: "Decal",
|
||||
successMessage: "Decal injected successfully.",
|
||||
log);
|
||||
}
|
||||
|
||||
public InjectionResult LaunchSuspendedAndInject(
|
||||
string clientPath,
|
||||
string arguments,
|
||||
string enginePath,
|
||||
Action<string>? log = null,
|
||||
Action<int>? onProcessCreated = null)
|
||||
{
|
||||
return LaunchSuspendedAndInvoke(
|
||||
clientPath,
|
||||
arguments,
|
||||
stackLabel: "RynthCore",
|
||||
failureContextPath: enginePath,
|
||||
successMessage: "Launched AC and injected RynthCore successfully.",
|
||||
inject: (proc, perCallLog) => InjectIntoProcess(proc, enginePath, perCallLog),
|
||||
log,
|
||||
onProcessCreated);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Launches AC suspended and injects Decal's <c>Inject.dll</c> + invokes
|
||||
/// <c>DecalStartup</c>. The RynthCore engine is NOT loaded into the
|
||||
/// process — this account runs against Decal's plugin stack alone, the
|
||||
/// same way ThwargLauncher launches Decal-using accounts.
|
||||
/// </summary>
|
||||
public InjectionResult LaunchSuspendedAndInjectDecal(
|
||||
string clientPath,
|
||||
string arguments,
|
||||
string decalInjectDllPath,
|
||||
Action<string>? log = null,
|
||||
Action<int>? onProcessCreated = null)
|
||||
{
|
||||
return LaunchSuspendedAndInvoke(
|
||||
clientPath,
|
||||
arguments,
|
||||
stackLabel: "Decal",
|
||||
failureContextPath: decalInjectDllPath,
|
||||
successMessage: "Launched AC and injected Decal successfully.",
|
||||
inject: (proc, perCallLog) => InjectDecalIntoProcess(proc, decalInjectDllPath, perCallLog),
|
||||
log,
|
||||
onProcessCreated);
|
||||
}
|
||||
|
||||
private InjectionResult LaunchSuspendedAndInvoke(
|
||||
string clientPath,
|
||||
string arguments,
|
||||
string stackLabel,
|
||||
string failureContextPath,
|
||||
string successMessage,
|
||||
Func<Process, Action<string>, InjectionResult> inject,
|
||||
Action<string>? log,
|
||||
Action<int>? onProcessCreated)
|
||||
{
|
||||
log ??= _ => { };
|
||||
|
||||
if (string.IsNullOrWhiteSpace(clientPath) || !File.Exists(clientPath))
|
||||
return InjectionResult.Failure(1, $"AC client not found: {clientPath}", enginePath);
|
||||
return InjectionResult.Failure(1, $"AC client not found: {clientPath}", failureContextPath);
|
||||
|
||||
string workingDirectory = Path.GetDirectoryName(clientPath) ?? Environment.CurrentDirectory;
|
||||
string commandLine = string.IsNullOrWhiteSpace(arguments)
|
||||
|
|
@ -312,7 +477,7 @@ public sealed class EngineInjectionService
|
|||
return InjectionResult.Failure(
|
||||
1,
|
||||
$"CreateProcessW failed (error {Marshal.GetLastWin32Error()}).",
|
||||
enginePath);
|
||||
failureContextPath);
|
||||
}
|
||||
|
||||
bool resumed = false;
|
||||
|
|
@ -331,20 +496,20 @@ public sealed class EngineInjectionService
|
|||
}
|
||||
|
||||
log($"Launched AC suspended (PID {processInfo.dwProcessId}).");
|
||||
log("Launching suspended so RynthCore can patch early startup gates before AC runs its single-instance checks.");
|
||||
log($"Launching suspended so {stackLabel} can install before AC's single-instance gate runs.");
|
||||
onProcessCreated?.Invoke((int)processInfo.dwProcessId);
|
||||
|
||||
try
|
||||
{
|
||||
using var launchedProcess = Process.GetProcessById((int)processInfo.dwProcessId);
|
||||
InjectionResult injectResult = InjectIntoProcess(launchedProcess, enginePath, log);
|
||||
InjectionResult injectResult = inject(launchedProcess, log);
|
||||
ResumeMainThread();
|
||||
|
||||
if (!injectResult.Success)
|
||||
return InjectionResult.Failure(injectResult.ExitCode, injectResult.Summary, injectResult.EnginePath, (int)processInfo.dwProcessId);
|
||||
|
||||
return InjectionResult.SuccessResult(
|
||||
"Launched AC and injected RynthCore successfully.",
|
||||
successMessage,
|
||||
injectResult.EnginePath,
|
||||
(int)processInfo.dwProcessId,
|
||||
injectResult.InitResult ?? 0);
|
||||
|
|
@ -360,14 +525,14 @@ public sealed class EngineInjectionService
|
|||
return InjectionResult.Failure(
|
||||
1,
|
||||
$"Launch + inject failed: {ex.Message} ResumeThread also failed: {resumeEx.Message}",
|
||||
enginePath,
|
||||
failureContextPath,
|
||||
(int)processInfo.dwProcessId);
|
||||
}
|
||||
|
||||
return InjectionResult.Failure(
|
||||
1,
|
||||
$"Launch + inject failed: {ex.Message}",
|
||||
enginePath,
|
||||
failureContextPath,
|
||||
(int)processInfo.dwProcessId);
|
||||
}
|
||||
finally
|
||||
|
|
@ -417,6 +582,18 @@ public sealed class EngineInjectionService
|
|||
if (!string.IsNullOrWhiteSpace(explicitEnginePath))
|
||||
{
|
||||
string explicitFullPath = Path.GetFullPath(explicitEnginePath);
|
||||
|
||||
// If the user's saved path points to the legacy engine DLL, prefer
|
||||
// the Loader sibling so we get the hot-reload-capable injection
|
||||
// path. Falls through to the explicit path if the Loader isn't
|
||||
// beside it.
|
||||
if (string.Equals(Path.GetFileName(explicitFullPath), LegacyEngineDllName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
string? legacyDir = Path.GetDirectoryName(explicitFullPath);
|
||||
if (!string.IsNullOrWhiteSpace(legacyDir))
|
||||
AddCandidate(candidates, Path.Combine(legacyDir, EngineDllName));
|
||||
}
|
||||
|
||||
string? runtimeSibling = TryGetRuntimeSiblingEnginePath(explicitFullPath);
|
||||
AddCandidate(candidates, runtimeSibling);
|
||||
AddCandidate(candidates, explicitFullPath);
|
||||
|
|
@ -520,7 +697,7 @@ public sealed class EngineInjectionService
|
|||
return false;
|
||||
}
|
||||
|
||||
if (!targetProcess.Responding)
|
||||
if (!IsWindowResponding(targetProcess.MainWindowHandle))
|
||||
{
|
||||
status = "Auto-inject wait: waiting for the AC window to respond.";
|
||||
return false;
|
||||
|
|
@ -542,6 +719,23 @@ public sealed class EngineInjectionService
|
|||
}
|
||||
}
|
||||
|
||||
// Bounded replacement for Process.Responding, which is
|
||||
// SendMessageTimeout(WM_NULL, ..., SMTO_ABORTIFHUNG, 5000) under the hood —
|
||||
// up to a 5s stall per probe on a busy-but-not-yet-ghosted client. Callers
|
||||
// poll readiness on the launcher UI thread every 2s per client, so that 5s
|
||||
// window can wedge the whole launcher behind one slow AC client. 250ms
|
||||
// bounds it; a client that can't answer WM_NULL in 250ms isn't ready yet.
|
||||
private const uint SMTO_ABORTIFHUNG = 0x0002;
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern IntPtr SendMessageTimeoutW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, uint flags, uint timeoutMs, out IntPtr result);
|
||||
|
||||
private static bool IsWindowResponding(IntPtr hwnd)
|
||||
{
|
||||
if (hwnd == IntPtr.Zero) return false;
|
||||
return SendMessageTimeoutW(hwnd, 0 /* WM_NULL */, IntPtr.Zero, IntPtr.Zero, SMTO_ABORTIFHUNG, 250, out _) != IntPtr.Zero;
|
||||
}
|
||||
|
||||
private static uint GetExportRva(string dllPath, string exportName)
|
||||
{
|
||||
byte[] pe = File.ReadAllBytes(dllPath);
|
||||
|
|
@ -629,6 +823,49 @@ public sealed class EngineInjectionService
|
|||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Names that signal a Decal-style coexistence stack is loaded
|
||||
/// inside the target acclient.exe. Match is case-insensitive.</summary>
|
||||
private static readonly string[] DecalStackModuleNames =
|
||||
{
|
||||
"decal.dll",
|
||||
"UBLoader.dll",
|
||||
"Decal.Adapter.dll",
|
||||
"phatacd.dll",
|
||||
};
|
||||
|
||||
/// <summary>Names that signal RynthCore is already mapped into the target,
|
||||
/// so the watcher should treat the process as already-injected.</summary>
|
||||
private static readonly string[] RynthCoreModuleNames =
|
||||
{
|
||||
"RynthCore.Loader.dll",
|
||||
"RynthCore.Engine.dll",
|
||||
};
|
||||
|
||||
public bool IsRynthCoreLoaded(Process targetProcess)
|
||||
{
|
||||
foreach (string name in RynthCoreModuleNames)
|
||||
{
|
||||
if (IsModuleLoaded(targetProcess, name))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Inspects loaded modules in the target acclient.exe and returns
|
||||
/// the first Decal-stack module name found, or null if none are present.
|
||||
/// Informational only — used to log when we're attaching alongside Decal.</summary>
|
||||
public string? TryDetectDecalStack(Process targetProcess)
|
||||
{
|
||||
foreach (string name in DecalStackModuleNames)
|
||||
{
|
||||
if (IsModuleLoaded(targetProcess, name))
|
||||
return name;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct STARTUPINFO
|
||||
{
|
||||
|
|
|
|||
332
src/RynthCore.Injector/LaunchCommand.cs
Normal file
332
src/RynthCore.Injector/LaunchCommand.cs
Normal file
|
|
@ -0,0 +1,332 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using RynthCore.Install;
|
||||
|
||||
namespace RynthCore.Injector;
|
||||
|
||||
/// <summary>
|
||||
/// Headless "launch a configured profile + inject RynthCore" command, exposed as
|
||||
/// <c>RynthCore.Injector.exe --launch</c>. Mirrors the essential bits of the
|
||||
/// Avalonia launcher's RynthCore launch path (resolve account+server profiles
|
||||
/// from %APPDATA%\RynthCore\appsettings.json, build AC auto-login args, launch
|
||||
/// suspended + inject the loader, and write the per-PID launch_context_*.json
|
||||
/// the engine reads for character auto-select) — without the GUI, so a test
|
||||
/// harness can start a client with one call.
|
||||
///
|
||||
/// Defaults to the private RynthCore AC copy (C:\Games\RynthCore\AcClient) so it
|
||||
/// never contends on DAT file locks with Decal/ThwargLauncher clients running
|
||||
/// out of C:\Turbine\Asheron's Call. Override with --client.
|
||||
///
|
||||
/// Usage:
|
||||
/// RynthCore.Injector.exe --launch [--account <name|id>] [--server <name|id>]
|
||||
/// [--client <acclient.exe>] [--engine <loader.dll>]
|
||||
/// [--no-login]
|
||||
///
|
||||
/// On success prints a machine-readable <c>LAUNCHED_PID=<pid></c> line and
|
||||
/// returns 0. Never prompts (safe for non-interactive shells).
|
||||
/// </summary>
|
||||
internal static class LaunchCommand
|
||||
{
|
||||
// The "bulletproof" private AC copy intended for RynthCore launches — a
|
||||
// separate DAT lock domain from the shared Turbine install.
|
||||
private static readonly string PrivateAcClientPath = Path.Combine(RynthInstallPaths.CoreDir, "AcClient", "acclient.exe");
|
||||
|
||||
// Matches LaunchAccountProfile.NoneOption — explicit opt-out of auto-login.
|
||||
private const string NoneOption = "(None — no auto-login)";
|
||||
|
||||
private static readonly JsonSerializerOptions ReadOpts = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter() }
|
||||
};
|
||||
|
||||
public static int Run(string[] args, Action<string> logToFile)
|
||||
{
|
||||
void Log(string msg)
|
||||
{
|
||||
Console.WriteLine(msg);
|
||||
logToFile($"[launch] {msg}");
|
||||
}
|
||||
|
||||
string? accountSelector = GetOpt(args, "--account");
|
||||
string? serverSelector = GetOpt(args, "--server");
|
||||
string? clientOverride = GetOpt(args, "--client");
|
||||
string? engineOverride = GetOpt(args, "--engine");
|
||||
bool noLogin = HasFlag(args, "--no-login");
|
||||
|
||||
string settingsPath = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore", "appsettings.json");
|
||||
if (!File.Exists(settingsPath))
|
||||
{
|
||||
Log($"appsettings.json not found at {settingsPath}.");
|
||||
return 2;
|
||||
}
|
||||
|
||||
AppSettingsDto? settings;
|
||||
try
|
||||
{
|
||||
settings = JsonSerializer.Deserialize<AppSettingsDto>(File.ReadAllText(settingsPath), ReadOpts);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Failed to parse appsettings.json: {ex.Message}");
|
||||
return 2;
|
||||
}
|
||||
if (settings == null)
|
||||
{
|
||||
Log("appsettings.json parsed to null.");
|
||||
return 2;
|
||||
}
|
||||
|
||||
// ── Resolve account ──────────────────────────────────────────────────
|
||||
List<AccountDto> accounts = settings.AccountProfiles ?? new();
|
||||
string? selector = accountSelector ?? settings.SelectedAccountProfileId;
|
||||
AccountDto? account = null;
|
||||
if (!string.IsNullOrWhiteSpace(selector))
|
||||
{
|
||||
account = accounts.FirstOrDefault(a =>
|
||||
string.Equals(a.Id, selector, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(a.AccountName, selector, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
if (account == null && (settings.CheckedLaunchAccountProfileIds?.Count ?? 0) > 0)
|
||||
{
|
||||
account = accounts.FirstOrDefault(a =>
|
||||
settings.CheckedLaunchAccountProfileIds!.Contains(a.Id));
|
||||
}
|
||||
if (account == null)
|
||||
{
|
||||
Log($"Could not resolve an account (selector='{selector ?? "<none>"}'). " +
|
||||
$"Available: {string.Join(", ", accounts.Select(a => a.AccountName))}");
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (account.InjectionMode == InjMode.Decal)
|
||||
Log($"WARNING: account '{account.AccountName}' is configured for Decal mode; --launch always injects the RynthCore engine.");
|
||||
|
||||
// ── Resolve server ───────────────────────────────────────────────────
|
||||
List<ServerDto> servers = settings.ServerProfiles ?? new();
|
||||
ServerDto? server = null;
|
||||
if (!string.IsNullOrWhiteSpace(serverSelector))
|
||||
{
|
||||
server = servers.FirstOrDefault(s =>
|
||||
string.Equals(s.Id, serverSelector, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(s.Name, serverSelector, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
server ??= servers.FirstOrDefault(s =>
|
||||
string.Equals(s.Id, account.ServerId, StringComparison.OrdinalIgnoreCase));
|
||||
if (server == null)
|
||||
{
|
||||
Log($"Could not resolve a server for account '{account.AccountName}' (serverId='{account.ServerId}').");
|
||||
return 2;
|
||||
}
|
||||
|
||||
// ── Resolve paths ────────────────────────────────────────────────────
|
||||
string clientPath;
|
||||
if (!string.IsNullOrWhiteSpace(clientOverride))
|
||||
clientPath = clientOverride!;
|
||||
else if (File.Exists(PrivateAcClientPath))
|
||||
clientPath = PrivateAcClientPath;
|
||||
else
|
||||
clientPath = settings.AcClientPath ?? string.Empty;
|
||||
|
||||
string enginePath = !string.IsNullOrWhiteSpace(engineOverride)
|
||||
? engineOverride!
|
||||
: settings.EnginePath ?? string.Empty;
|
||||
|
||||
if (!File.Exists(clientPath))
|
||||
{
|
||||
Log($"AC client not found: '{clientPath}'.");
|
||||
return 2;
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(enginePath))
|
||||
{
|
||||
Log("Engine/loader path is not set (appsettings.EnginePath empty and no --engine).");
|
||||
return 2;
|
||||
}
|
||||
|
||||
// ── Build AC auto-login args (mirrors AcLaunchArgumentBuilder) ────────
|
||||
string conn = ComputeConnectionString(server);
|
||||
string rodat = server.RodatEnabled ? "on" : "off";
|
||||
string acct = account.AccountName ?? string.Empty;
|
||||
string pwd = account.Password ?? string.Empty;
|
||||
|
||||
string arguments = server.Emulator == EmulatorKind.Gdle
|
||||
? string.Join(" ",
|
||||
"-h", Quote(server.Host ?? string.Empty),
|
||||
"-p", server.Port.ToString(CultureInfo.InvariantCulture),
|
||||
"-a", Quote($"{acct}:{pwd}"),
|
||||
"-rodat", rodat)
|
||||
: string.Join(" ",
|
||||
"-a", Quote(acct),
|
||||
"-v", Quote(pwd),
|
||||
"-h", Quote(conn),
|
||||
"-rodat", rodat);
|
||||
|
||||
string targetCharacter = noLogin || account.CharacterName == NoneOption
|
||||
? string.Empty
|
||||
: account.CharacterName ?? string.Empty;
|
||||
|
||||
// Credentials deliberately NOT logged (the args carry the password).
|
||||
Log($"Launching account='{acct}' server='{server.Name}' ({server.Emulator}) " +
|
||||
$"conn='{conn}' rodat={rodat} target='{(targetCharacter.Length == 0 ? "<login screen>" : targetCharacter)}'.");
|
||||
Log($"AC client: {clientPath}");
|
||||
Log($"Engine : {enginePath}");
|
||||
|
||||
// ── Launch suspended + inject ────────────────────────────────────────
|
||||
var service = new EngineInjectionService();
|
||||
int createdPid = 0;
|
||||
InjectionResult result = service.LaunchSuspendedAndInject(
|
||||
clientPath,
|
||||
arguments,
|
||||
enginePath,
|
||||
line =>
|
||||
{
|
||||
Console.WriteLine(line);
|
||||
logToFile($"[launch] {line}");
|
||||
},
|
||||
processId =>
|
||||
{
|
||||
createdPid = processId;
|
||||
try
|
||||
{
|
||||
WriteLaunchContext(processId, acct, server.Name ?? string.Empty,
|
||||
targetCharacter, settings.SkipLoginLogos, account.OnLoginWaitMs);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"WARNING: failed to write launch context for PID {processId}: {ex.Message}");
|
||||
}
|
||||
});
|
||||
|
||||
if (result.Success && result.ProcessId is int pid)
|
||||
{
|
||||
Log($"SUCCESS — PID {pid} launched and injected.");
|
||||
Console.WriteLine($"LAUNCHED_PID={pid}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
Log($"FAILED: {result.Summary}");
|
||||
if (createdPid != 0)
|
||||
Console.WriteLine($"LAUNCHED_PID={createdPid}"); // process exists; harness may want to clean it up
|
||||
return result.ExitCode == 0 ? 1 : result.ExitCode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes %APPDATA%\RynthCore\launch_contexts\launch_context_<pid>.json with the
|
||||
/// same PascalCase shape the launcher writes — the engine reads it to know
|
||||
/// which character to auto-select and whether to skip login logos.
|
||||
/// </summary>
|
||||
private static void WriteLaunchContext(
|
||||
int pid, string accountName, string serverName, string targetCharacter,
|
||||
bool skipLoginLogos, int onLoginWaitMs)
|
||||
{
|
||||
string dir = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore", "launch_contexts");
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
var record = new LaunchContextDto
|
||||
{
|
||||
ProcessId = pid,
|
||||
AccountName = accountName,
|
||||
ServerName = serverName,
|
||||
TargetCharacter = targetCharacter,
|
||||
SkipLoginLogos = skipLoginLogos,
|
||||
CreatedAtUtc = DateTime.UtcNow,
|
||||
OnLoginCommands = null,
|
||||
OnLoginWaitMs = onLoginWaitMs
|
||||
};
|
||||
|
||||
File.WriteAllText(
|
||||
Path.Combine(dir, $"launch_context_{pid}.json"),
|
||||
JsonSerializer.Serialize(record));
|
||||
}
|
||||
|
||||
private static string ComputeConnectionString(ServerDto s) =>
|
||||
string.IsNullOrWhiteSpace(s.Host) || s.Port <= 0
|
||||
? string.Empty
|
||||
: $"{s.Host}:{s.Port}";
|
||||
|
||||
// Mirrors AcLaunchArgumentBuilder.Quote — only quote when needed, escape
|
||||
// backslashes + quotes inside.
|
||||
private static string Quote(string value)
|
||||
{
|
||||
value ??= string.Empty;
|
||||
if (value.Length == 0)
|
||||
return "\"\"";
|
||||
bool needs = value.Any(ch => char.IsWhiteSpace(ch) || ch == '"');
|
||||
if (!needs)
|
||||
return value;
|
||||
return "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
|
||||
}
|
||||
|
||||
private static string? GetOpt(string[] args, string name)
|
||||
{
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
{
|
||||
if (string.Equals(args[i], name, StringComparison.OrdinalIgnoreCase))
|
||||
return i + 1 < args.Length ? args[i + 1] : null;
|
||||
if (args[i].StartsWith(name + "=", StringComparison.OrdinalIgnoreCase))
|
||||
return args[i].Substring(name.Length + 1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool HasFlag(string[] args, string name) =>
|
||||
args.Any(a => string.Equals(a, name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
// ── Minimal mirrors of the launcher's persisted DTOs ─────────────────────
|
||||
private sealed class AppSettingsDto
|
||||
{
|
||||
public string? AcClientPath { get; set; }
|
||||
public string? EnginePath { get; set; }
|
||||
public bool SkipLoginLogos { get; set; }
|
||||
public string? SelectedAccountProfileId { get; set; }
|
||||
public List<string>? CheckedLaunchAccountProfileIds { get; set; }
|
||||
public List<AccountDto>? AccountProfiles { get; set; }
|
||||
public List<ServerDto>? ServerProfiles { get; set; }
|
||||
}
|
||||
|
||||
private sealed class AccountDto
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public string AccountName { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
public string CharacterName { get; set; } = string.Empty;
|
||||
public string ServerId { get; set; } = string.Empty;
|
||||
public int OnLoginWaitMs { get; set; }
|
||||
public InjMode InjectionMode { get; set; }
|
||||
}
|
||||
|
||||
private sealed class ServerDto
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Host { get; set; } = string.Empty;
|
||||
public int Port { get; set; }
|
||||
public EmulatorKind Emulator { get; set; }
|
||||
public bool RodatEnabled { get; set; }
|
||||
}
|
||||
|
||||
private enum EmulatorKind { Ace = 0, Gdle = 1 }
|
||||
|
||||
private enum InjMode { RynthCore = 0, Decal = 1 }
|
||||
|
||||
private sealed class LaunchContextDto
|
||||
{
|
||||
public int ProcessId { get; set; }
|
||||
public string AccountName { get; set; } = string.Empty;
|
||||
public string ServerName { get; set; } = string.Empty;
|
||||
public string TargetCharacter { get; set; } = string.Empty;
|
||||
public bool SkipLoginLogos { get; set; }
|
||||
public DateTime CreatedAtUtc { get; set; }
|
||||
public List<string>? OnLoginCommands { get; set; }
|
||||
public int OnLoginWaitMs { get; set; }
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +1,33 @@
|
|||
using System;
|
||||
using RynthCore;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using RynthCore.Install;
|
||||
|
||||
namespace RynthCore.Injector;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
// Unified log path — must stay in sync with RynthCore.Engine.LogPaths.
|
||||
// Installer-chosen RynthCore folder (falls back to C:\Games\RynthCore).
|
||||
private static readonly string UnifiedLogDirectory = RynthInstallPaths.CoreLogsDir;
|
||||
private const string UnifiedLogFileName = "RynthCore.log";
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
// Headless modes never prompt — safe to call from scripts / a test
|
||||
// harness with no interactive console.
|
||||
bool headless = args.Any(a =>
|
||||
string.Equals(a, "--launch", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(a, "--no-prompt", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
try
|
||||
{
|
||||
LogToFile("Injector starting.");
|
||||
|
||||
if (args.Any(a => string.Equals(a, "--launch", StringComparison.OrdinalIgnoreCase)))
|
||||
return LaunchCommand.Run(args, LogToFile);
|
||||
|
||||
return Run(args);
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
|
@ -16,73 +35,106 @@ internal static class Program
|
|||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"FATAL EXCEPTION: {ex}");
|
||||
try
|
||||
{
|
||||
DesktopRollingLog.AppendLine(DesktopRollingLog.StemInjector,
|
||||
$"FATAL: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
Console.ResetColor();
|
||||
LogToFile($"FATAL: {ex}");
|
||||
return 99;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Press any key to exit...");
|
||||
Console.ReadKey(true);
|
||||
if (!headless)
|
||||
{
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Press any key to exit...");
|
||||
try { Console.ReadKey(true); } catch { /* no interactive console */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int Run(string[] args)
|
||||
{
|
||||
var service = new EngineInjectionService();
|
||||
void Line(string s)
|
||||
{
|
||||
Console.WriteLine(s);
|
||||
try
|
||||
{
|
||||
string t = DateTime.Now.ToString("HH:mm:ss.fff");
|
||||
DesktopRollingLog.AppendLine(DesktopRollingLog.StemInjector, $"[{t}] {s}");
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
Line("========================================");
|
||||
Line(" RynthCore Injector Console ");
|
||||
Line("========================================");
|
||||
Line("");
|
||||
Console.WriteLine("========================================");
|
||||
Console.WriteLine(" RynthCore Injector Console ");
|
||||
Console.WriteLine("========================================");
|
||||
Console.WriteLine();
|
||||
|
||||
string? enginePath = service.TryResolveEnginePath(args.Length > 0 ? args[0] : null);
|
||||
if (enginePath == null)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Line($"Could not locate {EngineInjectionService.EngineDllName}.");
|
||||
Line("Copy it next to the injector or pass the full path as the first argument.");
|
||||
Console.WriteLine($"Could not locate {EngineInjectionService.EngineDllName}.");
|
||||
Console.WriteLine("Copy it next to the injector or pass the full path as the first argument.");
|
||||
Console.ResetColor();
|
||||
LogToFile($"FAIL: could not locate {EngineInjectionService.EngineDllName}");
|
||||
return 1;
|
||||
}
|
||||
|
||||
InjectionResult result = service.InjectFirstRunning(enginePath, Line);
|
||||
Line("");
|
||||
LogToFile($"Resolved engine path: {enginePath}");
|
||||
|
||||
InjectionResult result = service.InjectFirstRunning(
|
||||
enginePath,
|
||||
line =>
|
||||
{
|
||||
Console.WriteLine(line);
|
||||
LogToFile(line);
|
||||
});
|
||||
Console.WriteLine();
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
Line(result.Summary);
|
||||
Line("Check Desktop\\RynthCore.log for in-process engine output. " +
|
||||
"RynthCore-Launcher.log and RynthCore-Injector.log list launcher/injector. " +
|
||||
"Each file rolls at 10 MB; up to 10 roll segments per day per file under Desktop\\RynthLogs.");
|
||||
Console.WriteLine(result.Summary);
|
||||
Console.WriteLine($"Check {Path.Combine(UnifiedLogDirectory, UnifiedLogFileName)} for in-process status.");
|
||||
Console.ResetColor();
|
||||
LogToFile($"SUCCESS: {result.Summary}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Line(result.Summary);
|
||||
Console.WriteLine(result.Summary);
|
||||
Console.ResetColor();
|
||||
LogToFile($"FAIL: {result.Summary} exit={result.ExitCode}");
|
||||
return result.ExitCode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Append a line to the unified RynthCore log so injector and in-process
|
||||
/// engine activity show up in one timeline. FileShare.ReadWrite lets the
|
||||
/// engine (running inside acclient.exe) keep writing concurrently.
|
||||
/// </summary>
|
||||
private static void LogToFile(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(UnifiedLogDirectory);
|
||||
string line = $"[{DateTime.Now:HH:mm:ss.fff}] [pid:{Environment.ProcessId}] [injector] {message}\r\n";
|
||||
byte[] bytes = Encoding.UTF8.GetBytes(line);
|
||||
|
||||
for (int attempt = 0; attempt < 4; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(
|
||||
Path.Combine(UnifiedLogDirectory, UnifiedLogFileName),
|
||||
FileMode.Append,
|
||||
FileAccess.Write,
|
||||
FileShare.ReadWrite);
|
||||
fs.Write(bytes, 0, bytes.Length);
|
||||
return;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
System.Threading.Thread.Sleep(5);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,4 +15,9 @@
|
|||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-location resolver (installer-chosen RynthCore / RynthSuite folders). -->
|
||||
<Compile Include="..\RynthCore.App\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
Loading…
Reference in a new issue