ExeSessionProcess.cs 50 KB

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