ExeSessionProcess.cs 45 KB

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