ExeSessionProcess.cs 43 KB

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