using System; using System.IO; using System.IO.Pipes; using System.Text; using System.Threading; using System.Threading.Tasks; namespace UCVL.Maintenance { // The server MUST run in the direct installer parent, not a helper process. public sealed class GuardianApprovalPipe : IDisposable { readonly CancellationTokenSource timeout; readonly Task task; readonly object sync=new object(); NamedPipeServerStream activeServer; int disposed; public GuardianApprovalPipe(string nonce,string line,int milliseconds) { if(nonce==null || !System.Text.RegularExpressions.Regex.IsMatch(nonce,"^[a-f0-9]{64}$") || line==null || line.Length>2000 || line.Contains("\n") || line.Contains("\r") || milliseconds<1 || milliseconds>300000) throw new ArgumentException("Invalid finite gate approval"); timeout=new CancellationTokenSource(milliseconds); task=Serve(nonce,line,timeout.Token); } async Task Serve(string nonce,string line,CancellationToken token) { var bytes=new UTF8Encoding(false).GetBytes(line+"\n"); for(int i=0;i<2;i++) { token.ThrowIfCancellationRequested(); using(var server=new NamedPipeServerStream("UCVL.InstallerGuardian."+nonce,PipeDirection.Out,1, PipeTransmissionMode.Byte,PipeOptions.Asynchronous|PipeOptions.CurrentUserOnly,0,1024)) { lock(sync){token.ThrowIfCancellationRequested();activeServer=server;} try { await server.WaitForConnectionAsync(token).ConfigureAwait(false); // Write directly so neither StreamWriter's synchronous AutoFlush nor its // disposal can block cleanup when a connected reader stops consuming. await server.WriteAsync(bytes,0,bytes.Length,token).ConfigureAwait(false); await Task.Delay(75,token).ConfigureAwait(false); } finally { lock(sync){if(ReferenceEquals(activeServer,server))activeServer=null;} } } } } public bool Completed {get{return task.IsCompletedSuccessfully;}} public void Verify(){task.GetAwaiter().GetResult();} public void Dispose(){ if(Interlocked.Exchange(ref disposed,1)!=0)return; // Cleanup must never veto the coordinator's rollback. Verify retains the // original fault/cancellation and remains the only approval success check. try{timeout.Cancel();}catch{} NamedPipeServerStream server; lock(sync){server=activeServer;activeServer=null;} try{if(server!=null)server.Dispose();}catch{} // Cancellation plus handle closure releases pending overlapped pipe I/O. // Keep an explicit bound even if an OS I/O completion is delayed. try{task.Wait(2000);}catch{} try{timeout.Dispose();}catch{} } } }