ExeSessionProcess.cs 34 KB

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