ExeSessionProcess.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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; private set; }
  21. public static ExeSessionProcess CreateForSession(Session session)
  22. {
  23. return new ExeSessionProcess(session, true, null);
  24. }
  25. public static ExeSessionProcess CreateForConsole(Session session, string additionalArguments)
  26. {
  27. return new ExeSessionProcess(session, false, additionalArguments);
  28. }
  29. private ExeSessionProcess(Session session, bool useXmlLog, string additionalArguments)
  30. {
  31. _session = session;
  32. _logger = session.Logger;
  33. _incompleteLine = string.Empty;
  34. using (_logger.CreateCallstack())
  35. {
  36. string executablePath = GetExecutablePath();
  37. _logger.WriteLine("EXE executable path resolved to {0}", executablePath);
  38. string assemblyFilePath = _logger.GetAssemblyFilePath();
  39. FileVersionInfo assemblyVersion = null;
  40. if (assemblyFilePath != null)
  41. {
  42. assemblyVersion = FileVersionInfo.GetVersionInfo(assemblyFilePath);
  43. }
  44. CheckVersion(executablePath, assemblyVersion);
  45. string configSwitch;
  46. if (_session.DefaultConfigurationInternal)
  47. {
  48. configSwitch = "/ini=nul ";
  49. }
  50. else
  51. {
  52. if (!string.IsNullOrEmpty(_session.IniFilePathInternal))
  53. {
  54. configSwitch = string.Format(CultureInfo.InvariantCulture, "/ini=\"{0}\" ", _session.IniFilePathInternal);
  55. }
  56. else
  57. {
  58. configSwitch = "";
  59. }
  60. }
  61. string logSwitch = null;
  62. if (!string.IsNullOrEmpty(_session.SessionLogPath))
  63. {
  64. logSwitch = string.Format(CultureInfo.InvariantCulture, "/log=\"{0}\" ", LogPathEscape(_session.SessionLogPath));
  65. }
  66. string xmlLogSwitch;
  67. if (useXmlLog)
  68. {
  69. xmlLogSwitch = string.Format(CultureInfo.InvariantCulture, "/xmllog=\"{0}\" /xmlgroups /xmllogrequired ", LogPathEscape(_session.XmlLogPath));
  70. }
  71. else
  72. {
  73. xmlLogSwitch = "";
  74. }
  75. string logLevelSwitch = null;
  76. if (_session.DebugLogLevel > 0)
  77. {
  78. logLevelSwitch = string.Format(CultureInfo.InvariantCulture, "/loglevel={0} ", _session.DebugLogLevel);
  79. }
  80. string assemblyVersionStr =
  81. (assemblyVersion == null) ? "unk" :
  82. string.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2} ", assemblyVersion.ProductMajorPart, assemblyVersion.ProductMinorPart, assemblyVersion.ProductBuildPart);
  83. string assemblyVersionSwitch =
  84. string.Format(CultureInfo.InvariantCulture, "/dotnet={0} ", assemblyVersionStr);
  85. string arguments =
  86. xmlLogSwitch + "/nointeractiveinput /stdout=chunked " + assemblyVersionSwitch +
  87. configSwitch + logSwitch + logLevelSwitch + _session.AdditionalExecutableArguments;
  88. Tools.AddRawParameters(ref arguments, _session.RawConfiguration, "/rawconfig", false);
  89. if (!string.IsNullOrEmpty(additionalArguments))
  90. {
  91. arguments += " " + additionalArguments;
  92. }
  93. _process = new Process();
  94. _process.StartInfo.FileName = executablePath;
  95. _process.StartInfo.WorkingDirectory = Path.GetDirectoryName(executablePath);
  96. _process.StartInfo.Arguments = arguments;
  97. _process.StartInfo.UseShellExecute = false;
  98. _process.Exited += ProcessExited;
  99. }
  100. }
  101. private static string LogPathEscape(string path)
  102. {
  103. return Tools.ArgumentEscape(path).Replace("!", "!!");
  104. }
  105. public void Abort()
  106. {
  107. using (_logger.CreateCallstack())
  108. {
  109. lock (_lock)
  110. {
  111. if ((_process != null) && !_process.HasExited)
  112. {
  113. _process.Kill();
  114. }
  115. }
  116. }
  117. }
  118. public void Start()
  119. {
  120. using (_logger.CreateCallstack())
  121. {
  122. StdOut = new PipeStream();
  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. default:
  283. throw _logger.WriteException(new NotImplementedException());
  284. }
  285. }
  286. _responseEvent.Set();
  287. }
  288. }
  289. private void ProcessChoiceEvent(ConsoleChoiceEventStruct e)
  290. {
  291. using (_logger.CreateCallstack())
  292. {
  293. _logger.WriteLine(
  294. "Options: [{0}], Timer: [{1}], Timeouting: [{2}], Timeouted: [{3}], Break: [{4}]",
  295. e.Options, e.Timer, e.Timeouting, e.Timeouted, e.Break);
  296. QueryReceivedEventArgs args = new QueryReceivedEventArgs
  297. {
  298. Message = e.Message
  299. };
  300. _session.ProcessChoice(args);
  301. if (args.SelectedAction == QueryReceivedEventArgs.Action.None)
  302. {
  303. if (e.Timeouting)
  304. {
  305. Thread.Sleep((int)e.Timer);
  306. e.Result = e.Timeouted;
  307. }
  308. else
  309. {
  310. e.Result = e.Break;
  311. }
  312. }
  313. else if (args.SelectedAction == QueryReceivedEventArgs.Action.Continue)
  314. {
  315. if (e.Timeouting)
  316. {
  317. Thread.Sleep((int)e.Timer);
  318. e.Result = e.Timeouted;
  319. }
  320. else
  321. {
  322. e.Result = e.Continue;
  323. }
  324. }
  325. else if (args.SelectedAction == QueryReceivedEventArgs.Action.Abort)
  326. {
  327. e.Result = e.Break;
  328. }
  329. _logger.WriteLine("Options Result: [{0}]", e.Result);
  330. }
  331. }
  332. private void ProcessTitleEvent(ConsoleTitleEventStruct e)
  333. {
  334. using (_logger.CreateCallstack())
  335. {
  336. _logger.WriteLine("Not-supported title event [{0}]", e.Title);
  337. }
  338. }
  339. private void ProcessInputEvent(ConsoleInputEventStruct e)
  340. {
  341. using (_logger.CreateCallstack())
  342. {
  343. while (!AbortedOrExited())
  344. {
  345. lock (_input)
  346. {
  347. if (_input.Count > 0)
  348. {
  349. e.Str = _input[0];
  350. e.Result = true;
  351. _input.RemoveAt(0);
  352. Print(false, false, _log[0] + "\n");
  353. _log.RemoveAt(0);
  354. return;
  355. }
  356. }
  357. _inputEvent.WaitOne(100, false);
  358. }
  359. }
  360. }
  361. private void Print(bool fromBeginning, bool error, string message)
  362. {
  363. if (fromBeginning && ((message.Length == 0) || (message[0] != '\n')))
  364. {
  365. _lastFromBeginning = message;
  366. _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);
  367. OutputDataReceived?.Invoke(this, null);
  368. }
  369. else
  370. {
  371. if (!string.IsNullOrEmpty(_lastFromBeginning))
  372. {
  373. AddToOutput(_lastFromBeginning, false);
  374. _lastFromBeginning = null;
  375. }
  376. if (fromBeginning && (message.Length > 0) && (message[0] == '\n'))
  377. {
  378. AddToOutput("\n", false);
  379. _lastFromBeginning = message.Substring(1);
  380. _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);
  381. }
  382. else
  383. {
  384. AddToOutput(message, error);
  385. }
  386. }
  387. }
  388. private void AddToOutput(string message, bool error)
  389. {
  390. string[] lines = (_incompleteLine + message).Split(new[] { '\n' });
  391. _incompleteLine = lines[lines.Length - 1];
  392. for (int i = 0; i < lines.Length - 1; ++i)
  393. {
  394. OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(lines[i], error));
  395. }
  396. }
  397. private void ProcessPrintEvent(ConsolePrintEventStruct e)
  398. {
  399. _logger.WriteLineLevel(1, string.Format(CultureInfo.CurrentCulture, "Print: {0}", e.Message));
  400. Print(e.FromBeginning, e.Error, e.Message);
  401. }
  402. private void ProcessInitEvent(ConsoleInitEventStruct e)
  403. {
  404. using (_logger.CreateCallstack())
  405. {
  406. e.InputType = 3; // pipe
  407. e.OutputType = 3; // pipe
  408. e.WantsProgress = _session.WantsProgress;
  409. }
  410. }
  411. private void ProcessProgressEvent(ConsoleProgressEventStruct e)
  412. {
  413. using (_logger.CreateCallstack())
  414. {
  415. _logger.WriteLine(
  416. "File Name [{0}] - Directory [{1}] - Overall Progress [{2}] - File Progress [{3}] - CPS [{4}]",
  417. e.FileName, e.Directory, e.OverallProgress, e.FileProgress, e.CPS);
  418. if (!_cancel)
  419. {
  420. FileTransferProgressEventArgs args = new FileTransferProgressEventArgs();
  421. switch (e.Operation)
  422. {
  423. case ConsoleProgressEventStruct.ProgressOperation.Copy:
  424. args.Operation = ProgressOperation.Transfer;
  425. break;
  426. default:
  427. throw _logger.WriteException(new ArgumentOutOfRangeException("Unknown progress operation", (Exception)null));
  428. }
  429. switch (e.Side)
  430. {
  431. case ConsoleProgressEventStruct.ProgressSide.Local:
  432. args.Side = ProgressSide.Local;
  433. break;
  434. case ConsoleProgressEventStruct.ProgressSide.Remote:
  435. args.Side = ProgressSide.Remote;
  436. break;
  437. default:
  438. throw _logger.WriteException(new ArgumentOutOfRangeException("Unknown progress side", (Exception)null));
  439. }
  440. args.FileName = e.FileName;
  441. args.Directory = e.Directory;
  442. args.OverallProgress = ((double)e.OverallProgress) / 100;
  443. args.FileProgress = ((double)e.FileProgress) / 100;
  444. args.CPS = (int)e.CPS;
  445. args.Cancel = false;
  446. _session.ProcessProgress(args);
  447. }
  448. if (_cancel)
  449. {
  450. e.Cancel = true;
  451. }
  452. }
  453. }
  454. private void ProcessTransferOutEvent(ConsoleTransferEventStruct e)
  455. {
  456. using (_logger.CreateCallstack())
  457. {
  458. _logger.WriteLine("Len [{0}]", e.Len);
  459. StdOut.Write(e.Data, 0, (int)e.Len);
  460. _logger.WriteLine("Data written to the buffer");
  461. }
  462. }
  463. private void InitializeConsole()
  464. {
  465. using (_logger.CreateCallstack())
  466. {
  467. int attempts = 0;
  468. Random random = new Random();
  469. int process = Process.GetCurrentProcess().Id;
  470. do
  471. {
  472. if (attempts > MaxAttempts)
  473. {
  474. throw _logger.WriteException(new SessionLocalException(_session, "Cannot find unique name for event object."));
  475. }
  476. int instanceNumber = random.Next(1000);
  477. _instanceName = string.Format(CultureInfo.InvariantCulture, "_{0}_{1}_{2}", process, GetHashCode(), instanceNumber);
  478. _logger.WriteLine("Trying event {0}", _instanceName);
  479. if (!TryCreateEvent(ConsoleEventRequest + _instanceName, out _requestEvent))
  480. {
  481. _logger.WriteLine("Event {0} is not unique", _instanceName);
  482. _requestEvent.Close();
  483. _requestEvent = null;
  484. }
  485. else
  486. {
  487. _logger.WriteLine("Event {0} is unique", _instanceName);
  488. _responseEvent = CreateEvent(ConsoleEventResponse + _instanceName);
  489. _cancelEvent = CreateEvent(ConsoleEventCancel + _instanceName);
  490. string fileMappingName = ConsoleMapping + _instanceName;
  491. _fileMapping = CreateFileMapping(fileMappingName);
  492. if (Marshal.GetLastWin32Error() == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  493. {
  494. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "File mapping {0} already exists", fileMappingName)));
  495. }
  496. if (_fileMapping.IsInvalid)
  497. {
  498. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Cannot create file mapping {0}", fileMappingName)));
  499. }
  500. }
  501. ++attempts;
  502. }
  503. while (_requestEvent == null);
  504. using (ConsoleCommStruct commStruct = AcquireCommStruct())
  505. {
  506. commStruct.InitHeader();
  507. }
  508. if (_session.GuardProcessWithJobInternal)
  509. {
  510. string jobName = ConsoleJob + _instanceName;
  511. _job = new Job(_logger, jobName);
  512. }
  513. }
  514. }
  515. private SafeFileHandle CreateFileMapping(string fileMappingName)
  516. {
  517. unsafe
  518. {
  519. IntPtr securityAttributesPtr = IntPtr.Zero;
  520. #if !NETSTANDARD
  521. // We use the EventWaitHandleSecurity only to generate the descriptor binary form
  522. // that does not differ for object types, so we abuse the existing "event handle" implementation,
  523. // not to have to create the file mapping SecurityAttributes via P/Invoke.
  524. // .NET 4 supports MemoryMappedFile and MemoryMappedFileSecurity natively already
  525. EventWaitHandleSecurity security = CreateSecurity((EventWaitHandleRights)FileMappingRights.AllAccess);
  526. if (security != null)
  527. {
  528. SecurityAttributes securityAttributes = new SecurityAttributes();
  529. securityAttributes.nLength = (uint)Marshal.SizeOf(securityAttributes);
  530. byte[] descriptorBinaryForm = security.GetSecurityDescriptorBinaryForm();
  531. byte * buffer = stackalloc byte[descriptorBinaryForm.Length];
  532. for (int i = 0; i < descriptorBinaryForm.Length; i++)
  533. {
  534. buffer[i] = descriptorBinaryForm[i];
  535. }
  536. securityAttributes.lpSecurityDescriptor = (IntPtr)buffer;
  537. int length = Marshal.SizeOf(typeof(SecurityAttributes));
  538. securityAttributesPtr = Marshal.AllocHGlobal(length);
  539. Marshal.StructureToPtr(securityAttributes, securityAttributesPtr, false);
  540. }
  541. #endif
  542. return
  543. UnsafeNativeMethods.CreateFileMapping(
  544. new SafeFileHandle(new IntPtr(-1), true), securityAttributesPtr, FileMapProtection.PageReadWrite, 0,
  545. ConsoleCommStruct.Size, fileMappingName);
  546. }
  547. }
  548. private ConsoleCommStruct AcquireCommStruct()
  549. {
  550. return new ConsoleCommStruct(_session, _fileMapping);
  551. }
  552. private bool TryCreateEvent(string name, out EventWaitHandle ev)
  553. {
  554. _logger.WriteLine("Creating event {0}", name);
  555. string securityDesc;
  556. #if !NETSTANDARD
  557. EventWaitHandleSecurity security = CreateSecurity(EventWaitHandleRights.FullControl);
  558. ev = new EventWaitHandle(false, EventResetMode.AutoReset, name, out bool createdNew, security);
  559. securityDesc = (security != null ? security.GetSecurityDescriptorSddlForm(AccessControlSections.All) : "none");
  560. #else
  561. ev = new EventWaitHandle(false, EventResetMode.AutoReset, name, out bool createdNew);
  562. securityDesc = "not impl";
  563. #endif
  564. _logger.WriteLine(
  565. "Created event {0} with handle {1} with security {2}, new {3}",
  566. name, ev.SafeWaitHandle.DangerousGetHandle(), securityDesc, createdNew);
  567. return createdNew;
  568. }
  569. #if !NETSTANDARD
  570. private EventWaitHandleSecurity CreateSecurity(EventWaitHandleRights eventRights)
  571. {
  572. EventWaitHandleSecurity security = null;
  573. // When "running as user", we have to grant the target user permissions to the objects (events and file mapping) explicitly
  574. if (!string.IsNullOrEmpty(_session.ExecutableProcessUserName))
  575. {
  576. security = new EventWaitHandleSecurity();
  577. IdentityReference si;
  578. try
  579. {
  580. si = new NTAccount(_session.ExecutableProcessUserName);
  581. }
  582. catch (Exception e)
  583. {
  584. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "Error resolving account {0}", _session.ExecutableProcessUserName), e));
  585. }
  586. EventWaitHandleAccessRule rule =
  587. new EventWaitHandleAccessRule(
  588. si, eventRights, AccessControlType.Allow);
  589. security.AddAccessRule(rule);
  590. }
  591. return security;
  592. }
  593. #endif
  594. private EventWaitHandle CreateEvent(string name)
  595. {
  596. if (!TryCreateEvent(name, out EventWaitHandle ev))
  597. {
  598. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Event {0} already exists", name)));
  599. }
  600. return ev;
  601. }
  602. private void TestEventClosed(string name)
  603. {
  604. if (_session.TestHandlesClosedInternal)
  605. {
  606. _logger.WriteLine("Testing that event {0} is closed", name);
  607. if (TryCreateEvent(name, out EventWaitHandle ev))
  608. {
  609. ev.Close();
  610. }
  611. else
  612. {
  613. _logger.WriteLine("Exception: Event {0} was not closed yet", name);
  614. }
  615. }
  616. }
  617. private void AddInput(string str, string log)
  618. {
  619. Type structType = typeof(ConsoleInputEventStruct);
  620. FieldInfo strField = structType.GetField("Str");
  621. object[] attributes = strField.GetCustomAttributes(typeof(MarshalAsAttribute), false);
  622. if (attributes.Length != 1)
  623. {
  624. throw _logger.WriteException(new InvalidOperationException("MarshalAs attribute not found for ConsoleInputEventStruct.Str"));
  625. }
  626. MarshalAsAttribute marshalAsAttribute = (MarshalAsAttribute)attributes[0];
  627. if (marshalAsAttribute.SizeConst <= str.Length)
  628. {
  629. throw _logger.WriteException(
  630. new SessionLocalException(
  631. _session,
  632. string.Format(CultureInfo.CurrentCulture, "Input [{0}] is too long ({1} limit)", str, marshalAsAttribute.SizeConst)));
  633. }
  634. lock (_input)
  635. {
  636. _input.Add(str);
  637. _log.Add(log);
  638. _inputEvent.Set();
  639. }
  640. }
  641. public void ExecuteCommand(string command, string log)
  642. {
  643. using (_logger.CreateCallstack())
  644. {
  645. _cancel = false;
  646. AddInput(command, log);
  647. }
  648. }
  649. public void Close()
  650. {
  651. using (_logger.CreateCallstack())
  652. {
  653. int timeout;
  654. #if DEBUG
  655. // in debug build, we expect the winscp.exe to run in tracing mode, being very slow
  656. timeout = 10000;
  657. #else
  658. timeout = 2000;
  659. #endif
  660. _logger.WriteLine("Waiting for process to exit ({0} ms)", timeout);
  661. if (!_process.WaitForExit(timeout))
  662. {
  663. _logger.WriteLine("Killing process");
  664. _process.Kill();
  665. }
  666. }
  667. }
  668. public void Dispose()
  669. {
  670. using (_logger.CreateCallstack())
  671. {
  672. lock (_lock)
  673. {
  674. if (_session.TestHandlesClosedInternal)
  675. {
  676. _logger.WriteLine("Will test that handles are closed");
  677. }
  678. _abort = true;
  679. if (_thread != null)
  680. {
  681. _thread.Join();
  682. _thread = null;
  683. }
  684. if (_process != null)
  685. {
  686. _process.Dispose();
  687. _process = null;
  688. }
  689. if (_requestEvent != null)
  690. {
  691. _requestEvent.Close();
  692. TestEventClosed(ConsoleEventRequest + _instanceName);
  693. }
  694. if (_responseEvent != null)
  695. {
  696. _responseEvent.Close();
  697. TestEventClosed(ConsoleEventResponse + _instanceName);
  698. }
  699. if (_cancelEvent != null)
  700. {
  701. _cancelEvent.Close();
  702. TestEventClosed(ConsoleEventCancel + _instanceName);
  703. }
  704. if (_fileMapping != null)
  705. {
  706. _fileMapping.Dispose();
  707. _fileMapping = null;
  708. if (_session.TestHandlesClosedInternal)
  709. {
  710. _logger.WriteLine("Testing that file mapping is closed");
  711. string fileMappingName = ConsoleMapping + _instanceName;
  712. SafeFileHandle fileMapping = CreateFileMapping(fileMappingName);
  713. if (Marshal.GetLastWin32Error() == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  714. {
  715. _logger.WriteLine("Exception: File mapping {0} was not closed yet", fileMappingName);
  716. }
  717. if (!fileMapping.IsInvalid)
  718. {
  719. fileMapping.Dispose();
  720. }
  721. }
  722. }
  723. if (_inputEvent != null)
  724. {
  725. _inputEvent.Close();
  726. _inputEvent = null;
  727. }
  728. if (_job != null)
  729. {
  730. _job.Dispose();
  731. _job = null;
  732. }
  733. }
  734. }
  735. }
  736. private string GetExecutablePath()
  737. {
  738. using (_logger.CreateCallstack())
  739. {
  740. string executablePath;
  741. if (!string.IsNullOrEmpty(_session.ExecutablePath))
  742. {
  743. executablePath = _session.ExecutablePath;
  744. if (!File.Exists(executablePath))
  745. {
  746. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "{0} does not exists.", executablePath)));
  747. }
  748. }
  749. else
  750. {
  751. if (!TryFindExecutableInPath(GetAssemblyPath(), out executablePath) &&
  752. !TryFindExecutableInPath(GetEntryAssemblyPath(), out executablePath) &&
  753. #if !NETSTANDARD
  754. !TryFindExecutableInPath(GetInstallationPath(RegistryHive.CurrentUser), out executablePath) &&
  755. !TryFindExecutableInPath(GetInstallationPath(RegistryHive.LocalMachine), out executablePath) &&
  756. #endif
  757. !TryFindExecutableInPath(GetDefaultInstallationPath(), out executablePath))
  758. {
  759. string entryAssemblyDesc = string.Empty;
  760. Assembly entryAssembly = Assembly.GetEntryAssembly();
  761. if (entryAssembly != null)
  762. {
  763. entryAssemblyDesc = $", nor the entry assembly {entryAssembly.GetName().Name} ({GetEntryAssemblyPath()})";
  764. }
  765. throw _logger.WriteException(
  766. new SessionLocalException(_session,
  767. string.Format(CultureInfo.CurrentCulture,
  768. "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}.",
  769. ExeExecutableFileName, Assembly.GetExecutingAssembly().GetName().Name, GetAssemblyPath(), entryAssemblyDesc)));
  770. }
  771. }
  772. return executablePath;
  773. }
  774. }
  775. private static string GetDefaultInstallationPath()
  776. {
  777. string programFiles;
  778. if (IntPtr.Size == 8)
  779. {
  780. programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
  781. }
  782. else
  783. {
  784. programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  785. }
  786. return Path.Combine(programFiles, "WinSCP");
  787. }
  788. #if !NETSTANDARD
  789. private static string GetInstallationPath(RegistryHive hive)
  790. {
  791. RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, RegistryView.Registry32);
  792. RegistryKey key = baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\winscp3_is1");
  793. string result = (key != null) ? (string)key.GetValue("Inno Setup: App Path") : null;
  794. return result;
  795. }
  796. #endif
  797. private bool TryFindExecutableInPath(string path, out string result)
  798. {
  799. if (string.IsNullOrEmpty(path))
  800. {
  801. result = null;
  802. }
  803. else
  804. {
  805. string executablePath = Path.Combine(path, ExeExecutableFileName);
  806. if (File.Exists(executablePath))
  807. {
  808. result = executablePath;
  809. _logger.WriteLine("Executable found in {0}", executablePath);
  810. }
  811. else
  812. {
  813. result = null;
  814. _logger.WriteLine("Executable not found in {0}", executablePath);
  815. }
  816. }
  817. return (result != null);
  818. }
  819. private string GetAssemblyPath()
  820. {
  821. return DoGetAssemblyPath(_logger.GetAssemblyFilePath());
  822. }
  823. private string GetEntryAssemblyPath()
  824. {
  825. return DoGetAssemblyPath(_logger.GetEntryAssemblyFilePath());
  826. }
  827. private static string DoGetAssemblyPath(string codeBasePath)
  828. {
  829. string path = null;
  830. if (!string.IsNullOrEmpty(codeBasePath))
  831. {
  832. path = Path.GetDirectoryName(codeBasePath);
  833. Debug.Assert(path != null);
  834. }
  835. return path;
  836. }
  837. private void CheckVersion(string exePath, FileVersionInfo assemblyVersion)
  838. {
  839. using (_logger.CreateCallstack())
  840. {
  841. if (assemblyVersion == null)
  842. {
  843. _logger.WriteLine("Assembly version not known, cannot check version");
  844. }
  845. else if (assemblyVersion.ProductVersion == AssemblyConstants.UndefinedProductVersion)
  846. {
  847. _logger.WriteLine("Undefined assembly version, cannot check version");
  848. }
  849. else
  850. {
  851. FileVersionInfo version = FileVersionInfo.GetVersionInfo(exePath);
  852. _logger.WriteLine("Version of {0} is {1}, product {2} version is {3}", exePath, version.FileVersion, version.ProductName, version.ProductVersion);
  853. if (_session.DisableVersionCheck)
  854. {
  855. _logger.WriteLine("Version check disabled (not recommended)");
  856. }
  857. else if (assemblyVersion.ProductVersion != version.ProductVersion)
  858. {
  859. throw _logger.WriteException(
  860. new SessionLocalException(
  861. _session, string.Format(CultureInfo.CurrentCulture,
  862. "The version of {0} ({1}) does not match version of this assembly {2} ({3}).",
  863. exePath, version.ProductVersion, _logger.GetAssemblyFilePath(), assemblyVersion.ProductVersion)));
  864. }
  865. }
  866. }
  867. }
  868. public void WriteStatus()
  869. {
  870. string executablePath = GetExecutablePath();
  871. _logger.WriteLine("{0} - exists [{1}]", executablePath, File.Exists(executablePath));
  872. }
  873. public void RequestCallstack()
  874. {
  875. using (_logger.CreateCallstack())
  876. {
  877. lock (_lock)
  878. {
  879. if (_process == null)
  880. {
  881. _logger.WriteLine("Process is closed already");
  882. }
  883. else
  884. {
  885. try
  886. {
  887. string eventName = string.Format(CultureInfo.InvariantCulture, "WinSCPCallstack{0}", _process.Id);
  888. using (EventWaitHandle ev = EventWaitHandle.OpenExisting(eventName))
  889. {
  890. _logger.WriteLine("Setting event {0}", eventName);
  891. ev.Set();
  892. string callstackFileName = string.Format(CultureInfo.InvariantCulture, "{0}.txt", eventName);
  893. string callstackPath = Path.Combine(Path.GetTempPath(), callstackFileName);
  894. int timeout = 2000;
  895. while (!File.Exists(callstackPath))
  896. {
  897. if (timeout < 0)
  898. {
  899. string message = string.Format(CultureInfo.CurrentCulture, "Timeout waiting for callstack file {0} to be created ", callstackPath);
  900. throw new TimeoutException(message);
  901. }
  902. int step = 50;
  903. timeout -= 50;
  904. Thread.Sleep(step);
  905. }
  906. _logger.WriteLine("Callstack file {0} has been created", callstackPath);
  907. // allow writting to be finished
  908. Thread.Sleep(100);
  909. _logger.WriteLine(File.ReadAllText(callstackPath));
  910. File.Delete(callstackPath);
  911. }
  912. }
  913. catch (Exception e)
  914. {
  915. _logger.WriteException(e);
  916. }
  917. }
  918. }
  919. }
  920. }
  921. public void Cancel()
  922. {
  923. _cancel = true;
  924. }
  925. private const int MaxAttempts = 10;
  926. private const string ConsoleMapping = "WinSCPConsoleMapping";
  927. private const string ConsoleEventRequest = "WinSCPConsoleEventRequest";
  928. private const string ConsoleEventResponse = "WinSCPConsoleEventResponse";
  929. private const string ConsoleEventCancel = "WinSCPConsoleEventCancel";
  930. private const string ConsoleJob = "WinSCPConsoleJob";
  931. private const string ExeExecutableFileName = "winscp.exe";
  932. private Process _process;
  933. private readonly object _lock = new object();
  934. private readonly Logger _logger;
  935. private readonly Session _session;
  936. private EventWaitHandle _requestEvent;
  937. private EventWaitHandle _responseEvent;
  938. private EventWaitHandle _cancelEvent;
  939. private SafeFileHandle _fileMapping;
  940. private string _instanceName;
  941. private Thread _thread;
  942. private bool _abort;
  943. private string _lastFromBeginning;
  944. private string _incompleteLine;
  945. private readonly List<string> _input = new List<string>();
  946. private readonly List<string> _log = new List<string>();
  947. private AutoResetEvent _inputEvent = new AutoResetEvent(false);
  948. private Job _job;
  949. private bool _cancel;
  950. }
  951. }