ExeSessionProcess.cs 47 KB

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