ExeSessionProcess.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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. namespace WinSCP
  11. {
  12. internal class ExeSessionProcess : IDisposable
  13. {
  14. public event OutputDataReceivedEventHandler OutputDataReceived;
  15. public bool HasExited { get { return _process.HasExited; } }
  16. public int ExitCode { get { return _process.ExitCode; } }
  17. public ExeSessionProcess(Session session)
  18. {
  19. _session = session;
  20. _logger = session.Logger;
  21. _incompleteLine = string.Empty;
  22. using (_logger.CreateCallstack())
  23. {
  24. string executablePath = GetExecutablePath();
  25. _logger.WriteLine("EXE executable path resolved to {0}", executablePath);
  26. string assemblyFilePath = _logger.GetAssemblyFilePath();
  27. FileVersionInfo assemblyVersion = null;
  28. if (assemblyFilePath != null)
  29. {
  30. assemblyVersion = FileVersionInfo.GetVersionInfo(assemblyFilePath);
  31. }
  32. CheckVersion(executablePath, assemblyVersion);
  33. string configSwitch;
  34. if (_session.DefaultConfiguration)
  35. {
  36. configSwitch = "/ini=nul ";
  37. }
  38. else
  39. {
  40. if (!string.IsNullOrEmpty(_session.IniFilePath))
  41. {
  42. configSwitch = string.Format(CultureInfo.InvariantCulture, "/ini=\"{0}\" ", _session.IniFilePath);
  43. }
  44. else
  45. {
  46. configSwitch = "";
  47. }
  48. }
  49. string logSwitch = null;
  50. if (!string.IsNullOrEmpty(_session.SessionLogPath))
  51. {
  52. logSwitch = string.Format(CultureInfo.InvariantCulture, "/log=\"{0}\" ", LogPathEscape(_session.SessionLogPath));
  53. }
  54. string xmlLogSwitch = string.Format(CultureInfo.InvariantCulture, "/xmllog=\"{0}\" ", LogPathEscape(_session.XmlLogPath));
  55. string assemblyVersionStr =
  56. (assemblyVersion == null) ? "unk" :
  57. string.Format(CultureInfo.InvariantCulture, "{0}{1}{2} ", assemblyVersion.ProductMajorPart, assemblyVersion.ProductMinorPart, assemblyVersion.ProductBuildPart);
  58. string assemblyVersionSwitch =
  59. string.Format(CultureInfo.InvariantCulture, "/dotnet={0} ", assemblyVersionStr);
  60. string arguments =
  61. xmlLogSwitch + "/xmlgroups /nointeractiveinput " + assemblyVersionSwitch +
  62. configSwitch + logSwitch + _session.AdditionalExecutableArguments;
  63. _process = new Process();
  64. _process.StartInfo.FileName = executablePath;
  65. _process.StartInfo.WorkingDirectory = Path.GetDirectoryName(executablePath);
  66. _process.StartInfo.Arguments = arguments;
  67. _process.StartInfo.UseShellExecute = false;
  68. _process.Exited += ProcessExited;
  69. if (_logger.Logging)
  70. {
  71. _process.OutputDataReceived += ProcessOutputDataReceived;
  72. _process.ErrorDataReceived += ProcessErrorDataReceived;
  73. }
  74. }
  75. }
  76. private static string LogPathEscape(string path)
  77. {
  78. return Session.ArgumentEscape(path).Replace("!", "!!");
  79. }
  80. public void Abort()
  81. {
  82. using (_logger.CreateCallstack())
  83. {
  84. lock (_lock)
  85. {
  86. if ((_process != null) && !_process.HasExited)
  87. {
  88. _process.Kill();
  89. }
  90. }
  91. }
  92. }
  93. public void Start()
  94. {
  95. using (_logger.CreateCallstack())
  96. {
  97. InitializeConsole();
  98. InitializeChild();
  99. }
  100. }
  101. private void InitializeChild()
  102. {
  103. using (_logger.CreateCallstack())
  104. {
  105. _process.StartInfo.Arguments += string.Format(CultureInfo.InvariantCulture, " /console /consoleinstance={0}", _instanceName);
  106. _logger.WriteLine("Starting \"{0}\" {1}", _process.StartInfo.FileName, _process.StartInfo.Arguments);
  107. _process.Start();
  108. _logger.WriteLine("Started process {0}", _process.Id);
  109. if (_session.GuardProcessWithJobInternal)
  110. {
  111. _job = new Job();
  112. _job.AddProcess(_process.Handle);
  113. }
  114. _thread = new Thread(ProcessEvents);
  115. _thread.IsBackground = true;
  116. _thread.Start();
  117. }
  118. }
  119. private void ProcessExited(object sender, EventArgs e)
  120. {
  121. _logger.WriteLine("Process {0} exited with exit code {1}", _process.Id, _process.ExitCode);
  122. }
  123. private void ProcessOutputDataReceived(object sender, DataReceivedEventArgs e)
  124. {
  125. _logger.WriteLine("Process output: {0}", e.Data);
  126. }
  127. private void ProcessErrorDataReceived(object sender, DataReceivedEventArgs e)
  128. {
  129. _logger.WriteLine("Process error output: {0}", e.Data);
  130. }
  131. private bool AbortedOrExited()
  132. {
  133. if (_abort)
  134. {
  135. _logger.WriteLine("Aborted");
  136. return true;
  137. }
  138. else if (_process.HasExited)
  139. {
  140. _logger.WriteLine("Exited");
  141. return true;
  142. }
  143. else
  144. {
  145. return false;
  146. }
  147. }
  148. private void ProcessEvents()
  149. {
  150. using (_logger.CreateCallstack())
  151. {
  152. while (!AbortedOrExited())
  153. {
  154. if (_requestEvent.WaitOne(100, false))
  155. {
  156. ProcessEvent();
  157. }
  158. }
  159. }
  160. }
  161. private void ProcessEvent()
  162. {
  163. using (_logger.CreateCallstack())
  164. {
  165. using (ConsoleCommStruct commStruct = AcquireCommStruct())
  166. {
  167. switch (commStruct.Event)
  168. {
  169. case ConsoleEvent.Print:
  170. ProcessPrintEvent(commStruct.PrintEvent);
  171. break;
  172. case ConsoleEvent.Input:
  173. ProcessInputEvent(commStruct.InputEvent);
  174. break;
  175. case ConsoleEvent.Choice:
  176. ProcessChoiceEvent(commStruct.ChoiceEvent);
  177. break;
  178. case ConsoleEvent.Title:
  179. ProcessTitleEvent(commStruct.TitleEvent);
  180. break;
  181. case ConsoleEvent.Init:
  182. ProcessInitEvent(commStruct.InitEvent);
  183. break;
  184. case ConsoleEvent.Progress:
  185. ProcessProgressEvent(commStruct.ProgressEvent);
  186. break;
  187. default:
  188. throw new NotImplementedException();
  189. }
  190. }
  191. _responseEvent.Set();
  192. }
  193. }
  194. private void ProcessChoiceEvent(ConsoleChoiceEventStruct e)
  195. {
  196. using (_logger.CreateCallstack())
  197. {
  198. if (e.Timeouting)
  199. {
  200. Thread.Sleep((int)e.Timer);
  201. e.Result = e.Timeouted;
  202. }
  203. else
  204. {
  205. e.Result = e.Break;
  206. }
  207. }
  208. }
  209. private void ProcessTitleEvent(ConsoleTitleEventStruct e)
  210. {
  211. using (_logger.CreateCallstack())
  212. {
  213. _logger.WriteLine("Not-supported title event [{0}]", e.Title);
  214. }
  215. }
  216. private void ProcessInputEvent(ConsoleInputEventStruct e)
  217. {
  218. using (_logger.CreateCallstack())
  219. {
  220. while (!AbortedOrExited())
  221. {
  222. lock (_input)
  223. {
  224. if (_input.Count > 0)
  225. {
  226. e.Str = _input[0];
  227. e.Result = true;
  228. _input.RemoveAt(0);
  229. Print(false, e.Str + "\n");
  230. return;
  231. }
  232. }
  233. _inputEvent.WaitOne(100, false);
  234. }
  235. }
  236. }
  237. private void Print(bool fromBeginning, string message)
  238. {
  239. if (fromBeginning && ((message.Length == 0) || (message[0] != '\n')))
  240. {
  241. _lastFromBeginning = message;
  242. _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);
  243. }
  244. else
  245. {
  246. if (!string.IsNullOrEmpty(_lastFromBeginning))
  247. {
  248. AddToOutput(_lastFromBeginning);
  249. _lastFromBeginning = null;
  250. }
  251. if (fromBeginning && (message.Length > 0) && (message[0] == '\n'))
  252. {
  253. AddToOutput("\n");
  254. _lastFromBeginning = message.Substring(1);
  255. _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);
  256. }
  257. else
  258. {
  259. AddToOutput(message);
  260. }
  261. }
  262. }
  263. private void AddToOutput(string message)
  264. {
  265. string[] lines = (_incompleteLine + message).Split(new[] { '\n' });
  266. _incompleteLine = lines[lines.Length - 1];
  267. for (int i = 0; i < lines.Length - 1; ++i)
  268. {
  269. if (OutputDataReceived != null)
  270. {
  271. OutputDataReceived(this, new OutputDataReceivedEventArgs(lines[i]));
  272. }
  273. }
  274. }
  275. private void ProcessPrintEvent(ConsolePrintEventStruct e)
  276. {
  277. Print(e.FromBeginning, e.Message);
  278. }
  279. private void ProcessInitEvent(ConsoleInitEventStruct e)
  280. {
  281. using (_logger.CreateCallstack())
  282. {
  283. e.InputType = 3; // pipe
  284. e.OutputType = 3; // pipe
  285. e.WantsProgress = _session.WantsProgress;
  286. }
  287. }
  288. private void ProcessProgressEvent(ConsoleProgressEventStruct e)
  289. {
  290. using (_logger.CreateCallstack())
  291. {
  292. _logger.WriteLine(
  293. "File Name [{0}] - Directory [{1}] - Overall Progress [{2}] - File Progress [{3}] - CPS [{4}]",
  294. e.FileName, e.Directory, e.OverallProgress, e.FileProgress, e.CPS);
  295. FileTransferProgressEventArgs args = new FileTransferProgressEventArgs();
  296. switch (e.Operation)
  297. {
  298. case ConsoleProgressEventStruct.ProgressOperation.Copy:
  299. args.Operation = ProgressOperation.Transfer;
  300. break;
  301. default:
  302. throw new ArgumentOutOfRangeException("Unknown progress operation", (Exception)null);
  303. }
  304. switch (e.Side)
  305. {
  306. case ConsoleProgressEventStruct.ProgressSide.Local:
  307. args.Side = ProgressSide.Local;
  308. break;
  309. case ConsoleProgressEventStruct.ProgressSide.Remote:
  310. args.Side = ProgressSide.Remote;
  311. break;
  312. default:
  313. throw new ArgumentOutOfRangeException("Unknown progress side", (Exception)null);
  314. }
  315. args.FileName = e.FileName;
  316. args.Directory = e.Directory;
  317. args.OverallProgress = ((double)e.OverallProgress) / 100;
  318. args.FileProgress = ((double)e.FileProgress) / 100;
  319. args.CPS = (int) e.CPS;
  320. _session.ProcessProgress(args);
  321. }
  322. }
  323. private void InitializeConsole()
  324. {
  325. using (_logger.CreateCallstack())
  326. {
  327. int attempts = 0;
  328. Random random = new Random();
  329. int process = Process.GetCurrentProcess().Id;
  330. do
  331. {
  332. if (attempts > MaxAttempts)
  333. {
  334. throw new SessionLocalException(_session, "Cannot find unique name for event object.");
  335. }
  336. int instanceNumber = random.Next(1000);
  337. _instanceName = string.Format(CultureInfo.InvariantCulture, "_{0}_{1}", process, instanceNumber);
  338. _logger.WriteLine("Trying event {0}", _instanceName);
  339. if (!TryCreateEvent(ConsoleEventRequest + _instanceName, out _requestEvent))
  340. {
  341. _logger.WriteLine("Event {0} is not unique", _instanceName);
  342. _requestEvent.Close();
  343. _requestEvent = null;
  344. }
  345. else
  346. {
  347. _logger.WriteLine("Event {0} is unique", _instanceName);
  348. _responseEvent = CreateEvent(ConsoleEventResponse + _instanceName);
  349. _cancelEvent = CreateEvent(ConsoleEventCancel + _instanceName);
  350. string fileMappingName = ConsoleMapping + _instanceName;
  351. _fileMapping = CreateFileMapping(fileMappingName);
  352. if (Marshal.GetLastWin32Error() == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  353. {
  354. throw new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "File mapping {0} already exists", fileMappingName));
  355. }
  356. if (_fileMapping.IsInvalid)
  357. {
  358. throw new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Cannot create file mapping {0}", fileMappingName));
  359. }
  360. }
  361. ++attempts;
  362. }
  363. while (_requestEvent == null);
  364. using (ConsoleCommStruct commStruct = AcquireCommStruct())
  365. {
  366. commStruct.InitHeader();
  367. }
  368. }
  369. }
  370. private static SafeFileHandle CreateFileMapping(string fileMappingName)
  371. {
  372. return
  373. UnsafeNativeMethods.CreateFileMapping(
  374. new SafeFileHandle(new IntPtr(-1), true), IntPtr.Zero, FileMapProtection.PageReadWrite, 0,
  375. ConsoleCommStruct.Size, fileMappingName);
  376. }
  377. private ConsoleCommStruct AcquireCommStruct()
  378. {
  379. return new ConsoleCommStruct(_session, _fileMapping);
  380. }
  381. private static bool TryCreateEvent(string name, out EventWaitHandle ev)
  382. {
  383. bool createdNew;
  384. ev = new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew);
  385. return createdNew;
  386. }
  387. private EventWaitHandle CreateEvent(string name)
  388. {
  389. EventWaitHandle ev;
  390. if (!TryCreateEvent(name, out ev))
  391. {
  392. throw new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Event {0} already exists", name));
  393. }
  394. return ev;
  395. }
  396. private void TestEventClosed(string name)
  397. {
  398. if (_session.TestHandlesClosedInternal)
  399. {
  400. _logger.WriteLine("Testing that event {0} is closed", name);
  401. EventWaitHandle ev;
  402. if (TryCreateEvent(name, out ev))
  403. {
  404. ev.Close();
  405. }
  406. else
  407. {
  408. _logger.WriteLine("Exception: Event {0} was not closed yet", name);
  409. }
  410. }
  411. }
  412. public void ExecuteCommand(string command)
  413. {
  414. using (_logger.CreateCallstack())
  415. {
  416. lock (_input)
  417. {
  418. _input.Add(command);
  419. _inputEvent.Set();
  420. }
  421. }
  422. }
  423. public void Close()
  424. {
  425. using (_logger.CreateCallstack())
  426. {
  427. _logger.WriteLine("Waiting for process to exit");
  428. if (!_process.WaitForExit(1000))
  429. {
  430. _logger.WriteLine("Killing process");
  431. _process.Kill();
  432. }
  433. }
  434. }
  435. public void Dispose()
  436. {
  437. using (_logger.CreateCallstack())
  438. {
  439. lock (_lock)
  440. {
  441. if (_session.TestHandlesClosedInternal)
  442. {
  443. _logger.WriteLine("Will test that handles are closed");
  444. }
  445. _abort = true;
  446. if (_thread != null)
  447. {
  448. _thread.Join();
  449. _thread = null;
  450. }
  451. if (_process != null)
  452. {
  453. _process.Dispose();
  454. _process = null;
  455. }
  456. if (_requestEvent != null)
  457. {
  458. _requestEvent.Close();
  459. TestEventClosed(ConsoleEventRequest + _instanceName);
  460. }
  461. if (_responseEvent != null)
  462. {
  463. _responseEvent.Close();
  464. TestEventClosed(ConsoleEventResponse + _instanceName);
  465. }
  466. if (_cancelEvent != null)
  467. {
  468. _cancelEvent.Close();
  469. TestEventClosed(ConsoleEventCancel + _instanceName);
  470. }
  471. if (_fileMapping != null)
  472. {
  473. _fileMapping.Dispose();
  474. _fileMapping = null;
  475. if (_session.TestHandlesClosedInternal)
  476. {
  477. _logger.WriteLine("Testing that file mapping is closed");
  478. string fileMappingName = ConsoleMapping + _instanceName;
  479. SafeFileHandle fileMapping = CreateFileMapping(fileMappingName);
  480. if (Marshal.GetLastWin32Error() == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  481. {
  482. _logger.WriteLine("Exception: File mapping {0} was not closed yet", fileMappingName);
  483. }
  484. if (!fileMapping.IsInvalid)
  485. {
  486. fileMapping.Dispose();
  487. }
  488. }
  489. }
  490. if (_inputEvent != null)
  491. {
  492. _inputEvent.Close();
  493. _inputEvent = null;
  494. }
  495. if (_job != null)
  496. {
  497. _job.Dispose();
  498. _job = null;
  499. }
  500. }
  501. }
  502. }
  503. private string GetExecutablePath()
  504. {
  505. using (_logger.CreateCallstack())
  506. {
  507. string executablePath;
  508. if (!string.IsNullOrEmpty(_session.ExecutablePath))
  509. {
  510. executablePath = _session.ExecutablePath;
  511. if (!File.Exists(executablePath))
  512. {
  513. throw new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "{0} does not exists.", executablePath));
  514. }
  515. }
  516. else
  517. {
  518. if (!TryFindExecutableInPath(GetAssemblyPath(), out executablePath) &&
  519. !TryFindExecutableInPath(GetInstallationPath(Registry.CurrentUser), out executablePath) &&
  520. !TryFindExecutableInPath(GetInstallationPath(Registry.LocalMachine), out executablePath) &&
  521. !TryFindExecutableInPath(GetDefaultInstallationPath(), out executablePath))
  522. {
  523. throw new SessionLocalException(_session,
  524. string.Format(CultureInfo.CurrentCulture,
  525. "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}.",
  526. ExeExecutableFileName, GetAssemblyPath()));
  527. }
  528. }
  529. return executablePath;
  530. }
  531. }
  532. private static string GetDefaultInstallationPath()
  533. {
  534. return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WinSCP");
  535. }
  536. private static string GetInstallationPath(RegistryKey rootKey)
  537. {
  538. RegistryKey key = rootKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\winscp3_is1");
  539. return (key != null) ? (string)key.GetValue("Inno Setup: App Path") : null;
  540. }
  541. private bool TryFindExecutableInPath(string path, out string result)
  542. {
  543. if (string.IsNullOrEmpty(path))
  544. {
  545. result = null;
  546. }
  547. else
  548. {
  549. string executablePath = Path.Combine(path, ExeExecutableFileName);
  550. if (File.Exists(executablePath))
  551. {
  552. result = executablePath;
  553. _logger.WriteLine("Executable found in {0}", executablePath);
  554. }
  555. else
  556. {
  557. result = null;
  558. _logger.WriteLine("Executable not found in {0}", executablePath);
  559. }
  560. }
  561. return (result != null);
  562. }
  563. private string GetAssemblyPath()
  564. {
  565. string codeBasePath = _logger.GetAssemblyFilePath();
  566. string path = null;
  567. if (!string.IsNullOrEmpty(codeBasePath))
  568. {
  569. path = Path.GetDirectoryName(codeBasePath);
  570. Debug.Assert(path != null);
  571. }
  572. return path;
  573. }
  574. private void CheckVersion(string exePath, FileVersionInfo assemblyVersion)
  575. {
  576. using (_logger.CreateCallstack())
  577. {
  578. FileVersionInfo version = FileVersionInfo.GetVersionInfo(exePath);
  579. _logger.WriteLine("Version of {0} is {1}, product {2} version is {3}", exePath, version.FileVersion, version.ProductName, version.ProductVersion);
  580. if (_session.DisableVersionCheck)
  581. {
  582. _logger.WriteLine("Version check disabled (not recommended)");
  583. }
  584. else if (assemblyVersion == null)
  585. {
  586. _logger.WriteLine("Assembly version not known, cannot check version");
  587. }
  588. else if (assemblyVersion.ProductVersion != version.ProductVersion)
  589. {
  590. throw new SessionLocalException(
  591. _session, string.Format(CultureInfo.CurrentCulture,
  592. "The version of {0} ({1}) does not match version of this assembly {2} ({3}). You can disable this check using Session.DisableVersionCheck (not recommended).",
  593. exePath, version.ProductVersion, _logger.GetAssemblyFilePath(), assemblyVersion.ProductVersion));
  594. }
  595. }
  596. }
  597. public void WriteStatus()
  598. {
  599. string executablePath = GetExecutablePath();
  600. _logger.WriteLine("{0} - exists [{1}]", executablePath, File.Exists(executablePath));
  601. }
  602. private const int MaxAttempts = 10;
  603. private const string ConsoleMapping = "WinSCPConsoleMapping";
  604. private const string ConsoleEventRequest = "WinSCPConsoleEventRequest";
  605. private const string ConsoleEventResponse = "WinSCPConsoleEventResponse";
  606. private const string ConsoleEventCancel = "WinSCPConsoleEventCancel";
  607. private const string ExeExecutableFileName = "winscp.exe";
  608. private Process _process;
  609. private readonly object _lock = new object();
  610. private readonly Logger _logger;
  611. private readonly Session _session;
  612. private EventWaitHandle _requestEvent;
  613. private EventWaitHandle _responseEvent;
  614. private EventWaitHandle _cancelEvent;
  615. private SafeFileHandle _fileMapping;
  616. private string _instanceName;
  617. private Thread _thread;
  618. private bool _abort;
  619. private string _lastFromBeginning;
  620. private string _incompleteLine;
  621. private readonly List<string> _input = new List<string>();
  622. private AutoResetEvent _inputEvent = new AutoResetEvent(false);
  623. private Job _job;
  624. }
  625. }