ExeSessionProcess.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Threading;
  7. using Microsoft.Win32;
  8. using Microsoft.Win32.SafeHandles;
  9. using System.Runtime.InteropServices;
  10. using System.Reflection;
  11. using System.Security.Principal;
  12. using System.Security.AccessControl;
  13. namespace WinSCP
  14. {
  15. internal class ExeSessionProcess : IDisposable
  16. {
  17. public event OutputDataReceivedEventHandler OutputDataReceived;
  18. public bool HasExited { get { return _process.HasExited; } }
  19. public int ExitCode { get { return _process.ExitCode; } }
  20. public static ExeSessionProcess CreateForSession(Session session)
  21. {
  22. return new ExeSessionProcess(session, true, null);
  23. }
  24. public static ExeSessionProcess CreateForConsole(Session session, string additionalArguments)
  25. {
  26. return new ExeSessionProcess(session, false, additionalArguments);
  27. }
  28. private ExeSessionProcess(Session session, bool useXmlLog, string additionalArguments)
  29. {
  30. _session = session;
  31. _logger = session.Logger;
  32. _incompleteLine = string.Empty;
  33. using (_logger.CreateCallstack())
  34. {
  35. string executablePath = GetExecutablePath();
  36. _logger.WriteLine("EXE executable path resolved to {0}", executablePath);
  37. string assemblyFilePath = _logger.GetAssemblyFilePath();
  38. FileVersionInfo assemblyVersion = null;
  39. if (assemblyFilePath != null)
  40. {
  41. assemblyVersion = FileVersionInfo.GetVersionInfo(assemblyFilePath);
  42. }
  43. CheckVersion(executablePath, assemblyVersion);
  44. string configSwitch;
  45. if (_session.DefaultConfigurationInternal)
  46. {
  47. configSwitch = "/ini=nul ";
  48. }
  49. else
  50. {
  51. if (!string.IsNullOrEmpty(_session.IniFilePathInternal))
  52. {
  53. configSwitch = string.Format(CultureInfo.InvariantCulture, "/ini=\"{0}\" ", _session.IniFilePathInternal);
  54. }
  55. else
  56. {
  57. configSwitch = "";
  58. }
  59. }
  60. string logSwitch = null;
  61. if (!string.IsNullOrEmpty(_session.SessionLogPath))
  62. {
  63. logSwitch = string.Format(CultureInfo.InvariantCulture, "/log=\"{0}\" ", LogPathEscape(_session.SessionLogPath));
  64. }
  65. string xmlLogSwitch;
  66. if (useXmlLog)
  67. {
  68. xmlLogSwitch = string.Format(CultureInfo.InvariantCulture, "/xmllog=\"{0}\" /xmlgroups ", LogPathEscape(_session.XmlLogPath));
  69. }
  70. else
  71. {
  72. xmlLogSwitch = "";
  73. }
  74. string assemblyVersionStr =
  75. (assemblyVersion == null) ? "unk" :
  76. string.Format(CultureInfo.InvariantCulture, "{0}{1}{2} ", assemblyVersion.ProductMajorPart, assemblyVersion.ProductMinorPart, assemblyVersion.ProductBuildPart);
  77. string assemblyVersionSwitch =
  78. string.Format(CultureInfo.InvariantCulture, "/dotnet={0} ", assemblyVersionStr);
  79. string arguments =
  80. xmlLogSwitch + "/nointeractiveinput " + assemblyVersionSwitch +
  81. configSwitch + logSwitch + _session.AdditionalExecutableArguments;
  82. Tools.AddRawParameters(ref arguments, _session.RawConfiguration, "/rawconfig");
  83. if (!string.IsNullOrEmpty(additionalArguments))
  84. {
  85. arguments += " " + additionalArguments;
  86. }
  87. _process = new Process();
  88. _process.StartInfo.FileName = executablePath;
  89. _process.StartInfo.WorkingDirectory = Path.GetDirectoryName(executablePath);
  90. _process.StartInfo.Arguments = arguments;
  91. _process.StartInfo.UseShellExecute = false;
  92. _process.Exited += ProcessExited;
  93. }
  94. }
  95. private static string LogPathEscape(string path)
  96. {
  97. return Tools.ArgumentEscape(path).Replace("!", "!!");
  98. }
  99. public void Abort()
  100. {
  101. using (_logger.CreateCallstack())
  102. {
  103. lock (_lock)
  104. {
  105. if ((_process != null) && !_process.HasExited)
  106. {
  107. _process.Kill();
  108. }
  109. }
  110. }
  111. }
  112. public void Start()
  113. {
  114. using (_logger.CreateCallstack())
  115. {
  116. InitializeConsole();
  117. InitializeChild();
  118. }
  119. }
  120. private void InitializeChild()
  121. {
  122. using (_logger.CreateCallstack())
  123. {
  124. // The /console is redundant for CreateForConsole
  125. _process.StartInfo.Arguments += string.Format(CultureInfo.InvariantCulture, " /console /consoleinstance={0}", _instanceName);
  126. // When running under IIS in "impersonated" mode, the process starts, but does not do anything.
  127. // Supposedly it "displayes" some invisible error message when starting and hangs.
  128. // Running it "as the user" helps, eventhough it already runs as the user.
  129. // These's probably some difference between "run as" and impersonations
  130. if (!string.IsNullOrEmpty(_session.ExecutableProcessUserName))
  131. {
  132. _logger.WriteLine("Will run process as {0}", _session.ExecutableProcessUserName);
  133. _process.StartInfo.UserName = _session.ExecutableProcessUserName;
  134. _process.StartInfo.Password = _session.ExecutableProcessPassword;
  135. // One of the hints for resolving C0000142 error (see below)
  136. // was setting this property, so that an environment is correctly loaded,
  137. // so DLLs can be found and loaded.
  138. _process.StartInfo.LoadUserProfile = true;
  139. // Without granting both window station and desktop access permissions,
  140. // WinSCP process aborts with C0000142 (DLL Initialization Failed) error,
  141. // when "running as user"
  142. _logger.WriteLine("Granting access to window station");
  143. try
  144. {
  145. IntPtr windowStation = UnsafeNativeMethods.GetProcessWindowStation();
  146. GrantAccess(windowStation, (int)WindowStationRights.AllAccess);
  147. }
  148. catch (Exception e)
  149. {
  150. throw new SessionLocalException(_session, "Error granting access to window station", e);
  151. }
  152. _logger.WriteLine("Granting access to desktop");
  153. try
  154. {
  155. IntPtr desktop = UnsafeNativeMethods.GetThreadDesktop(UnsafeNativeMethods.GetCurrentThreadId());
  156. GrantAccess(desktop, (int)DesktopRights.AllAccess);
  157. }
  158. catch (Exception e)
  159. {
  160. throw new SessionLocalException(_session, "Error granting access to desktop", e);
  161. }
  162. }
  163. _logger.WriteLine("Starting \"{0}\" {1}", _process.StartInfo.FileName, _process.StartInfo.Arguments);
  164. _process.Start();
  165. _logger.WriteLine("Started process {0}", _process.Id);
  166. _thread = new Thread(ProcessEvents);
  167. _thread.IsBackground = true;
  168. _thread.Start();
  169. }
  170. }
  171. // Handles returned by GetProcessWindowStation and GetThreadDesktop should not be closed
  172. internal class NoopSafeHandle : SafeHandle
  173. {
  174. public NoopSafeHandle(IntPtr handle) :
  175. base(handle, false)
  176. {
  177. }
  178. public override bool IsInvalid
  179. {
  180. get { return false; }
  181. }
  182. protected override bool ReleaseHandle()
  183. {
  184. return true;
  185. }
  186. }
  187. private void GrantAccess(IntPtr handle, int accessMask)
  188. {
  189. using (SafeHandle safeHandle = new NoopSafeHandle(handle))
  190. {
  191. GenericSecurity security =
  192. new GenericSecurity(false, ResourceType.WindowObject, safeHandle, AccessControlSections.Access);
  193. security.AddAccessRule(
  194. new GenericAccessRule(new NTAccount(_session.ExecutableProcessUserName), accessMask, AccessControlType.Allow));
  195. security.Persist(safeHandle, AccessControlSections.Access);
  196. }
  197. }
  198. private void ProcessExited(object sender, EventArgs e)
  199. {
  200. _logger.WriteLine("Process {0} exited with exit code {1}", _process.Id, _process.ExitCode);
  201. }
  202. private bool AbortedOrExited()
  203. {
  204. if (_abort)
  205. {
  206. _logger.WriteLine("Aborted");
  207. return true;
  208. }
  209. else if (_process.HasExited)
  210. {
  211. _logger.WriteLine("Exited");
  212. return true;
  213. }
  214. else
  215. {
  216. return false;
  217. }
  218. }
  219. private void ProcessEvents()
  220. {
  221. using (_logger.CreateCallstack())
  222. {
  223. while (!AbortedOrExited())
  224. {
  225. _logger.WriteLineLevel(1, "Waiting for request event");
  226. if (_requestEvent.WaitOne(100, false))
  227. {
  228. _logger.WriteLineLevel(1, "Got request event");
  229. ProcessEvent();
  230. }
  231. }
  232. }
  233. }
  234. private void ProcessEvent()
  235. {
  236. using (_logger.CreateCallstack())
  237. {
  238. using (ConsoleCommStruct commStruct = AcquireCommStruct())
  239. {
  240. switch (commStruct.Event)
  241. {
  242. case ConsoleEvent.Print:
  243. ProcessPrintEvent(commStruct.PrintEvent);
  244. break;
  245. case ConsoleEvent.Input:
  246. ProcessInputEvent(commStruct.InputEvent);
  247. break;
  248. case ConsoleEvent.Choice:
  249. ProcessChoiceEvent(commStruct.ChoiceEvent);
  250. break;
  251. case ConsoleEvent.Title:
  252. ProcessTitleEvent(commStruct.TitleEvent);
  253. break;
  254. case ConsoleEvent.Init:
  255. ProcessInitEvent(commStruct.InitEvent);
  256. break;
  257. case ConsoleEvent.Progress:
  258. ProcessProgressEvent(commStruct.ProgressEvent);
  259. break;
  260. default:
  261. throw new NotImplementedException();
  262. }
  263. }
  264. _responseEvent.Set();
  265. }
  266. }
  267. private void ProcessChoiceEvent(ConsoleChoiceEventStruct e)
  268. {
  269. using (_logger.CreateCallstack())
  270. {
  271. if (e.Timeouting)
  272. {
  273. Thread.Sleep((int)e.Timer);
  274. e.Result = e.Timeouted;
  275. }
  276. else
  277. {
  278. e.Result = e.Break;
  279. }
  280. }
  281. }
  282. private void ProcessTitleEvent(ConsoleTitleEventStruct e)
  283. {
  284. using (_logger.CreateCallstack())
  285. {
  286. _logger.WriteLine("Not-supported title event [{0}]", e.Title);
  287. }
  288. }
  289. private void ProcessInputEvent(ConsoleInputEventStruct e)
  290. {
  291. using (_logger.CreateCallstack())
  292. {
  293. while (!AbortedOrExited())
  294. {
  295. lock (_input)
  296. {
  297. if (_input.Count > 0)
  298. {
  299. e.Str = _input[0];
  300. e.Result = true;
  301. _input.RemoveAt(0);
  302. Print(false, e.Str + "\n");
  303. return;
  304. }
  305. }
  306. _inputEvent.WaitOne(100, false);
  307. }
  308. }
  309. }
  310. private void Print(bool fromBeginning, string message)
  311. {
  312. if (fromBeginning && ((message.Length == 0) || (message[0] != '\n')))
  313. {
  314. _lastFromBeginning = message;
  315. _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);
  316. }
  317. else
  318. {
  319. if (!string.IsNullOrEmpty(_lastFromBeginning))
  320. {
  321. AddToOutput(_lastFromBeginning);
  322. _lastFromBeginning = null;
  323. }
  324. if (fromBeginning && (message.Length > 0) && (message[0] == '\n'))
  325. {
  326. AddToOutput("\n");
  327. _lastFromBeginning = message.Substring(1);
  328. _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);
  329. }
  330. else
  331. {
  332. AddToOutput(message);
  333. }
  334. }
  335. }
  336. private void AddToOutput(string message)
  337. {
  338. string[] lines = (_incompleteLine + message).Split(new[] { '\n' });
  339. _incompleteLine = lines[lines.Length - 1];
  340. for (int i = 0; i < lines.Length - 1; ++i)
  341. {
  342. if (OutputDataReceived != null)
  343. {
  344. OutputDataReceived(this, new OutputDataReceivedEventArgs(lines[i]));
  345. }
  346. }
  347. }
  348. private void ProcessPrintEvent(ConsolePrintEventStruct e)
  349. {
  350. Print(e.FromBeginning, e.Message);
  351. }
  352. private void ProcessInitEvent(ConsoleInitEventStruct e)
  353. {
  354. using (_logger.CreateCallstack())
  355. {
  356. e.InputType = 3; // pipe
  357. e.OutputType = 3; // pipe
  358. e.WantsProgress = _session.WantsProgress;
  359. }
  360. }
  361. private void ProcessProgressEvent(ConsoleProgressEventStruct e)
  362. {
  363. using (_logger.CreateCallstack())
  364. {
  365. _logger.WriteLine(
  366. "File Name [{0}] - Directory [{1}] - Overall Progress [{2}] - File Progress [{3}] - CPS [{4}]",
  367. e.FileName, e.Directory, e.OverallProgress, e.FileProgress, e.CPS);
  368. FileTransferProgressEventArgs args = new FileTransferProgressEventArgs();
  369. switch (e.Operation)
  370. {
  371. case ConsoleProgressEventStruct.ProgressOperation.Copy:
  372. args.Operation = ProgressOperation.Transfer;
  373. break;
  374. default:
  375. throw new ArgumentOutOfRangeException("Unknown progress operation", (Exception)null);
  376. }
  377. switch (e.Side)
  378. {
  379. case ConsoleProgressEventStruct.ProgressSide.Local:
  380. args.Side = ProgressSide.Local;
  381. break;
  382. case ConsoleProgressEventStruct.ProgressSide.Remote:
  383. args.Side = ProgressSide.Remote;
  384. break;
  385. default:
  386. throw new ArgumentOutOfRangeException("Unknown progress side", (Exception)null);
  387. }
  388. args.FileName = e.FileName;
  389. args.Directory = e.Directory;
  390. args.OverallProgress = ((double)e.OverallProgress) / 100;
  391. args.FileProgress = ((double)e.FileProgress) / 100;
  392. args.CPS = (int) e.CPS;
  393. _session.ProcessProgress(args);
  394. }
  395. }
  396. private void InitializeConsole()
  397. {
  398. using (_logger.CreateCallstack())
  399. {
  400. int attempts = 0;
  401. Random random = new Random();
  402. int process = Process.GetCurrentProcess().Id;
  403. do
  404. {
  405. if (attempts > MaxAttempts)
  406. {
  407. throw new SessionLocalException(_session, "Cannot find unique name for event object.");
  408. }
  409. int instanceNumber = random.Next(1000);
  410. _instanceName = string.Format(CultureInfo.InvariantCulture, "_{0}_{1}_{2}", process, GetHashCode(), instanceNumber);
  411. _logger.WriteLine("Trying event {0}", _instanceName);
  412. if (!TryCreateEvent(ConsoleEventRequest + _instanceName, out _requestEvent))
  413. {
  414. _logger.WriteLine("Event {0} is not unique", _instanceName);
  415. _requestEvent.Close();
  416. _requestEvent = null;
  417. }
  418. else
  419. {
  420. _logger.WriteLine("Event {0} is unique", _instanceName);
  421. _responseEvent = CreateEvent(ConsoleEventResponse + _instanceName);
  422. _cancelEvent = CreateEvent(ConsoleEventCancel + _instanceName);
  423. string fileMappingName = ConsoleMapping + _instanceName;
  424. _fileMapping = CreateFileMapping(fileMappingName);
  425. if (Marshal.GetLastWin32Error() == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  426. {
  427. throw new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "File mapping {0} already exists", fileMappingName));
  428. }
  429. if (_fileMapping.IsInvalid)
  430. {
  431. throw new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Cannot create file mapping {0}", fileMappingName));
  432. }
  433. }
  434. ++attempts;
  435. }
  436. while (_requestEvent == null);
  437. using (ConsoleCommStruct commStruct = AcquireCommStruct())
  438. {
  439. commStruct.InitHeader();
  440. }
  441. if (_session.GuardProcessWithJobInternal)
  442. {
  443. string jobName = ConsoleJob + _instanceName;
  444. _job = new Job(_logger, jobName);
  445. }
  446. }
  447. }
  448. private SafeFileHandle CreateFileMapping(string fileMappingName)
  449. {
  450. unsafe
  451. {
  452. IntPtr securityAttributesPtr = IntPtr.Zero;
  453. // We use the EventWaitHandleSecurity only to generate the descriptor binary form
  454. // that does not differ for object types, so we abuse the existing "event handle" implementation,
  455. // not to have to create the file mapping SecurityAttributes via P/Invoke.
  456. // .NET 4 supports MemoryMappedFile and MemoryMappedFileSecurity natively already
  457. EventWaitHandleSecurity security = CreateSecurity((EventWaitHandleRights)FileMappingRights.AllAccess);
  458. if (security != null)
  459. {
  460. SecurityAttributes securityAttributes = new SecurityAttributes();
  461. securityAttributes.nLength = (uint)Marshal.SizeOf(securityAttributes);
  462. byte[] descriptorBinaryForm = security.GetSecurityDescriptorBinaryForm();
  463. byte * buffer = stackalloc byte[descriptorBinaryForm.Length];
  464. for (int i = 0; i < descriptorBinaryForm.Length; i++)
  465. {
  466. buffer[i] = descriptorBinaryForm[i];
  467. }
  468. securityAttributes.lpSecurityDescriptor = (IntPtr)buffer;
  469. int length = Marshal.SizeOf(typeof(SecurityAttributes));
  470. securityAttributesPtr = Marshal.AllocHGlobal(length);
  471. Marshal.StructureToPtr(securityAttributes, securityAttributesPtr, false);
  472. }
  473. return
  474. UnsafeNativeMethods.CreateFileMapping(
  475. new SafeFileHandle(new IntPtr(-1), true), securityAttributesPtr, FileMapProtection.PageReadWrite, 0,
  476. ConsoleCommStruct.Size, fileMappingName);
  477. }
  478. }
  479. private ConsoleCommStruct AcquireCommStruct()
  480. {
  481. return new ConsoleCommStruct(_session, _fileMapping);
  482. }
  483. private bool TryCreateEvent(string name, out EventWaitHandle ev)
  484. {
  485. bool createdNew;
  486. _logger.WriteLine("Creating event {0}", name);
  487. EventWaitHandleSecurity security = CreateSecurity(EventWaitHandleRights.FullControl);
  488. ev = new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew, security);
  489. _logger.WriteLine(
  490. "Created event {0} with handle {1} with security {2}, new {3}",
  491. name, ev.SafeWaitHandle.DangerousGetHandle(),
  492. (security != null ? security.GetSecurityDescriptorSddlForm(AccessControlSections.All) : "none"), createdNew);
  493. return createdNew;
  494. }
  495. private EventWaitHandleSecurity CreateSecurity(EventWaitHandleRights eventRights)
  496. {
  497. EventWaitHandleSecurity security = null;
  498. // When "running as user", we have to grant the target user permissions to the objects (events and file mapping) explicitly
  499. if (!string.IsNullOrEmpty(_session.ExecutableProcessUserName))
  500. {
  501. security = new EventWaitHandleSecurity();
  502. IdentityReference si;
  503. try
  504. {
  505. si = new NTAccount(_session.ExecutableProcessUserName);
  506. }
  507. catch (Exception e)
  508. {
  509. throw new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "Error resolving account {0}", _session.ExecutableProcessUserName), e);
  510. }
  511. EventWaitHandleAccessRule rule =
  512. new EventWaitHandleAccessRule(
  513. si, eventRights, AccessControlType.Allow);
  514. security.AddAccessRule(rule);
  515. }
  516. return security;
  517. }
  518. private EventWaitHandle CreateEvent(string name)
  519. {
  520. EventWaitHandle ev;
  521. if (!TryCreateEvent(name, out ev))
  522. {
  523. throw new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Event {0} already exists", name));
  524. }
  525. return ev;
  526. }
  527. private void TestEventClosed(string name)
  528. {
  529. if (_session.TestHandlesClosedInternal)
  530. {
  531. _logger.WriteLine("Testing that event {0} is closed", name);
  532. EventWaitHandle ev;
  533. if (TryCreateEvent(name, out ev))
  534. {
  535. ev.Close();
  536. }
  537. else
  538. {
  539. _logger.WriteLine("Exception: Event {0} was not closed yet", name);
  540. }
  541. }
  542. }
  543. private void AddInput(string str)
  544. {
  545. Type structType = typeof(ConsoleInputEventStruct);
  546. FieldInfo strField = structType.GetField("Str");
  547. object[] attributes = strField.GetCustomAttributes(typeof(MarshalAsAttribute), false);
  548. if (attributes.Length != 1)
  549. {
  550. throw new InvalidOperationException("MarshalAs attribute not found for ConsoleInputEventStruct.Str");
  551. }
  552. MarshalAsAttribute marshalAsAttribute = (MarshalAsAttribute)attributes[0];
  553. if (marshalAsAttribute.SizeConst <= str.Length)
  554. {
  555. throw new SessionLocalException(
  556. _session,
  557. string.Format(CultureInfo.CurrentCulture, "Input [{0}] is too long ({1} limit)", str, marshalAsAttribute.SizeConst));
  558. }
  559. lock (_input)
  560. {
  561. _input.Add(str);
  562. _inputEvent.Set();
  563. }
  564. }
  565. public void ExecuteCommand(string command)
  566. {
  567. using (_logger.CreateCallstack())
  568. {
  569. AddInput(command);
  570. }
  571. }
  572. public void Close()
  573. {
  574. using (_logger.CreateCallstack())
  575. {
  576. int timeout;
  577. #if DEBUG
  578. // in debug build, we expect the winscp.exe to run in tracing mode, being very slow
  579. timeout = 10000;
  580. #else
  581. timeout = 2000;
  582. #endif
  583. _logger.WriteLine("Waiting for process to exit ({0} ms)", timeout);
  584. if (!_process.WaitForExit(timeout))
  585. {
  586. _logger.WriteLine("Killing process");
  587. _process.Kill();
  588. }
  589. }
  590. }
  591. public void Dispose()
  592. {
  593. using (_logger.CreateCallstack())
  594. {
  595. lock (_lock)
  596. {
  597. if (_session.TestHandlesClosedInternal)
  598. {
  599. _logger.WriteLine("Will test that handles are closed");
  600. }
  601. _abort = true;
  602. if (_thread != null)
  603. {
  604. _thread.Join();
  605. _thread = null;
  606. }
  607. if (_process != null)
  608. {
  609. _process.Dispose();
  610. _process = null;
  611. }
  612. if (_requestEvent != null)
  613. {
  614. _requestEvent.Close();
  615. TestEventClosed(ConsoleEventRequest + _instanceName);
  616. }
  617. if (_responseEvent != null)
  618. {
  619. _responseEvent.Close();
  620. TestEventClosed(ConsoleEventResponse + _instanceName);
  621. }
  622. if (_cancelEvent != null)
  623. {
  624. _cancelEvent.Close();
  625. TestEventClosed(ConsoleEventCancel + _instanceName);
  626. }
  627. if (_fileMapping != null)
  628. {
  629. _fileMapping.Dispose();
  630. _fileMapping = null;
  631. if (_session.TestHandlesClosedInternal)
  632. {
  633. _logger.WriteLine("Testing that file mapping is closed");
  634. string fileMappingName = ConsoleMapping + _instanceName;
  635. SafeFileHandle fileMapping = CreateFileMapping(fileMappingName);
  636. if (Marshal.GetLastWin32Error() == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  637. {
  638. _logger.WriteLine("Exception: File mapping {0} was not closed yet", fileMappingName);
  639. }
  640. if (!fileMapping.IsInvalid)
  641. {
  642. fileMapping.Dispose();
  643. }
  644. }
  645. }
  646. if (_inputEvent != null)
  647. {
  648. _inputEvent.Close();
  649. _inputEvent = null;
  650. }
  651. if (_job != null)
  652. {
  653. _job.Dispose();
  654. _job = null;
  655. }
  656. }
  657. }
  658. }
  659. private string GetExecutablePath()
  660. {
  661. using (_logger.CreateCallstack())
  662. {
  663. string executablePath;
  664. if (!string.IsNullOrEmpty(_session.ExecutablePath))
  665. {
  666. executablePath = _session.ExecutablePath;
  667. if (!File.Exists(executablePath))
  668. {
  669. throw new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "{0} does not exists.", executablePath));
  670. }
  671. }
  672. else
  673. {
  674. if (!TryFindExecutableInPath(GetAssemblyPath(), out executablePath) &&
  675. !TryFindExecutableInPath(GetInstallationPath(Registry.CurrentUser), out executablePath) &&
  676. !TryFindExecutableInPath(GetInstallationPath(Registry.LocalMachine), out executablePath) &&
  677. !TryFindExecutableInPath(GetDefaultInstallationPath(), out executablePath))
  678. {
  679. throw new SessionLocalException(_session,
  680. string.Format(CultureInfo.CurrentCulture,
  681. "The {0} executable was not found at location of the assembly ({1}), nor in an installation path. You may use Session.ExecutablePath property to explicitly set path to {0}.",
  682. ExeExecutableFileName, GetAssemblyPath()));
  683. }
  684. }
  685. return executablePath;
  686. }
  687. }
  688. private static string GetDefaultInstallationPath()
  689. {
  690. return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WinSCP");
  691. }
  692. private static string GetInstallationPath(RegistryKey rootKey)
  693. {
  694. RegistryKey key = rootKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\winscp3_is1");
  695. return (key != null) ? (string)key.GetValue("Inno Setup: App Path") : null;
  696. }
  697. private bool TryFindExecutableInPath(string path, out string result)
  698. {
  699. if (string.IsNullOrEmpty(path))
  700. {
  701. result = null;
  702. }
  703. else
  704. {
  705. string executablePath = Path.Combine(path, ExeExecutableFileName);
  706. if (File.Exists(executablePath))
  707. {
  708. result = executablePath;
  709. _logger.WriteLine("Executable found in {0}", executablePath);
  710. }
  711. else
  712. {
  713. result = null;
  714. _logger.WriteLine("Executable not found in {0}", executablePath);
  715. }
  716. }
  717. return (result != null);
  718. }
  719. private string GetAssemblyPath()
  720. {
  721. string codeBasePath = _logger.GetAssemblyFilePath();
  722. string path = null;
  723. if (!string.IsNullOrEmpty(codeBasePath))
  724. {
  725. path = Path.GetDirectoryName(codeBasePath);
  726. Debug.Assert(path != null);
  727. }
  728. return path;
  729. }
  730. private void CheckVersion(string exePath, FileVersionInfo assemblyVersion)
  731. {
  732. using (_logger.CreateCallstack())
  733. {
  734. FileVersionInfo version = FileVersionInfo.GetVersionInfo(exePath);
  735. _logger.WriteLine("Version of {0} is {1}, product {2} version is {3}", exePath, version.FileVersion, version.ProductName, version.ProductVersion);
  736. if (_session.DisableVersionCheck)
  737. {
  738. _logger.WriteLine("Version check disabled (not recommended)");
  739. }
  740. else if (assemblyVersion == null)
  741. {
  742. _logger.WriteLine("Assembly version not known, cannot check version");
  743. }
  744. else if (assemblyVersion.ProductVersion != version.ProductVersion)
  745. {
  746. throw new SessionLocalException(
  747. _session, string.Format(CultureInfo.CurrentCulture,
  748. "The version of {0} ({1}) does not match version of this assembly {2} ({3}).",
  749. exePath, version.ProductVersion, _logger.GetAssemblyFilePath(), assemblyVersion.ProductVersion));
  750. }
  751. }
  752. }
  753. public void WriteStatus()
  754. {
  755. string executablePath = GetExecutablePath();
  756. _logger.WriteLine("{0} - exists [{1}]", executablePath, File.Exists(executablePath));
  757. }
  758. private const int MaxAttempts = 10;
  759. private const string ConsoleMapping = "WinSCPConsoleMapping";
  760. private const string ConsoleEventRequest = "WinSCPConsoleEventRequest";
  761. private const string ConsoleEventResponse = "WinSCPConsoleEventResponse";
  762. private const string ConsoleEventCancel = "WinSCPConsoleEventCancel";
  763. private const string ConsoleJob = "WinSCPConsoleJob";
  764. private const string ExeExecutableFileName = "winscp.exe";
  765. private Process _process;
  766. private readonly object _lock = new object();
  767. private readonly Logger _logger;
  768. private readonly Session _session;
  769. private EventWaitHandle _requestEvent;
  770. private EventWaitHandle _responseEvent;
  771. private EventWaitHandle _cancelEvent;
  772. private SafeFileHandle _fileMapping;
  773. private string _instanceName;
  774. private Thread _thread;
  775. private bool _abort;
  776. private string _lastFromBeginning;
  777. private string _incompleteLine;
  778. private readonly List<string> _input = new List<string>();
  779. private AutoResetEvent _inputEvent = new AutoResetEvent(false);
  780. private Job _job;
  781. }
  782. }