ExeSessionProcess.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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.GuardProcessWithJob)
  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. FileTransferProgressEventArgs args = new FileTransferProgressEventArgs();
  293. switch (e.Operation)
  294. {
  295. case ConsoleProgressEventStruct.ProgressOperation.Copy:
  296. args.Operation = ProgressOperation.Transfer;
  297. break;
  298. default:
  299. throw new ArgumentOutOfRangeException("Unknown progress operation", (Exception)null);
  300. }
  301. switch (e.Side)
  302. {
  303. case ConsoleProgressEventStruct.ProgressSide.Local:
  304. args.Side = ProgressSide.Local;
  305. break;
  306. case ConsoleProgressEventStruct.ProgressSide.Remote:
  307. args.Side = ProgressSide.Remote;
  308. break;
  309. default:
  310. throw new ArgumentOutOfRangeException("Unknown progress side", (Exception)null);
  311. }
  312. args.FileName = e.FileName;
  313. args.Directory = e.Directory;
  314. args.OverallProgress = ((double)e.OverallProgress) / 100;
  315. args.FileProgress = ((double)e.FileProgress) / 100;
  316. args.CPS = (int) e.CPS;
  317. _session.ProcessProgress(args);
  318. }
  319. }
  320. private void InitializeConsole()
  321. {
  322. using (_logger.CreateCallstack())
  323. {
  324. int attempts = 0;
  325. Random random = new Random();
  326. int process = Process.GetCurrentProcess().Id;
  327. do
  328. {
  329. if (attempts > MaxAttempts)
  330. {
  331. throw new SessionLocalException(_session, "Cannot find unique name for event object.");
  332. }
  333. int instanceNumber = random.Next(1000);
  334. _instanceName = string.Format(CultureInfo.InvariantCulture, "_{0}_{1}", process, instanceNumber);
  335. _logger.WriteLine("Trying event {0}", _instanceName);
  336. if (!TryCreateEvent(ConsoleEventRequest + _instanceName, out _requestEvent))
  337. {
  338. _logger.WriteLine("Event {0} is not unique", _instanceName);
  339. _requestEvent.Close();
  340. _requestEvent = null;
  341. }
  342. else
  343. {
  344. _logger.WriteLine("Event {0} is unique", _instanceName);
  345. _responseEvent = CreateEvent(ConsoleEventResponse + _instanceName);
  346. _cancelEvent = CreateEvent(ConsoleEventCancel + _instanceName);
  347. string fileMappingName = ConsoleMapping + _instanceName;
  348. _fileMapping = CreateFileMapping(fileMappingName);
  349. if (Marshal.GetLastWin32Error() == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  350. {
  351. throw new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "File mapping {0} already exists", fileMappingName));
  352. }
  353. if (_fileMapping.IsInvalid)
  354. {
  355. throw new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Cannot create file mapping {0}", fileMappingName));
  356. }
  357. }
  358. ++attempts;
  359. }
  360. while (_requestEvent == null);
  361. using (ConsoleCommStruct commStruct = AcquireCommStruct())
  362. {
  363. commStruct.InitHeader();
  364. }
  365. }
  366. }
  367. private static SafeFileHandle CreateFileMapping(string fileMappingName)
  368. {
  369. return
  370. UnsafeNativeMethods.CreateFileMapping(
  371. new SafeFileHandle(new IntPtr(-1), true), IntPtr.Zero, FileMapProtection.PageReadWrite, 0,
  372. ConsoleCommStruct.Size, fileMappingName);
  373. }
  374. private ConsoleCommStruct AcquireCommStruct()
  375. {
  376. return new ConsoleCommStruct(_session, _fileMapping);
  377. }
  378. private static bool TryCreateEvent(string name, out EventWaitHandle ev)
  379. {
  380. bool createdNew;
  381. ev = new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew);
  382. return createdNew;
  383. }
  384. private EventWaitHandle CreateEvent(string name)
  385. {
  386. EventWaitHandle ev;
  387. if (!TryCreateEvent(name, out ev))
  388. {
  389. throw new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Event {0} already exists", name));
  390. }
  391. return ev;
  392. }
  393. public void ExecuteCommand(string command)
  394. {
  395. using (_logger.CreateCallstack())
  396. {
  397. lock (_input)
  398. {
  399. _input.Add(command);
  400. _inputEvent.Set();
  401. }
  402. }
  403. }
  404. public void Close()
  405. {
  406. using (_logger.CreateCallstack())
  407. {
  408. _logger.WriteLine("Waiting for process to exit");
  409. if (!_process.WaitForExit(1000))
  410. {
  411. _logger.WriteLine("Killing process");
  412. _process.Kill();
  413. }
  414. }
  415. }
  416. public void Dispose()
  417. {
  418. using (_logger.CreateCallstack())
  419. {
  420. lock (_lock)
  421. {
  422. _abort = true;
  423. if (_thread != null)
  424. {
  425. _thread.Join();
  426. _thread = null;
  427. }
  428. if (_process != null)
  429. {
  430. _process.Dispose();
  431. _process = null;
  432. }
  433. if (_requestEvent != null)
  434. {
  435. _requestEvent.Close();
  436. }
  437. if (_responseEvent != null)
  438. {
  439. _responseEvent.Close();
  440. }
  441. if (_cancelEvent != null)
  442. {
  443. _cancelEvent.Close();
  444. }
  445. if (_fileMapping != null)
  446. {
  447. _fileMapping.Dispose();
  448. _fileMapping = null;
  449. }
  450. if (_inputEvent != null)
  451. {
  452. _inputEvent.Close();
  453. _inputEvent = null;
  454. }
  455. if (_job != null)
  456. {
  457. _job.Dispose();
  458. _job = null;
  459. }
  460. }
  461. }
  462. }
  463. private string GetExecutablePath()
  464. {
  465. using (_logger.CreateCallstack())
  466. {
  467. string executablePath;
  468. if (!string.IsNullOrEmpty(_session.ExecutablePath))
  469. {
  470. executablePath = _session.ExecutablePath;
  471. if (!File.Exists(executablePath))
  472. {
  473. throw new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "{0} does not exists.", executablePath));
  474. }
  475. }
  476. else
  477. {
  478. if (!TryFindExecutableInPath(GetAssemblyPath(), out executablePath) &&
  479. !TryFindExecutableInPath(GetInstallationPath(Registry.CurrentUser), out executablePath) &&
  480. !TryFindExecutableInPath(GetInstallationPath(Registry.LocalMachine), out executablePath) &&
  481. !TryFindExecutableInPath(GetDefaultInstallationPath(), out executablePath))
  482. {
  483. throw new SessionLocalException(_session,
  484. string.Format(CultureInfo.CurrentCulture,
  485. "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}.",
  486. ExeExecutableFileName, GetAssemblyPath()));
  487. }
  488. }
  489. return executablePath;
  490. }
  491. }
  492. private static string GetDefaultInstallationPath()
  493. {
  494. return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WinSCP");
  495. }
  496. private static string GetInstallationPath(RegistryKey rootKey)
  497. {
  498. RegistryKey key = rootKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\winscp3_is1");
  499. return (key != null) ? (string)key.GetValue("Inno Setup: App Path") : null;
  500. }
  501. private bool TryFindExecutableInPath(string path, out string result)
  502. {
  503. if (string.IsNullOrEmpty(path))
  504. {
  505. result = null;
  506. }
  507. else
  508. {
  509. string executablePath = Path.Combine(path, ExeExecutableFileName);
  510. if (File.Exists(executablePath))
  511. {
  512. result = executablePath;
  513. _logger.WriteLine("Executable found in {0}", executablePath);
  514. }
  515. else
  516. {
  517. result = null;
  518. _logger.WriteLine("Executable not found in {0}", executablePath);
  519. }
  520. }
  521. return (result != null);
  522. }
  523. private string GetAssemblyPath()
  524. {
  525. string codeBasePath = _logger.GetAssemblyFilePath();
  526. string path = null;
  527. if (!string.IsNullOrEmpty(codeBasePath))
  528. {
  529. path = Path.GetDirectoryName(codeBasePath);
  530. Debug.Assert(path != null);
  531. }
  532. return path;
  533. }
  534. private void CheckVersion(string exePath, FileVersionInfo assemblyVersion)
  535. {
  536. using (_logger.CreateCallstack())
  537. {
  538. FileVersionInfo version = FileVersionInfo.GetVersionInfo(exePath);
  539. _logger.WriteLine("Version of {0} is {1}, product {2} version is {3}", exePath, version.FileVersion, version.ProductName, version.ProductVersion);
  540. if (_session.DisableVersionCheck)
  541. {
  542. _logger.WriteLine("Version check disabled (not recommended)");
  543. }
  544. else if (assemblyVersion == null)
  545. {
  546. _logger.WriteLine("Assembly version not known, cannot check version");
  547. }
  548. else if (assemblyVersion.ProductVersion != version.ProductVersion)
  549. {
  550. throw new SessionLocalException(
  551. _session, string.Format(CultureInfo.CurrentCulture,
  552. "The version of {0} ({1}) does not match version of this assembly {2} ({3}). You can disable this check using Session.DisableVersionCheck (not recommended).",
  553. exePath, version.ProductVersion, _logger.GetAssemblyFilePath(), assemblyVersion.ProductVersion));
  554. }
  555. }
  556. }
  557. public void WriteStatus()
  558. {
  559. string executablePath = GetExecutablePath();
  560. _logger.WriteLine("{0} - exists [{1}]", executablePath, File.Exists(executablePath));
  561. }
  562. private const int MaxAttempts = 10;
  563. private const string ConsoleMapping = "WinSCPConsoleMapping";
  564. private const string ConsoleEventRequest = "WinSCPConsoleEventRequest";
  565. private const string ConsoleEventResponse = "WinSCPConsoleEventResponse";
  566. private const string ConsoleEventCancel = "WinSCPConsoleEventCancel";
  567. private const string ExeExecutableFileName = "winscp.exe";
  568. private Process _process;
  569. private readonly object _lock = new object();
  570. private readonly Logger _logger;
  571. private readonly Session _session;
  572. private EventWaitHandle _requestEvent;
  573. private EventWaitHandle _responseEvent;
  574. private EventWaitHandle _cancelEvent;
  575. private SafeFileHandle _fileMapping;
  576. private string _instanceName;
  577. private Thread _thread;
  578. private bool _abort;
  579. private string _lastFromBeginning;
  580. private string _incompleteLine;
  581. private readonly List<string> _input = new List<string>();
  582. private AutoResetEvent _inputEvent = new AutoResetEvent(false);
  583. private Job _job;
  584. }
  585. }