ExeSessionProcess.cs 40 KB

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