ExeSessionProcess.cs 46 KB

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