ExeSessionProcess.cs 46 KB

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