using System; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Linq; using Microsoft.Win32; namespace PlotDirector.WordAddIn { internal static class AgentProcess { internal static string LaunchStatus {get;private set;}="Not requested"; internal static string PipeName() { var value = WindowsIdentity.GetCurrent().User.Value + ":" + Process.GetCurrentProcess().SessionId; using (var hash = SHA256.Create()) return "PlotDirector.Companion.v1." + BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(value))).Replace("-", "").Substring(0,24); } // Called only on the IPC worker. No Word objects, UI calls or shell search paths. internal static void Start()=>Start(false); internal static void Start(bool activate) { var paused=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"PlotDirector","Companion","paused"); if(!activate&&File.Exists(paused)&&File.GetLastWriteTimeUtc(paused)>=Process.GetCurrentProcess().StartTime.ToUniversalTime()){LaunchStatus="Companion exited by author; use Open Companion to resume.";return;} if(activate&&File.Exists(paused))File.Delete(paused); var assembly=Assembly.GetExecutingAssembly().Location; var executable=Path.Combine(Path.GetDirectoryName(assembly),"Agent","PlotDirector.Companion.Agent.exe"); if(!File.Exists(executable))executable=FindRegisteredAgent(assembly); if(string.IsNullOrEmpty(executable)){LaunchStatus="Matching agent missing from the registered package. Reinstall the complete package.";return;} LaunchStatus="Starting the matching local agent"; using (Process.Start(new ProcessStartInfo(executable) { Arguments=activate?"--open":"",UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(executable) })) { } } private static string FindRegisteredAgent(string loadedAssembly) { // VSTO can shadow-copy the DLL without its adjacent Agent directory. // Resolve only a registered local package containing the exact DLL bytes. using(var registrations=Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\Word\Addins")) using(var hash=SHA256.Create()) { if(registrations==null||!File.Exists(loadedAssembly))return null; byte[] expected;using(var stream=File.OpenRead(loadedAssembly))expected=hash.ComputeHash(stream); foreach(var key in registrations.GetSubKeyNames().Take(64)) using(var entry=registrations.OpenSubKey(key)) { var manifest=(entry?.GetValue("Manifest") as string??"").Split('|')[0]; if(!Uri.TryCreate(manifest,UriKind.Absolute,out var uri)||!uri.IsFile||Path.GetFileName(uri.LocalPath)!="PlotDirector.WordAddIn.vsto")continue; var root=Path.GetDirectoryName(uri.LocalPath); var candidate=Path.Combine(root,"PlotDirector.WordAddIn.dll"); var agent=Path.Combine(root,"Agent","PlotDirector.Companion.Agent.exe"); if(!File.Exists(candidate)||!File.Exists(agent))continue; using(var stream=File.OpenRead(candidate))if(hash.ComputeHash(stream).SequenceEqual(expected))return agent; } } return null; } internal static bool VerifyOwner(NamedPipeClientStream pipe) { uint processId; if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle.DangerousGetHandle(),out processId)) return false; var process = OpenProcess(0x1000,false,processId); if (process == IntPtr.Zero) return false; IntPtr token = IntPtr.Zero; try { if (!OpenProcessToken(process,8,out token)) return false; using (var identity = new WindowsIdentity(token)) using (var current = WindowsIdentity.GetCurrent()) return identity.User == current.User; } finally { if(token != IntPtr.Zero)CloseHandle(token); CloseHandle(process); } } [DllImport("kernel32.dll",SetLastError=true)] private static extern bool GetNamedPipeServerProcessId(IntPtr pipe,out uint processId); [DllImport("kernel32.dll",SetLastError=true)] private static extern IntPtr OpenProcess(uint access,bool inherit,uint processId); [DllImport("advapi32.dll",SetLastError=true)] private static extern bool OpenProcessToken(IntPtr process,uint access,out IntPtr token); [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle); } }