using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using Microsoft.Extensions.Logging; namespace ClassNotify.Service.Services; public static class SessionLauncher { [DllImport("kernel32.dll", SetLastError = true)] private static extern uint WTSGetActiveConsoleSessionId(); [DllImport("wtsapi32.dll", SetLastError = true)] private static extern bool WTSQueryUserToken(uint sessionId, out IntPtr phToken); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern bool DuplicateTokenEx( IntPtr hExistingToken, uint dwDesiredAccess, IntPtr lpTokenAttributes, int impersonationLevel, int tokenType, out IntPtr phNewToken); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern bool CreateProcessAsUser( IntPtr hToken, string? lpApplicationName, string? lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string? lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); [DllImport("userenv.dll", SetLastError = true)] private static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit); [DllImport("userenv.dll", SetLastError = true)] private static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", SetLastError = true)] private static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode); [DllImport("advapi32.dll", SetLastError = true)] private static extern bool SetTokenInformation( IntPtr TokenHandle, int TokenInformationClass, ref uint TokenInformation, uint TokenInformationLength); private const int TokenSessionId = 7; [StructLayout(LayoutKind.Sequential)] private struct STARTUPINFO { public int cb; public string? lpReserved; public string? lpDesktop; public string? lpTitle; public int dwX; public int dwY; public int dwXSize; public int dwYSize; public int dwXCountChars; public int dwYCountChars; public int dwFillAttribute; public int dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential)] private struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } private const uint MAXIMUM_ALLOWED = 0x02000000; private const int SecurityImpersonation = 2; private const int TokenPrimary = 1; private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400; private const uint CREATE_NEW_CONSOLE = 0x00000010; private const int STARTF_USESHOWWINDOW = 0x00000001; private const short SW_SHOW = 5; public static (bool Success, int Pid, uint SessionId, string LaunchToken) LaunchProcessInActiveUserSession( string exePath, string? launchToken = null, ILogger? logger = null, string? extraArgs = null) { string token = launchToken ?? Guid.NewGuid().ToString("N"); if (!File.Exists(exePath)) { logger?.LogError("Target executable does not exist: {ExePath}", exePath); return (false, 0, 0, string.Empty); } IntPtr userToken = IntPtr.Zero; IntPtr primaryToken = IntPtr.Zero; IntPtr envBlock = IntPtr.Zero; try { uint activeSessionId = WTSGetActiveConsoleSessionId(); bool tokenFound = (activeSessionId != 0xFFFFFFFF) && WTSQueryUserToken(activeSessionId, out userToken); if (!tokenFound) { // Fallback: search sessions 1..32 for any session with an active logged-in user token for (uint s = 1; s <= 32; s++) { if (WTSQueryUserToken(s, out userToken)) { activeSessionId = s; tokenFound = true; break; } } } if (!tokenFound) { logger?.LogWarning("[SessionLauncher] No active user session token found across all sessions (1..32). Aborting launch to allow watchdog backoff retry."); return (false, 0, activeSessionId, string.Empty); } // Explicitly set target SessionId on user token SetTokenInformation(userToken, TokenSessionId, ref activeSessionId, sizeof(uint)); IntPtr launchTokenHandle = userToken; if (DuplicateTokenEx(userToken, MAXIMUM_ALLOWED, IntPtr.Zero, SecurityImpersonation, TokenPrimary, out primaryToken)) { SetTokenInformation(primaryToken, TokenSessionId, ref activeSessionId, sizeof(uint)); launchTokenHandle = primaryToken; } bool envCreated = CreateEnvironmentBlock(out envBlock, launchTokenHandle, false); if (!envCreated) { var err = Marshal.GetLastWin32Error(); logger?.LogWarning("[SessionLauncher] CreateEnvironmentBlock failed, Win32Error: {Error}. Falling back to IntPtr.Zero.", err); envBlock = IntPtr.Zero; } var si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_SHOW; si.lpDesktop = null; // Let Windows assign the default interactive desktop for target session var workingDir = Path.GetDirectoryName(exePath); var commandLine = string.IsNullOrEmpty(extraArgs) ? $"\"{exePath}\" --ipc-token {token}" : $"\"{exePath}\" --ipc-token {token} {extraArgs}"; uint dwCreationFlags = CREATE_NEW_CONSOLE | (envBlock != IntPtr.Zero ? CREATE_UNICODE_ENVIRONMENT : 0); var success = CreateProcessAsUser( launchTokenHandle, null, commandLine, IntPtr.Zero, IntPtr.Zero, false, dwCreationFlags, envBlock, workingDir, ref si, out var pi); if (!success && launchTokenHandle != userToken) { logger?.LogWarning("[SessionLauncher] CreateProcessAsUser failed with duplicate token. Retrying with original userToken..."); success = CreateProcessAsUser( userToken, null, commandLine, IntPtr.Zero, IntPtr.Zero, false, dwCreationFlags, envBlock, workingDir, ref si, out pi); } if (success) { int pid = pi.dwProcessId; logger?.LogInformation("[SessionLauncher] launched new client PID={Pid} SessionId={SessionId}.", pid, activeSessionId); if (WaitForSingleObject(pi.hProcess, 300) == 0) { GetExitCodeProcess(pi.hProcess, out uint exitCode); logger?.LogWarning("[SessionLauncher] Process PID={Pid} exited immediately with ExitCode={ExitCode} (0x{ExitCode:X8})", pid, exitCode, exitCode); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return (true, pid, activeSessionId, token); } else { var err = Marshal.GetLastWin32Error(); logger?.LogWarning("[SessionLauncher] CreateProcessAsUser failed, Win32Error: {Error}. Aborting launch to allow watchdog backoff retry.", err); return (false, 0, activeSessionId, string.Empty); } } catch (Exception ex) { logger?.LogError(ex, "[SessionLauncher] Exception in LaunchProcessInActiveUserSession. Aborting launch to allow watchdog backoff retry."); return (false, 0, 0, string.Empty); } finally { if (envBlock != IntPtr.Zero) DestroyEnvironmentBlock(envBlock); if (primaryToken != IntPtr.Zero) CloseHandle(primaryToken); if (userToken != IntPtr.Zero) CloseHandle(userToken); } } }