ExeSessionProcess.cs 23 KB

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