using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Web.Script.Serialization;
using System.Windows.Automation;
public static class SelectionWatchdog
{
[StructLayout(LayoutKind.Sequential)]
struct FileTime { public uint low; public uint high; }
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool GetProcessTimes(IntPtr handle, out FileTime creation, out FileTime exit, out FileTime kernel, out FileTime user);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool TerminateProcess(IntPtr handle, uint code);
[DllImport("kernel32.dll")]
static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
[DllImport("kernel32.dll")]
static extern bool CloseHandle(IntPtr handle);
public sealed class Journal
{
public int parent_pid;
public long parent_start_ticks;
public string hwnd;
public uint window_pid;
public long window_start_ticks;
public uint input_tick;
public int[] original_tab;
public int[] owned_tab;
public int[] pending_tab;
public long deadline_utc_ticks;
public bool stop;
}
static bool SameProcess(int pid, long ticks)
{
try
{
using (var process = Process.GetProcessById(pid))
return process.StartTime.ToUniversalTime().Ticks == ticks;
}
catch { return false; }
}
static void ValidateImmutable(Journal initial, Journal current)
{
if (current == null || initial.parent_pid != current.parent_pid
|| initial.parent_start_ticks != current.parent_start_ticks
|| initial.hwnd != current.hwnd || initial.window_pid != current.window_pid
|| initial.window_start_ticks != current.window_start_ticks
|| initial.input_tick != current.input_tick
|| initial.deadline_utc_ticks != current.deadline_utc_ticks
|| initial.original_tab == null || current.original_tab == null
|| !initial.original_tab.SequenceEqual(current.original_tab))
throw new InvalidOperationException("Immutable selection-watchdog scope changed");
}
static void TerminateOwnedCollector(Journal journal)
{
IntPtr handle = OpenProcess(0x00101001, false, journal.parent_pid);
if (handle == IntPtr.Zero)
{
if (Marshal.GetLastWin32Error() == 87) return;
throw new InvalidOperationException("Owned collector handle unavailable");
}
try
{
FileTime creation, exit, kernel, user;
if (!GetProcessTimes(handle, out creation, out exit, out kernel, out user))
throw new InvalidOperationException("Owned collector creation identity unavailable");
ulong ticks = ((ulong)creation.high << 32 | creation.low) + 504911232000000000UL;
if (ticks != (ulong)journal.parent_start_ticks) return;
if (!TerminateProcess(handle, 1) && WaitForSingleObject(handle, 0) != 0)
throw new InvalidOperationException("Owned collector termination failed");
if (WaitForSingleObject(handle, 1000) != 0)
throw new InvalidOperationException("Owned collector did not terminate");
}
finally { CloseHandle(handle); }
}
enum PublicationRace
{
FileNotFound = 2,
PathNotFound = 3,
SharingViolation = 32,
LockViolation = 33,
DeletePending = 303
}
static bool IsPublicationRace(IOException error)
{
return Enum.IsDefined(typeof(PublicationRace), error.HResult & 0xffff);
}
static Journal Read(string path, long deadlineTicks)
{
long retryUntil = Math.Min(DateTime.UtcNow.AddMilliseconds(250).Ticks, deadlineTicks);
while (true)
{
try
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete))
{
if (stream.Length > 65536) throw new InvalidOperationException("Selection journal exceeds bound");
using (var reader = new StreamReader(stream))
return new JavaScriptSerializer().Deserialize<Journal>(reader.ReadToEnd());
}
}
catch (IOException error)
{
if (!IsPublicationRace(error) || DateTime.UtcNow.Ticks >= retryUntil) throw;
Thread.Sleep(2);
}
}
}
static void Receipt(string path, string status)
{
using (var self = Process.GetCurrentProcess())
{
var value = new { status = status, pid = self.Id, start_ticks = self.StartTime.ToUniversalTime().Ticks };
File.WriteAllText(path, new JavaScriptSerializer().Serialize(value));
}
}
static bool Matches(AutomationElement element, int[] runtime)
{
return runtime != null && element.GetRuntimeId().SequenceEqual(runtime);
}
static string Restore(Journal journal)
{
if (journal.owned_tab == null) return "no_owned_selection";
if (!SameProcess((int)journal.window_pid, journal.window_start_ticks))
return "skipped_window_identity_changed";
if (!CaptureNative.Windows().Any(window => window.hwnd == journal.hwnd && window.pid == journal.window_pid))
return "skipped_window_missing";
if (CaptureNative.InputTick() != journal.input_tick)
return "skipped_physical_input_changed";
var windowElement = AutomationElement.FromHandle(new IntPtr(long.Parse(journal.hwnd)));
if (windowElement.Current.ProcessId != journal.window_pid)
return "skipped_hwnd_reused";
var tabs = windowElement.FindAll(TreeScope.Descendants,
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem));
AutomationElement original = null;
AutomationElement current = null;
foreach (AutomationElement tab in tabs)
{
if (Matches(tab, journal.original_tab)) original = tab;
var pattern = (SelectionItemPattern)tab.GetCurrentPattern(SelectionItemPattern.Pattern);
if (pattern.Current.IsSelected)
{
if (current != null) return "failed_multiple_selected_tabs";
current = tab;
}
}
if (original == null || current == null) return "failed_tab_identity_missing";
if (!Matches(current, journal.owned_tab) && !Matches(current, journal.pending_tab))
return "skipped_selection_changed";
if (CaptureNative.InputTick() != journal.input_tick)
return "skipped_physical_input_changed";
((SelectionItemPattern)original.GetCurrentPattern(SelectionItemPattern.Pattern)).Select();
return ((SelectionItemPattern)original.GetCurrentPattern(SelectionItemPattern.Pattern)).Current.IsSelected
? "restored" : "failed_selection_verification";
}
public static int Main(string[] args)
{
if (args.Length != 3) return 64;
string journalPath = args[0], readyPath = args[1], receiptPath = args[2];
try
{
var initial = Read(journalPath, DateTime.UtcNow.AddMilliseconds(250).Ticks);
if (!SameProcess(initial.parent_pid, initial.parent_start_ticks))
throw new InvalidOperationException("Collector identity missing before watchdog startup");
Receipt(readyPath, "ready");
var lifetime = Stopwatch.StartNew();
while (true)
{
var journal = Read(journalPath, initial.deadline_utc_ticks);
ValidateImmutable(initial, journal);
if (journal.stop)
{
Receipt(receiptPath, "normal_stop_acknowledged");
return 0;
}
bool parentAlive = SameProcess(initial.parent_pid, initial.parent_start_ticks);
bool expired = DateTime.UtcNow.Ticks >= initial.deadline_utc_ticks || lifetime.ElapsedMilliseconds >= 105000;
if (!parentAlive || expired)
{
if (parentAlive)
{
TerminateOwnedCollector(initial);
}
string status = null;
var worker = new Thread(() =>
{
try { status = Restore(journal); }
catch (Exception error) { status = "failed_restore: " + error.Message; }
});
worker.IsBackground = true;
worker.SetApartmentState(ApartmentState.MTA);
worker.Start();
if (!worker.Join(4000))
{
Receipt(receiptPath, "failed_restore_timeout");
Environment.Exit(2);
}
Receipt(receiptPath, status ?? "failed_restore_no_result");
return status != null && !status.StartsWith("failed") ? 0 : 2;
}
Thread.Sleep(20);
}
}
catch (Exception error)
{
try { Receipt(receiptPath, "failed_watchdog: " + error.Message); } catch { }
return 2;
}
}
}