ExeSessionProcess.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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. Exception accessException = null;
  900. try
  901. {
  902. using (File.OpenRead(exePath))
  903. {
  904. }
  905. long size = new FileInfo(exePath).Length;
  906. _logger.WriteLine($"Size of the executable file is {size}");
  907. }
  908. catch (Exception e)
  909. {
  910. _logger.WriteLine("Accessing executable file failed");
  911. _logger.WriteException(e);
  912. accessException = e;
  913. }
  914. if (_session.DisableVersionCheck)
  915. {
  916. _logger.WriteLine("Version check disabled (not recommended)");
  917. }
  918. else if (assemblyVersion.ProductVersion != version.ProductVersion)
  919. {
  920. string message;
  921. if (string.IsNullOrEmpty(version.ProductVersion) && (accessException != null))
  922. {
  923. message = $"Cannot access {exePath}";
  924. }
  925. else
  926. {
  927. message =
  928. $"The version of {exePath} ({version.ProductVersion}) does not match " +
  929. $"version of this assembly {_logger.GetAssemblyFilePath()} ({assemblyVersion.ProductVersion}).";
  930. }
  931. throw _logger.WriteException(new SessionLocalException(_session, message, accessException));
  932. }
  933. }
  934. }
  935. }
  936. public void WriteStatus()
  937. {
  938. string executablePath = GetExecutablePath();
  939. _logger.WriteLine("{0} - exists [{1}]", executablePath, File.Exists(executablePath));
  940. }
  941. public void RequestCallstack()
  942. {
  943. using (_logger.CreateCallstack())
  944. {
  945. lock (_lock)
  946. {
  947. if (_process == null)
  948. {
  949. _logger.WriteLine("Process is closed already");
  950. }
  951. else
  952. {
  953. try
  954. {
  955. string eventName = string.Format(CultureInfo.InvariantCulture, "WinSCPCallstack{0}", _process.Id);
  956. using (EventWaitHandle ev = EventWaitHandle.OpenExisting(eventName))
  957. {
  958. _logger.WriteLine("Setting event {0}", eventName);
  959. ev.Set();
  960. string callstackFileName = string.Format(CultureInfo.InvariantCulture, "{0}.txt", eventName);
  961. string callstackPath = Path.Combine(Path.GetTempPath(), callstackFileName);
  962. int timeout = 2000;
  963. while (!File.Exists(callstackPath))
  964. {
  965. if (timeout < 0)
  966. {
  967. string message = string.Format(CultureInfo.CurrentCulture, "Timeout waiting for callstack file {0} to be created ", callstackPath);
  968. throw new TimeoutException(message);
  969. }
  970. int step = 50;
  971. timeout -= 50;
  972. Thread.Sleep(step);
  973. }
  974. _logger.WriteLine("Callstack file {0} has been created", callstackPath);
  975. // allow writting to be finished
  976. Thread.Sleep(100);
  977. _logger.WriteLine(File.ReadAllText(callstackPath));
  978. File.Delete(callstackPath);
  979. }
  980. }
  981. catch (Exception e)
  982. {
  983. _logger.WriteException(e);
  984. }
  985. }
  986. }
  987. }
  988. }
  989. public void Cancel()
  990. {
  991. _cancel = true;
  992. }
  993. private const int MaxAttempts = 10;
  994. private const string ConsoleMapping = "WinSCPConsoleMapping";
  995. private const string ConsoleEventRequest = "WinSCPConsoleEventRequest";
  996. private const string ConsoleEventResponse = "WinSCPConsoleEventResponse";
  997. private const string ConsoleEventCancel = "WinSCPConsoleEventCancel";
  998. private const string ConsoleJob = "WinSCPConsoleJob";
  999. private const string ExeExecutableFileName = "winscp.exe";
  1000. private Process _process;
  1001. private readonly object _lock = new object();
  1002. private readonly Logger _logger;
  1003. private readonly Session _session;
  1004. private EventWaitHandle _requestEvent;
  1005. private EventWaitHandle _responseEvent;
  1006. private EventWaitHandle _cancelEvent;
  1007. private SafeFileHandle _fileMapping;
  1008. private string _instanceName;
  1009. private Thread _thread;
  1010. private bool _abort;
  1011. private string _lastFromBeginning;
  1012. private string _incompleteLine;
  1013. private readonly List<string> _input = new List<string>();
  1014. private readonly List<string> _log = new List<string>();
  1015. private AutoResetEvent _inputEvent = new AutoResetEvent(false);
  1016. private Job _job;
  1017. private bool _cancel;
  1018. }
  1019. }