ExeSessionProcess.cs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  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. #if !NETSTANDARD
  8. using Microsoft.Win32;
  9. #endif
  10. using Microsoft.Win32.SafeHandles;
  11. using System.Runtime.InteropServices;
  12. using System.Reflection;
  13. #if !NETSTANDARD
  14. using System.Security.Principal;
  15. using System.Security.AccessControl;
  16. #endif
  17. using System.ComponentModel;
  18. using System.Security.Cryptography;
  19. namespace WinSCP
  20. {
  21. internal class ExeSessionProcess : IDisposable
  22. {
  23. public event OutputDataReceivedEventHandler OutputDataReceived;
  24. public bool HasExited { get { return _process.HasExited; } }
  25. public int ExitCode { get { return _process.ExitCode; } }
  26. public PipeStream StdOut { get; set; }
  27. public Stream StdIn { get; set; }
  28. public string ExecutablePath { get; }
  29. public static ExeSessionProcess CreateForSession(Session session)
  30. {
  31. return new ExeSessionProcess(session, true, null);
  32. }
  33. public static ExeSessionProcess CreateForConsole(Session session, string additionalArguments)
  34. {
  35. return new ExeSessionProcess(session, false, additionalArguments);
  36. }
  37. private ExeSessionProcess(Session session, bool useXmlLog, string additionalArguments)
  38. {
  39. _session = session;
  40. _logger = session.Logger;
  41. _incompleteLine = string.Empty;
  42. using (_logger.CreateCallstack())
  43. {
  44. ExecutablePath = GetExecutablePath();
  45. _logger.WriteLine("EXE executable path resolved to {0}", ExecutablePath);
  46. string assemblyFilePath = _logger.GetAssemblyFilePath();
  47. FileVersionInfo assemblyVersion = null;
  48. if (assemblyFilePath != null)
  49. {
  50. assemblyVersion = FileVersionInfo.GetVersionInfo(assemblyFilePath);
  51. }
  52. CheckVersion(ExecutablePath, assemblyVersion);
  53. string configSwitch;
  54. if (_session.DefaultConfigurationInternal)
  55. {
  56. configSwitch = "/ini=nul ";
  57. }
  58. else
  59. {
  60. if (!string.IsNullOrEmpty(_session.IniFilePathInternal))
  61. {
  62. configSwitch = string.Format(CultureInfo.InvariantCulture, "/ini=\"{0}\" ", _session.IniFilePathInternal);
  63. }
  64. else
  65. {
  66. configSwitch = "";
  67. }
  68. }
  69. string logSwitch = null;
  70. if (!string.IsNullOrEmpty(_session.SessionLogPath))
  71. {
  72. logSwitch = string.Format(CultureInfo.InvariantCulture, "/log=\"{0}\" ", LogPathEscape(_session.SessionLogPath));
  73. }
  74. string xmlLogSwitch;
  75. if (useXmlLog)
  76. {
  77. xmlLogSwitch = string.Format(CultureInfo.InvariantCulture, "/xmllog=\"{0}\" /xmlgroups /xmllogrequired ", LogPathEscape(_session.XmlLogPath));
  78. }
  79. else
  80. {
  81. xmlLogSwitch = "";
  82. }
  83. string logLevelSwitch = null;
  84. if (_session.DebugLogLevel != 0)
  85. {
  86. logLevelSwitch = string.Format(CultureInfo.InvariantCulture, "/loglevel={0} ", _session.DebugLogLevel);
  87. }
  88. string assemblyVersionStr =
  89. (assemblyVersion == null) ? "unk" :
  90. string.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2} ", assemblyVersion.ProductMajorPart, assemblyVersion.ProductMinorPart, assemblyVersion.ProductBuildPart);
  91. string assemblyVersionSwitch =
  92. string.Format(CultureInfo.InvariantCulture, "/dotnet={0} ", assemblyVersionStr);
  93. string arguments =
  94. xmlLogSwitch + "/nointeractiveinput /stdout /stdin " + assemblyVersionSwitch +
  95. configSwitch + logSwitch + logLevelSwitch + _session.AdditionalExecutableArguments;
  96. Tools.AddRawParameters(ref arguments, _session.RawConfiguration, "/rawconfig", false);
  97. if (!string.IsNullOrEmpty(additionalArguments))
  98. {
  99. arguments += " " + additionalArguments;
  100. }
  101. _process = new Process();
  102. _process.StartInfo.FileName = ExecutablePath;
  103. _process.StartInfo.WorkingDirectory = Path.GetDirectoryName(ExecutablePath);
  104. _process.StartInfo.Arguments = arguments;
  105. _process.StartInfo.UseShellExecute = false;
  106. _process.Exited += ProcessExited;
  107. }
  108. }
  109. private static string LogPathEscape(string path)
  110. {
  111. return Tools.ArgumentEscape(path).Replace("!", "!!");
  112. }
  113. public void Abort()
  114. {
  115. using (_logger.CreateCallstack())
  116. {
  117. lock (_lock)
  118. {
  119. if ((_process != null) && !_process.HasExited)
  120. {
  121. _process.Kill();
  122. }
  123. }
  124. }
  125. }
  126. public void Start()
  127. {
  128. using (_logger.CreateCallstack())
  129. {
  130. InitializeConsole();
  131. InitializeChild();
  132. }
  133. }
  134. private void InitializeChild()
  135. {
  136. using (_logger.CreateCallstack())
  137. {
  138. // The /console is redundant for CreateForConsole
  139. _process.StartInfo.Arguments += string.Format(CultureInfo.InvariantCulture, " /console /consoleinstance={0}", _instanceName);
  140. #if !NETSTANDARD
  141. // When running under IIS in "impersonated" mode, the process starts, but does not do anything.
  142. // Supposedly it "displayes" some invisible error message when starting and hangs.
  143. // Running it "as the user" helps, eventhough it already runs as the user.
  144. // These's probably some difference between "run as" and impersonations
  145. if (!string.IsNullOrEmpty(_session.ExecutableProcessUserName))
  146. {
  147. _logger.WriteLine("Will run process as {0}", _session.ExecutableProcessUserName);
  148. _process.StartInfo.UserName = _session.ExecutableProcessUserName;
  149. _process.StartInfo.Password = _session.ExecutableProcessPassword;
  150. // One of the hints for resolving C0000142 error (see below)
  151. // was setting this property, so that an environment is correctly loaded,
  152. // so DLLs can be found and loaded.
  153. _process.StartInfo.LoadUserProfile = true;
  154. // Without granting both window station and desktop access permissions,
  155. // WinSCP process aborts with C0000142 (DLL Initialization Failed) error,
  156. // when "running as user"
  157. _logger.WriteLine("Granting access to window station");
  158. try
  159. {
  160. IntPtr windowStation = UnsafeNativeMethods.GetProcessWindowStation();
  161. GrantAccess(windowStation, (int)WindowStationRights.AllAccess);
  162. }
  163. catch (Exception e)
  164. {
  165. throw _logger.WriteException(new SessionLocalException(_session, "Error granting access to window station", e));
  166. }
  167. _logger.WriteLine("Granting access to desktop");
  168. try
  169. {
  170. IntPtr desktop = UnsafeNativeMethods.GetThreadDesktop(UnsafeNativeMethods.GetCurrentThreadId());
  171. GrantAccess(desktop, (int)DesktopRights.AllAccess);
  172. }
  173. catch (Exception e)
  174. {
  175. throw _logger.WriteException(new SessionLocalException(_session, "Error granting access to desktop", e));
  176. }
  177. }
  178. #endif
  179. _logger.WriteLine("Starting \"{0}\" {1}", _process.StartInfo.FileName, _process.StartInfo.Arguments);
  180. _process.Start();
  181. _logger.WriteLine("Started process {0}", _process.Id);
  182. _thread = new Thread(ProcessEvents)
  183. {
  184. IsBackground = true
  185. };
  186. _thread.Start();
  187. }
  188. }
  189. // Handles returned by GetProcessWindowStation and GetThreadDesktop should not be closed
  190. internal class NoopSafeHandle : SafeHandle
  191. {
  192. public NoopSafeHandle(IntPtr handle) :
  193. base(handle, false)
  194. {
  195. }
  196. public override bool IsInvalid
  197. {
  198. get { return false; }
  199. }
  200. protected override bool ReleaseHandle()
  201. {
  202. return true;
  203. }
  204. }
  205. #if !NETSTANDARD
  206. private void GrantAccess(IntPtr handle, int accessMask)
  207. {
  208. using (SafeHandle safeHandle = new NoopSafeHandle(handle))
  209. {
  210. GenericSecurity security =
  211. new GenericSecurity(false, ResourceType.WindowObject, safeHandle, AccessControlSections.Access);
  212. security.AddAccessRule(
  213. new GenericAccessRule(new NTAccount(_session.ExecutableProcessUserName), accessMask, AccessControlType.Allow));
  214. security.Persist(safeHandle, AccessControlSections.Access);
  215. }
  216. }
  217. #endif
  218. private void ProcessExited(object sender, EventArgs e)
  219. {
  220. _logger.WriteLine("Process {0} exited with exit code {1}", _process.Id, _process.ExitCode);
  221. }
  222. private bool AbortedOrExited()
  223. {
  224. if (_abort)
  225. {
  226. _logger.WriteLine("Aborted");
  227. return true;
  228. }
  229. else if (_process.HasExited)
  230. {
  231. _logger.WriteLine("Exited");
  232. return true;
  233. }
  234. else
  235. {
  236. return false;
  237. }
  238. }
  239. private void ProcessEvents()
  240. {
  241. using (_logger.CreateCallstack())
  242. {
  243. try
  244. {
  245. while (!AbortedOrExited())
  246. {
  247. _logger.WriteLineLevel(1, "Waiting for request event");
  248. // Keep in sync with a delay in SessionLogReader.DoRead
  249. if (_requestEvent.WaitOne(100, false))
  250. {
  251. _logger.WriteLineLevel(1, "Got request event");
  252. ProcessEvent();
  253. }
  254. if (_logger.LogLevel >= 1)
  255. {
  256. _logger.WriteLine(string.Format(CultureInfo.InvariantCulture, "2nd generation collection count: {0}", GC.CollectionCount(2)));
  257. _logger.WriteLine(string.Format(CultureInfo.InvariantCulture, "Total memory allocated: {0}", GC.GetTotalMemory(false)));
  258. }
  259. }
  260. }
  261. catch (Exception e)
  262. {
  263. _logger.WriteLine("Error while processing events");
  264. _logger.WriteException(e);
  265. throw;
  266. }
  267. }
  268. }
  269. private void ProcessEvent()
  270. {
  271. using (_logger.CreateCallstack())
  272. {
  273. using (ConsoleCommStruct commStruct = AcquireCommStruct())
  274. {
  275. switch (commStruct.Event)
  276. {
  277. case ConsoleEvent.Print:
  278. ProcessPrintEvent(commStruct.PrintEvent);
  279. break;
  280. case ConsoleEvent.Input:
  281. ProcessInputEvent(commStruct.InputEvent);
  282. break;
  283. case ConsoleEvent.Choice:
  284. ProcessChoiceEvent(commStruct.ChoiceEvent);
  285. break;
  286. case ConsoleEvent.Title:
  287. ProcessTitleEvent(commStruct.TitleEvent);
  288. break;
  289. case ConsoleEvent.Init:
  290. ProcessInitEvent(commStruct.InitEvent);
  291. break;
  292. case ConsoleEvent.Progress:
  293. ProcessProgressEvent(commStruct.ProgressEvent);
  294. break;
  295. case ConsoleEvent.TransferOut:
  296. ProcessTransferOutEvent(commStruct.TransferOutEvent);
  297. break;
  298. case ConsoleEvent.TransferIn:
  299. ProcessTransferInEvent(commStruct.TransferInEvent);
  300. break;
  301. default:
  302. throw _logger.WriteException(new NotImplementedException());
  303. }
  304. }
  305. _responseEvent.Set();
  306. _logger.WriteLineLevel(1, "Response event set");
  307. }
  308. }
  309. private void ProcessChoiceEvent(ConsoleChoiceEventStruct e)
  310. {
  311. using (_logger.CreateCallstack())
  312. {
  313. _logger.WriteLine(
  314. "Options: [{0}], Timer: [{1}], Timeouting: [{2}], Timeouted: [{3}], Break: [{4}]",
  315. e.Options, e.Timer, e.Timeouting, e.Timeouted, e.Break);
  316. QueryReceivedEventArgs args = new QueryReceivedEventArgs
  317. {
  318. Message = e.Message
  319. };
  320. _session.ProcessChoice(args);
  321. if (args.SelectedAction == QueryReceivedEventArgs.Action.None)
  322. {
  323. if (e.Timeouting)
  324. {
  325. Thread.Sleep((int)e.Timer);
  326. e.Result = e.Timeouted;
  327. }
  328. else
  329. {
  330. e.Result = e.Break;
  331. }
  332. }
  333. else if (args.SelectedAction == QueryReceivedEventArgs.Action.Continue)
  334. {
  335. if (e.Timeouting)
  336. {
  337. Thread.Sleep((int)e.Timer);
  338. e.Result = e.Timeouted;
  339. }
  340. else
  341. {
  342. e.Result = e.Continue;
  343. }
  344. }
  345. else if (args.SelectedAction == QueryReceivedEventArgs.Action.Abort)
  346. {
  347. e.Result = e.Break;
  348. }
  349. _logger.WriteLine("Options Result: [{0}]", e.Result);
  350. }
  351. }
  352. private void ProcessTitleEvent(ConsoleTitleEventStruct e)
  353. {
  354. using (_logger.CreateCallstack())
  355. {
  356. _logger.WriteLine("Not-supported title event [{0}]", e.Title);
  357. }
  358. }
  359. private void ProcessInputEvent(ConsoleInputEventStruct e)
  360. {
  361. using (_logger.CreateCallstack())
  362. {
  363. while (!AbortedOrExited())
  364. {
  365. lock (_input)
  366. {
  367. if (_input.Count > 0)
  368. {
  369. e.Str = _input[0];
  370. e.Result = true;
  371. _input.RemoveAt(0);
  372. Print(false, false, _log[0] + "\n");
  373. _log.RemoveAt(0);
  374. return;
  375. }
  376. }
  377. _inputEvent.WaitOne(100, false);
  378. }
  379. }
  380. }
  381. private void Print(bool fromBeginning, bool error, string message)
  382. {
  383. if (fromBeginning && ((message.Length == 0) || (message[0] != '\n')))
  384. {
  385. _lastFromBeginning = message;
  386. _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);
  387. OutputDataReceived?.Invoke(this, null);
  388. }
  389. else
  390. {
  391. if (!string.IsNullOrEmpty(_lastFromBeginning))
  392. {
  393. AddToOutput(_lastFromBeginning, false);
  394. _lastFromBeginning = null;
  395. }
  396. if (fromBeginning && (message.Length > 0) && (message[0] == '\n'))
  397. {
  398. AddToOutput("\n", false);
  399. _lastFromBeginning = message.Substring(1);
  400. _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);
  401. }
  402. else
  403. {
  404. AddToOutput(message, error);
  405. }
  406. }
  407. }
  408. private void AddToOutput(string message, bool error)
  409. {
  410. string[] lines = (_incompleteLine + message).Split(new[] { '\n' });
  411. _incompleteLine = lines[lines.Length - 1];
  412. for (int i = 0; i < lines.Length - 1; ++i)
  413. {
  414. OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(lines[i], error));
  415. }
  416. }
  417. private void ProcessPrintEvent(ConsolePrintEventStruct e)
  418. {
  419. _logger.WriteLineLevel(1, string.Format(CultureInfo.CurrentCulture, "Print: {0}", e.Message));
  420. Print(e.FromBeginning, e.Error, e.Message);
  421. }
  422. private void ProcessInitEvent(ConsoleInitEventStruct e)
  423. {
  424. using (_logger.CreateCallstack())
  425. {
  426. if (!e.UseStdErr ||
  427. (e.BinaryOutput != ConsoleInitEventStruct.StdInOut.Binary) ||
  428. (e.BinaryInput != ConsoleInitEventStruct.StdInOut.Binary))
  429. {
  430. throw _logger.WriteException(new InvalidOperationException("Unexpected console interface options"));
  431. }
  432. e.InputType = 3; // pipe
  433. e.OutputType = 3; // pipe
  434. e.WantsProgress = _session.WantsProgress;
  435. }
  436. }
  437. private void ProcessProgressEvent(ConsoleProgressEventStruct e)
  438. {
  439. using (_logger.CreateCallstack())
  440. {
  441. _logger.WriteLine(
  442. "File Name [{0}] - Directory [{1}] - Overall Progress [{2}] - File Progress [{3}] - CPS [{4}]",
  443. e.FileName, e.Directory, e.OverallProgress, e.FileProgress, e.CPS);
  444. if (!_cancel)
  445. {
  446. FileTransferProgressEventArgs args = new FileTransferProgressEventArgs();
  447. switch (e.Operation)
  448. {
  449. case ConsoleProgressEventStruct.ProgressOperation.Copy:
  450. args.Operation = ProgressOperation.Transfer;
  451. break;
  452. default:
  453. throw _logger.WriteException(new ArgumentOutOfRangeException("Unknown progress operation", (Exception)null));
  454. }
  455. switch (e.Side)
  456. {
  457. case ConsoleProgressEventStruct.ProgressSide.Local:
  458. args.Side = ProgressSide.Local;
  459. break;
  460. case ConsoleProgressEventStruct.ProgressSide.Remote:
  461. args.Side = ProgressSide.Remote;
  462. break;
  463. default:
  464. throw _logger.WriteException(new ArgumentOutOfRangeException("Unknown progress side", (Exception)null));
  465. }
  466. args.FileName = e.FileName;
  467. args.Directory = e.Directory;
  468. args.OverallProgress = ((double)e.OverallProgress) / 100;
  469. args.FileProgress = ((double)e.FileProgress) / 100;
  470. args.CPS = (int)e.CPS;
  471. args.Cancel = false;
  472. _session.ProcessProgress(args);
  473. }
  474. if (_cancel)
  475. {
  476. e.Cancel = true;
  477. }
  478. }
  479. }
  480. private void ProcessTransferOutEvent(ConsoleTransferEventStruct e)
  481. {
  482. using (_logger.CreateCallstack())
  483. {
  484. _logger.WriteLine("Len [{0}]", e.Len);
  485. if (StdOut == null)
  486. {
  487. throw _logger.WriteException(new InvalidOperationException("Unexpected data"));
  488. }
  489. int len = (int)e.Len;
  490. if (len > 0)
  491. {
  492. StdOut.WriteInternal(e.Data, 0, len);
  493. _logger.WriteLine("Data written to the buffer");
  494. }
  495. else
  496. {
  497. StdOut.CloseWrite();
  498. _logger.WriteLine("Data buffer closed");
  499. }
  500. }
  501. }
  502. private void ProcessTransferInEvent(ConsoleTransferEventStruct e)
  503. {
  504. using (_logger.CreateCallstack())
  505. {
  506. _logger.WriteLine("Len [{0}]", e.Len);
  507. if (StdIn == null)
  508. {
  509. throw _logger.WriteException(new InvalidOperationException("Unexpected data request"));
  510. }
  511. try
  512. {
  513. int len = (int)e.Len;
  514. len = StdIn.Read(e.Data, 0, len);
  515. _logger.WriteLine("{0} bytes read", len);
  516. e.Len = (UIntPtr)len;
  517. }
  518. catch (Exception ex)
  519. {
  520. _logger.WriteLine("Error reading data stream");
  521. _logger.WriteException(ex);
  522. e.Error = true;
  523. }
  524. }
  525. }
  526. private void InitializeConsole()
  527. {
  528. using (_logger.CreateCallstack())
  529. {
  530. int attempts = 0;
  531. Random random = new Random();
  532. int process = Process.GetCurrentProcess().Id;
  533. do
  534. {
  535. if (attempts > MaxAttempts)
  536. {
  537. throw _logger.WriteException(new SessionLocalException(_session, "Cannot find unique name for event object."));
  538. }
  539. int instanceNumber = random.Next(1000);
  540. _instanceName = string.Format(CultureInfo.InvariantCulture, "_{0}_{1}_{2}", process, GetHashCode(), instanceNumber);
  541. _logger.WriteLine("Trying event {0}", _instanceName);
  542. if (!TryCreateEvent(ConsoleEventRequest + _instanceName, out _requestEvent))
  543. {
  544. _logger.WriteLine("Event {0} is not unique", _instanceName);
  545. _requestEvent.Close();
  546. _requestEvent = null;
  547. }
  548. else
  549. {
  550. _logger.WriteLine("Event {0} is unique", _instanceName);
  551. _responseEvent = CreateEvent(ConsoleEventResponse + _instanceName);
  552. _cancelEvent = CreateEvent(ConsoleEventCancel + _instanceName);
  553. string fileMappingName = ConsoleMapping + _instanceName;
  554. _fileMapping = CreateFileMapping(fileMappingName);
  555. if (Marshal.GetLastWin32Error() == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  556. {
  557. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "File mapping {0} already exists", fileMappingName)));
  558. }
  559. if (_fileMapping.IsInvalid)
  560. {
  561. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Cannot create file mapping {0}", fileMappingName)));
  562. }
  563. }
  564. ++attempts;
  565. }
  566. while (_requestEvent == null);
  567. using (ConsoleCommStruct commStruct = AcquireCommStruct())
  568. {
  569. commStruct.InitHeader();
  570. }
  571. if (_session.GuardProcessWithJobInternal)
  572. {
  573. string jobName = ConsoleJob + _instanceName;
  574. _job = new Job(_logger, jobName);
  575. }
  576. }
  577. }
  578. private SafeFileHandle CreateFileMapping(string fileMappingName)
  579. {
  580. unsafe
  581. {
  582. IntPtr securityAttributesPtr = IntPtr.Zero;
  583. #if !NETSTANDARD
  584. // We use the EventWaitHandleSecurity only to generate the descriptor binary form
  585. // that does not differ for object types, so we abuse the existing "event handle" implementation,
  586. // not to have to create the file mapping SecurityAttributes via P/Invoke.
  587. // .NET 4 supports MemoryMappedFile and MemoryMappedFileSecurity natively already
  588. EventWaitHandleSecurity security = CreateSecurity((EventWaitHandleRights)FileMappingRights.AllAccess);
  589. if (security != null)
  590. {
  591. SecurityAttributes securityAttributes = new SecurityAttributes();
  592. securityAttributes.nLength = (uint)Marshal.SizeOf(securityAttributes);
  593. byte[] descriptorBinaryForm = security.GetSecurityDescriptorBinaryForm();
  594. byte * buffer = stackalloc byte[descriptorBinaryForm.Length];
  595. for (int i = 0; i < descriptorBinaryForm.Length; i++)
  596. {
  597. buffer[i] = descriptorBinaryForm[i];
  598. }
  599. securityAttributes.lpSecurityDescriptor = (IntPtr)buffer;
  600. int length = Marshal.SizeOf(typeof(SecurityAttributes));
  601. securityAttributesPtr = Marshal.AllocHGlobal(length);
  602. Marshal.StructureToPtr(securityAttributes, securityAttributesPtr, false);
  603. }
  604. #endif
  605. return
  606. UnsafeNativeMethods.CreateFileMapping(
  607. new SafeFileHandle(new IntPtr(-1), true), securityAttributesPtr, FileMapProtection.PageReadWrite, 0,
  608. ConsoleCommStruct.Size, fileMappingName);
  609. }
  610. }
  611. private ConsoleCommStruct AcquireCommStruct()
  612. {
  613. return new ConsoleCommStruct(_session, _fileMapping);
  614. }
  615. private bool TryCreateEvent(string name, out EventWaitHandle ev)
  616. {
  617. _logger.WriteLine("Creating event {0}", name);
  618. string securityDesc;
  619. #if !NETSTANDARD
  620. EventWaitHandleSecurity security = CreateSecurity(EventWaitHandleRights.FullControl);
  621. ev = new EventWaitHandle(false, EventResetMode.AutoReset, name, out bool createdNew, security);
  622. securityDesc = (security != null ? security.GetSecurityDescriptorSddlForm(AccessControlSections.All) : "none");
  623. #else
  624. ev = new EventWaitHandle(false, EventResetMode.AutoReset, name, out bool createdNew);
  625. securityDesc = "not impl";
  626. #endif
  627. _logger.WriteLine(
  628. "Created event {0} with handle {1} with security {2}, new {3}",
  629. name, ev.SafeWaitHandle.DangerousGetHandle(), securityDesc, createdNew);
  630. return createdNew;
  631. }
  632. #if !NETSTANDARD
  633. private EventWaitHandleSecurity CreateSecurity(EventWaitHandleRights eventRights)
  634. {
  635. EventWaitHandleSecurity security = null;
  636. // When "running as user", we have to grant the target user permissions to the objects (events and file mapping) explicitly
  637. if (!string.IsNullOrEmpty(_session.ExecutableProcessUserName))
  638. {
  639. security = new EventWaitHandleSecurity();
  640. IdentityReference si;
  641. try
  642. {
  643. si = new NTAccount(_session.ExecutableProcessUserName);
  644. }
  645. catch (Exception e)
  646. {
  647. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "Error resolving account {0}", _session.ExecutableProcessUserName), e));
  648. }
  649. EventWaitHandleAccessRule rule =
  650. new EventWaitHandleAccessRule(
  651. si, eventRights, AccessControlType.Allow);
  652. security.AddAccessRule(rule);
  653. }
  654. return security;
  655. }
  656. #endif
  657. private EventWaitHandle CreateEvent(string name)
  658. {
  659. if (!TryCreateEvent(name, out EventWaitHandle ev))
  660. {
  661. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Event {0} already exists", name)));
  662. }
  663. return ev;
  664. }
  665. private void TestEventClosed(string name)
  666. {
  667. if (_session.TestHandlesClosedInternal)
  668. {
  669. _logger.WriteLine("Testing that event {0} is closed", name);
  670. if (TryCreateEvent(name, out EventWaitHandle ev))
  671. {
  672. ev.Close();
  673. }
  674. else
  675. {
  676. _logger.WriteLine("Exception: Event {0} was not closed yet", name);
  677. }
  678. }
  679. }
  680. private void AddInput(string str, string log)
  681. {
  682. Type structType = typeof(ConsoleInputEventStruct);
  683. FieldInfo strField = structType.GetField("Str");
  684. object[] attributes = strField.GetCustomAttributes(typeof(MarshalAsAttribute), false);
  685. if (attributes.Length != 1)
  686. {
  687. throw _logger.WriteException(new InvalidOperationException("MarshalAs attribute not found for ConsoleInputEventStruct.Str"));
  688. }
  689. MarshalAsAttribute marshalAsAttribute = (MarshalAsAttribute)attributes[0];
  690. if (marshalAsAttribute.SizeConst <= str.Length)
  691. {
  692. throw _logger.WriteException(
  693. new SessionLocalException(
  694. _session,
  695. string.Format(CultureInfo.CurrentCulture, "Input [{0}] is too long ({1} limit)", str, marshalAsAttribute.SizeConst)));
  696. }
  697. lock (_input)
  698. {
  699. _input.Add(str);
  700. _log.Add(log);
  701. _inputEvent.Set();
  702. }
  703. }
  704. public void ExecuteCommand(string command, string log)
  705. {
  706. using (_logger.CreateCallstack())
  707. {
  708. _cancel = false;
  709. AddInput(command, log);
  710. }
  711. }
  712. public void Close()
  713. {
  714. using (_logger.CreateCallstack())
  715. {
  716. int timeout;
  717. #if DEBUG
  718. // in debug build, we expect the winscp.exe to run in tracing mode, being very slow
  719. timeout = 10000;
  720. #else
  721. timeout = 2000;
  722. #endif
  723. _logger.WriteLine("Waiting for process to exit ({0} ms)", timeout);
  724. if (!_process.WaitForExit(timeout))
  725. {
  726. _logger.WriteLine("Killing process");
  727. _process.Kill();
  728. }
  729. }
  730. }
  731. public void Dispose()
  732. {
  733. using (_logger.CreateCallstack())
  734. {
  735. lock (_lock)
  736. {
  737. if (_session.TestHandlesClosedInternal)
  738. {
  739. _logger.WriteLine("Will test that handles are closed");
  740. }
  741. _abort = true;
  742. if (_thread != null)
  743. {
  744. _thread.Join();
  745. _thread = null;
  746. }
  747. if (_process != null)
  748. {
  749. _process.Dispose();
  750. _process = null;
  751. }
  752. if (_requestEvent != null)
  753. {
  754. _requestEvent.Close();
  755. TestEventClosed(ConsoleEventRequest + _instanceName);
  756. }
  757. if (_responseEvent != null)
  758. {
  759. _responseEvent.Close();
  760. TestEventClosed(ConsoleEventResponse + _instanceName);
  761. }
  762. if (_cancelEvent != null)
  763. {
  764. _cancelEvent.Close();
  765. TestEventClosed(ConsoleEventCancel + _instanceName);
  766. }
  767. if (_fileMapping != null)
  768. {
  769. _fileMapping.Dispose();
  770. _fileMapping = null;
  771. if (_session.TestHandlesClosedInternal)
  772. {
  773. _logger.WriteLine("Testing that file mapping is closed");
  774. string fileMappingName = ConsoleMapping + _instanceName;
  775. SafeFileHandle fileMapping = CreateFileMapping(fileMappingName);
  776. if (Marshal.GetLastWin32Error() == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  777. {
  778. _logger.WriteLine("Exception: File mapping {0} was not closed yet", fileMappingName);
  779. }
  780. if (!fileMapping.IsInvalid)
  781. {
  782. fileMapping.Dispose();
  783. }
  784. }
  785. }
  786. if (_inputEvent != null)
  787. {
  788. _inputEvent.Close();
  789. _inputEvent = null;
  790. }
  791. if (_job != null)
  792. {
  793. _job.Dispose();
  794. _job = null;
  795. }
  796. }
  797. }
  798. }
  799. private string GetExecutablePath()
  800. {
  801. using (_logger.CreateCallstack())
  802. {
  803. string executablePath;
  804. if (!string.IsNullOrEmpty(_session.ExecutablePath))
  805. {
  806. executablePath = _session.ExecutablePath;
  807. if (!File.Exists(executablePath))
  808. {
  809. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "{0} does not exists.", executablePath)));
  810. }
  811. }
  812. else
  813. {
  814. executablePath = FindExecutable(_session);
  815. }
  816. return executablePath;
  817. }
  818. }
  819. // Should be moved to Session class
  820. internal static string FindExecutable(Session session)
  821. {
  822. Logger logger = session.Logger;
  823. string executablePath;
  824. if (!TryFindExecutableInPath(logger, GetAssemblyPath(logger), out executablePath) &&
  825. !TryFindExecutableInPath(logger, GetEntryAssemblyPath(logger), out executablePath) &&
  826. #if !NETSTANDARD
  827. !TryFindExecutableInPath(logger, GetInstallationPath(RegistryHive.CurrentUser), out executablePath) &&
  828. !TryFindExecutableInPath(logger, GetInstallationPath(RegistryHive.LocalMachine), out executablePath) &&
  829. #endif
  830. !TryFindExecutableInPath(logger, GetDefaultInstallationPath(), out executablePath))
  831. {
  832. string entryAssemblyDesc = string.Empty;
  833. Assembly entryAssembly = Assembly.GetEntryAssembly();
  834. if (entryAssembly != null)
  835. {
  836. entryAssemblyDesc = $", nor the entry assembly {entryAssembly.GetName().Name} ({GetEntryAssemblyPath(logger)})";
  837. }
  838. throw logger.WriteException(
  839. new SessionLocalException(session,
  840. string.Format(CultureInfo.CurrentCulture,
  841. "The {0} executable was not found at location of the assembly {1} ({2}){3}, nor in an installation path. You may use Session.ExecutablePath property to explicitly set path to {0}.",
  842. ExeExecutableFileName, Assembly.GetExecutingAssembly().GetName().Name, GetAssemblyPath(logger), entryAssemblyDesc)));
  843. }
  844. return executablePath;
  845. }
  846. private static string GetDefaultInstallationPath()
  847. {
  848. string programFiles;
  849. if (IntPtr.Size == 8)
  850. {
  851. programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
  852. }
  853. else
  854. {
  855. programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  856. }
  857. return Path.Combine(programFiles, "WinSCP");
  858. }
  859. #if !NETSTANDARD
  860. private static string GetInstallationPath(RegistryHive hive)
  861. {
  862. RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, RegistryView.Registry32);
  863. RegistryKey key = baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\winscp3_is1");
  864. string result = (key != null) ? (string)key.GetValue("Inno Setup: App Path") : null;
  865. return result;
  866. }
  867. #endif
  868. private static bool TryFindExecutableInPath(Logger logger, string path, out string result)
  869. {
  870. if (string.IsNullOrEmpty(path))
  871. {
  872. result = null;
  873. }
  874. else
  875. {
  876. string executablePath = Path.Combine(path, ExeExecutableFileName);
  877. if (File.Exists(executablePath))
  878. {
  879. result = executablePath;
  880. logger.WriteLine("Executable found in {0}", executablePath);
  881. }
  882. else
  883. {
  884. result = null;
  885. logger.WriteLine("Executable not found in {0}", executablePath);
  886. }
  887. }
  888. return (result != null);
  889. }
  890. private static string GetAssemblyPath(Logger logger)
  891. {
  892. return DoGetAssemblyPath(logger.GetAssemblyFilePath());
  893. }
  894. private static string GetEntryAssemblyPath(Logger logger)
  895. {
  896. return DoGetAssemblyPath(logger.GetEntryAssemblyFilePath());
  897. }
  898. private static string DoGetAssemblyPath(string codeBasePath)
  899. {
  900. string path = null;
  901. if (!string.IsNullOrEmpty(codeBasePath))
  902. {
  903. path = Path.GetDirectoryName(codeBasePath);
  904. Debug.Assert(path != null);
  905. }
  906. return path;
  907. }
  908. [DllImport("version.dll", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
  909. public static extern int GetFileVersionInfoSize(string lptstrFilename, out int handle);
  910. [DllImport("kernel32.dll", SetLastError = true)]
  911. static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hReservedNull, uint dwFlags);
  912. [DllImport("kernel32.dll", SetLastError = true)]
  913. [return: MarshalAs(UnmanagedType.Bool)]
  914. static extern bool FreeLibrary(IntPtr hModule);
  915. [DllImport("kernel32.dll", SetLastError = true)]
  916. static extern IntPtr FindResource(IntPtr hModule, string lpName, string lpType);
  917. [DllImport("kernel32.dll", SetLastError = true)]
  918. static extern uint SizeofResource(IntPtr hModule, IntPtr hResInfo);
  919. private void CheckVersion(string exePath, FileVersionInfo assemblyVersion)
  920. {
  921. using (_logger.CreateCallstack())
  922. {
  923. if (assemblyVersion == null)
  924. {
  925. _logger.WriteLine("Assembly version not known, cannot check version");
  926. }
  927. else if (assemblyVersion.ProductVersion == AssemblyConstants.UndefinedProductVersion)
  928. {
  929. _logger.WriteLine("Undefined assembly version, cannot check version");
  930. }
  931. else
  932. {
  933. FileVersionInfo version = FileVersionInfo.GetVersionInfo(exePath);
  934. _logger.WriteLine("Version of {0} is {1}, product {2} version is {3}", exePath, version.FileVersion, version.ProductName, version.ProductVersion);
  935. Exception accessException = null;
  936. try
  937. {
  938. using (File.OpenRead(exePath))
  939. {
  940. }
  941. long size = new FileInfo(exePath).Length;
  942. _logger.WriteLine($"Size of the executable file is {size}");
  943. int verInfoSize = GetFileVersionInfoSize(exePath, out int handle);
  944. if (verInfoSize == 0)
  945. {
  946. throw new Exception($"Cannot retrieve {exePath} version info", new Win32Exception());
  947. }
  948. else
  949. {
  950. _logger.WriteLine($"Size of the executable file version info is {verInfoSize}");
  951. }
  952. }
  953. catch (Exception e)
  954. {
  955. _logger.WriteLine("Accessing executable file failed");
  956. _logger.WriteException(e);
  957. accessException = e;
  958. }
  959. if (_session.DisableVersionCheck)
  960. {
  961. _logger.WriteLine("Version check disabled (not recommended)");
  962. }
  963. else if (assemblyVersion.ProductVersion != version.ProductVersion)
  964. {
  965. try
  966. {
  967. using (SHA256 SHA256 = SHA256.Create())
  968. using (FileStream stream = File.OpenRead(exePath))
  969. {
  970. string sha256 = string.Concat(Array.ConvertAll(SHA256.ComputeHash(stream), b => b.ToString("x2")));
  971. _logger.WriteLine($"SHA-256 of the executable file is {sha256}");
  972. }
  973. }
  974. catch (Exception e)
  975. {
  976. _logger.WriteLine("Calculating SHA-256 of the executable file failed");
  977. _logger.WriteException(e);
  978. }
  979. try
  980. {
  981. IntPtr library = LoadLibraryEx(exePath, IntPtr.Zero, 0x00000002); // LOAD_LIBRARY_AS_DATAFILE
  982. if (library == IntPtr.Zero)
  983. {
  984. _logger.WriteLine("Cannot load");
  985. _logger.WriteException(new Win32Exception());
  986. }
  987. else
  988. {
  989. IntPtr resource = FindResource(library, "#1", "#16");
  990. if (resource == IntPtr.Zero)
  991. {
  992. _logger.WriteLine("Cannot find version resource");
  993. _logger.WriteException(new Win32Exception());
  994. }
  995. else
  996. {
  997. uint resourceSize = SizeofResource(library, resource);
  998. if (resourceSize == 0)
  999. {
  1000. _logger.WriteLine("Cannot find size of version resource");
  1001. _logger.WriteException(new Win32Exception());
  1002. }
  1003. else
  1004. {
  1005. _logger.WriteLine($"Version resource size is {resourceSize}");
  1006. }
  1007. }
  1008. FreeLibrary(library);
  1009. }
  1010. }
  1011. catch (Exception e)
  1012. {
  1013. _logger.WriteLine("Querying version resource failed");
  1014. _logger.WriteException(e);
  1015. }
  1016. string message;
  1017. if (string.IsNullOrEmpty(version.ProductVersion) && (accessException != null))
  1018. {
  1019. message = $"Cannot use {exePath}";
  1020. }
  1021. else
  1022. {
  1023. message =
  1024. $"The version of {exePath} ({version.ProductVersion}) does not match " +
  1025. $"version of this assembly {_logger.GetAssemblyFilePath()} ({assemblyVersion.ProductVersion}).";
  1026. }
  1027. throw _logger.WriteException(new SessionLocalException(_session, message, accessException));
  1028. }
  1029. }
  1030. }
  1031. }
  1032. public void WriteStatus()
  1033. {
  1034. _logger.WriteLine("{0} - exists [{1}]", ExecutablePath, File.Exists(ExecutablePath));
  1035. }
  1036. public void RequestCallstack()
  1037. {
  1038. using (_logger.CreateCallstack())
  1039. {
  1040. lock (_lock)
  1041. {
  1042. if (_process == null)
  1043. {
  1044. _logger.WriteLine("Process is closed already");
  1045. }
  1046. else
  1047. {
  1048. try
  1049. {
  1050. string eventName = string.Format(CultureInfo.InvariantCulture, "WinSCPCallstack{0}", _process.Id);
  1051. using (EventWaitHandle ev = EventWaitHandle.OpenExisting(eventName))
  1052. {
  1053. _logger.WriteLine("Setting event {0}", eventName);
  1054. ev.Set();
  1055. string callstackFileName = string.Format(CultureInfo.InvariantCulture, "{0}.txt", eventName);
  1056. string callstackPath = Path.Combine(Path.GetTempPath(), callstackFileName);
  1057. int timeout = 2000;
  1058. while (!File.Exists(callstackPath))
  1059. {
  1060. if (timeout < 0)
  1061. {
  1062. string message = string.Format(CultureInfo.CurrentCulture, "Timeout waiting for callstack file {0} to be created ", callstackPath);
  1063. throw new TimeoutException(message);
  1064. }
  1065. int step = 50;
  1066. timeout -= 50;
  1067. Thread.Sleep(step);
  1068. }
  1069. _logger.WriteLine("Callstack file {0} has been created", callstackPath);
  1070. // allow writting to be finished
  1071. Thread.Sleep(100);
  1072. _logger.WriteLine(File.ReadAllText(callstackPath));
  1073. File.Delete(callstackPath);
  1074. }
  1075. }
  1076. catch (Exception e)
  1077. {
  1078. _logger.WriteException(e);
  1079. }
  1080. }
  1081. }
  1082. }
  1083. }
  1084. public void Cancel()
  1085. {
  1086. _cancel = true;
  1087. }
  1088. private const int MaxAttempts = 10;
  1089. private const string ConsoleMapping = "WinSCPConsoleMapping";
  1090. private const string ConsoleEventRequest = "WinSCPConsoleEventRequest";
  1091. private const string ConsoleEventResponse = "WinSCPConsoleEventResponse";
  1092. private const string ConsoleEventCancel = "WinSCPConsoleEventCancel";
  1093. private const string ConsoleJob = "WinSCPConsoleJob";
  1094. private const string ExeExecutableFileName = "winscp.exe";
  1095. private Process _process;
  1096. private readonly object _lock = new object();
  1097. private readonly Logger _logger;
  1098. private readonly Session _session;
  1099. private EventWaitHandle _requestEvent;
  1100. private EventWaitHandle _responseEvent;
  1101. private EventWaitHandle _cancelEvent;
  1102. private SafeFileHandle _fileMapping;
  1103. private string _instanceName;
  1104. private Thread _thread;
  1105. private bool _abort;
  1106. private string _lastFromBeginning;
  1107. private string _incompleteLine;
  1108. private readonly List<string> _input = new List<string>();
  1109. private readonly List<string> _log = new List<string>();
  1110. private AutoResetEvent _inputEvent = new AutoResetEvent(false);
  1111. private Job _job;
  1112. private bool _cancel;
  1113. }
  1114. }