ExeSessionProcess.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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. _thread.IsBackground = true;
  173. _thread.Start();
  174. }
  175. }
  176. // Handles returned by GetProcessWindowStation and GetThreadDesktop should not be closed
  177. internal class NoopSafeHandle : SafeHandle
  178. {
  179. public NoopSafeHandle(IntPtr handle) :
  180. base(handle, false)
  181. {
  182. }
  183. public override bool IsInvalid
  184. {
  185. get { return false; }
  186. }
  187. protected override bool ReleaseHandle()
  188. {
  189. return true;
  190. }
  191. }
  192. private void GrantAccess(IntPtr handle, int accessMask)
  193. {
  194. using (SafeHandle safeHandle = new NoopSafeHandle(handle))
  195. {
  196. GenericSecurity security =
  197. new GenericSecurity(false, ResourceType.WindowObject, safeHandle, AccessControlSections.Access);
  198. security.AddAccessRule(
  199. new GenericAccessRule(new NTAccount(_session.ExecutableProcessUserName), accessMask, AccessControlType.Allow));
  200. security.Persist(safeHandle, AccessControlSections.Access);
  201. }
  202. }
  203. private void ProcessExited(object sender, EventArgs e)
  204. {
  205. _logger.WriteLine("Process {0} exited with exit code {1}", _process.Id, _process.ExitCode);
  206. }
  207. private bool AbortedOrExited()
  208. {
  209. if (_abort)
  210. {
  211. _logger.WriteLine("Aborted");
  212. return true;
  213. }
  214. else if (_process.HasExited)
  215. {
  216. _logger.WriteLine("Exited");
  217. return true;
  218. }
  219. else
  220. {
  221. return false;
  222. }
  223. }
  224. private void ProcessEvents()
  225. {
  226. using (_logger.CreateCallstack())
  227. {
  228. while (!AbortedOrExited())
  229. {
  230. _logger.WriteLineLevel(1, "Waiting for request event");
  231. // Keep in sync with a delay in SessionLogReader.DoRead
  232. if (_requestEvent.WaitOne(100, false))
  233. {
  234. _logger.WriteLineLevel(1, "Got request event");
  235. ProcessEvent();
  236. }
  237. if (_logger.LogLevel >= 1)
  238. {
  239. _logger.WriteLine(string.Format(CultureInfo.InvariantCulture, "2nd generation collection count: {0}", GC.CollectionCount(2)));
  240. _logger.WriteLine(string.Format(CultureInfo.InvariantCulture, "Total memory allocated: {0}", GC.GetTotalMemory(false)));
  241. }
  242. }
  243. }
  244. }
  245. private void ProcessEvent()
  246. {
  247. using (_logger.CreateCallstack())
  248. {
  249. using (ConsoleCommStruct commStruct = AcquireCommStruct())
  250. {
  251. switch (commStruct.Event)
  252. {
  253. case ConsoleEvent.Print:
  254. ProcessPrintEvent(commStruct.PrintEvent);
  255. break;
  256. case ConsoleEvent.Input:
  257. ProcessInputEvent(commStruct.InputEvent);
  258. break;
  259. case ConsoleEvent.Choice:
  260. ProcessChoiceEvent(commStruct.ChoiceEvent);
  261. break;
  262. case ConsoleEvent.Title:
  263. ProcessTitleEvent(commStruct.TitleEvent);
  264. break;
  265. case ConsoleEvent.Init:
  266. ProcessInitEvent(commStruct.InitEvent);
  267. break;
  268. case ConsoleEvent.Progress:
  269. ProcessProgressEvent(commStruct.ProgressEvent);
  270. break;
  271. default:
  272. throw _logger.WriteException(new NotImplementedException());
  273. }
  274. }
  275. _responseEvent.Set();
  276. }
  277. }
  278. private void ProcessChoiceEvent(ConsoleChoiceEventStruct e)
  279. {
  280. using (_logger.CreateCallstack())
  281. {
  282. if (e.Timeouting)
  283. {
  284. Thread.Sleep((int)e.Timer);
  285. e.Result = e.Timeouted;
  286. }
  287. else
  288. {
  289. e.Result = e.Break;
  290. }
  291. _logger.WriteLine(
  292. "Options: [{0}], Timer: [{1}], Timeouting: [{2}], Timeouted: [{3}], Break: [{4}], Result: [{5}]",
  293. e.Options, e.Timer, e.Timeouting, e.Timeouted, e.Break, e.Result);
  294. }
  295. }
  296. private void ProcessTitleEvent(ConsoleTitleEventStruct e)
  297. {
  298. using (_logger.CreateCallstack())
  299. {
  300. _logger.WriteLine("Not-supported title event [{0}]", e.Title);
  301. }
  302. }
  303. private void ProcessInputEvent(ConsoleInputEventStruct e)
  304. {
  305. using (_logger.CreateCallstack())
  306. {
  307. while (!AbortedOrExited())
  308. {
  309. lock (_input)
  310. {
  311. if (_input.Count > 0)
  312. {
  313. e.Str = _input[0];
  314. e.Result = true;
  315. _input.RemoveAt(0);
  316. Print(false, false, _log[0] + "\n");
  317. _log.RemoveAt(0);
  318. return;
  319. }
  320. }
  321. _inputEvent.WaitOne(100, false);
  322. }
  323. }
  324. }
  325. private void Print(bool fromBeginning, bool error, string message)
  326. {
  327. if (fromBeginning && ((message.Length == 0) || (message[0] != '\n')))
  328. {
  329. _lastFromBeginning = message;
  330. _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);
  331. if (OutputDataReceived != null)
  332. {
  333. OutputDataReceived(this, null);
  334. }
  335. }
  336. else
  337. {
  338. if (!string.IsNullOrEmpty(_lastFromBeginning))
  339. {
  340. AddToOutput(_lastFromBeginning, false);
  341. _lastFromBeginning = null;
  342. }
  343. if (fromBeginning && (message.Length > 0) && (message[0] == '\n'))
  344. {
  345. AddToOutput("\n", false);
  346. _lastFromBeginning = message.Substring(1);
  347. _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);
  348. }
  349. else
  350. {
  351. AddToOutput(message, error);
  352. }
  353. }
  354. }
  355. private void AddToOutput(string message, bool error)
  356. {
  357. string[] lines = (_incompleteLine + message).Split(new[] { '\n' });
  358. _incompleteLine = lines[lines.Length - 1];
  359. for (int i = 0; i < lines.Length - 1; ++i)
  360. {
  361. if (OutputDataReceived != null)
  362. {
  363. OutputDataReceived(this, new OutputDataReceivedEventArgs(lines[i], error));
  364. }
  365. }
  366. }
  367. private void ProcessPrintEvent(ConsolePrintEventStruct e)
  368. {
  369. _logger.WriteLineLevel(1, string.Format(CultureInfo.CurrentCulture, "Print: {0}", e.Message));
  370. Print(e.FromBeginning, e.Error, e.Message);
  371. }
  372. private void ProcessInitEvent(ConsoleInitEventStruct e)
  373. {
  374. using (_logger.CreateCallstack())
  375. {
  376. e.InputType = 3; // pipe
  377. e.OutputType = 3; // pipe
  378. e.WantsProgress = _session.WantsProgress;
  379. }
  380. }
  381. private void ProcessProgressEvent(ConsoleProgressEventStruct e)
  382. {
  383. using (_logger.CreateCallstack())
  384. {
  385. _logger.WriteLine(
  386. "File Name [{0}] - Directory [{1}] - Overall Progress [{2}] - File Progress [{3}] - CPS [{4}]",
  387. e.FileName, e.Directory, e.OverallProgress, e.FileProgress, e.CPS);
  388. if (!_cancel)
  389. {
  390. FileTransferProgressEventArgs args = new FileTransferProgressEventArgs();
  391. switch (e.Operation)
  392. {
  393. case ConsoleProgressEventStruct.ProgressOperation.Copy:
  394. args.Operation = ProgressOperation.Transfer;
  395. break;
  396. default:
  397. throw _logger.WriteException(new ArgumentOutOfRangeException("Unknown progress operation", (Exception)null));
  398. }
  399. switch (e.Side)
  400. {
  401. case ConsoleProgressEventStruct.ProgressSide.Local:
  402. args.Side = ProgressSide.Local;
  403. break;
  404. case ConsoleProgressEventStruct.ProgressSide.Remote:
  405. args.Side = ProgressSide.Remote;
  406. break;
  407. default:
  408. throw _logger.WriteException(new ArgumentOutOfRangeException("Unknown progress side", (Exception)null));
  409. }
  410. args.FileName = e.FileName;
  411. args.Directory = e.Directory;
  412. args.OverallProgress = ((double)e.OverallProgress) / 100;
  413. args.FileProgress = ((double)e.FileProgress) / 100;
  414. args.CPS = (int)e.CPS;
  415. args.Cancel = false;
  416. _session.ProcessProgress(args);
  417. }
  418. if (_cancel)
  419. {
  420. e.Cancel = true;
  421. }
  422. }
  423. }
  424. private void InitializeConsole()
  425. {
  426. using (_logger.CreateCallstack())
  427. {
  428. int attempts = 0;
  429. Random random = new Random();
  430. int process = Process.GetCurrentProcess().Id;
  431. do
  432. {
  433. if (attempts > MaxAttempts)
  434. {
  435. throw _logger.WriteException(new SessionLocalException(_session, "Cannot find unique name for event object."));
  436. }
  437. int instanceNumber = random.Next(1000);
  438. _instanceName = string.Format(CultureInfo.InvariantCulture, "_{0}_{1}_{2}", process, GetHashCode(), instanceNumber);
  439. _logger.WriteLine("Trying event {0}", _instanceName);
  440. if (!TryCreateEvent(ConsoleEventRequest + _instanceName, out _requestEvent))
  441. {
  442. _logger.WriteLine("Event {0} is not unique", _instanceName);
  443. _requestEvent.Close();
  444. _requestEvent = null;
  445. }
  446. else
  447. {
  448. _logger.WriteLine("Event {0} is unique", _instanceName);
  449. _responseEvent = CreateEvent(ConsoleEventResponse + _instanceName);
  450. _cancelEvent = CreateEvent(ConsoleEventCancel + _instanceName);
  451. string fileMappingName = ConsoleMapping + _instanceName;
  452. _fileMapping = CreateFileMapping(fileMappingName);
  453. if (Marshal.GetLastWin32Error() == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  454. {
  455. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "File mapping {0} already exists", fileMappingName)));
  456. }
  457. if (_fileMapping.IsInvalid)
  458. {
  459. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Cannot create file mapping {0}", fileMappingName)));
  460. }
  461. }
  462. ++attempts;
  463. }
  464. while (_requestEvent == null);
  465. using (ConsoleCommStruct commStruct = AcquireCommStruct())
  466. {
  467. commStruct.InitHeader();
  468. }
  469. if (_session.GuardProcessWithJobInternal)
  470. {
  471. string jobName = ConsoleJob + _instanceName;
  472. _job = new Job(_logger, jobName);
  473. }
  474. }
  475. }
  476. private SafeFileHandle CreateFileMapping(string fileMappingName)
  477. {
  478. unsafe
  479. {
  480. IntPtr securityAttributesPtr = IntPtr.Zero;
  481. // We use the EventWaitHandleSecurity only to generate the descriptor binary form
  482. // that does not differ for object types, so we abuse the existing "event handle" implementation,
  483. // not to have to create the file mapping SecurityAttributes via P/Invoke.
  484. // .NET 4 supports MemoryMappedFile and MemoryMappedFileSecurity natively already
  485. EventWaitHandleSecurity security = CreateSecurity((EventWaitHandleRights)FileMappingRights.AllAccess);
  486. if (security != null)
  487. {
  488. SecurityAttributes securityAttributes = new SecurityAttributes();
  489. securityAttributes.nLength = (uint)Marshal.SizeOf(securityAttributes);
  490. byte[] descriptorBinaryForm = security.GetSecurityDescriptorBinaryForm();
  491. byte * buffer = stackalloc byte[descriptorBinaryForm.Length];
  492. for (int i = 0; i < descriptorBinaryForm.Length; i++)
  493. {
  494. buffer[i] = descriptorBinaryForm[i];
  495. }
  496. securityAttributes.lpSecurityDescriptor = (IntPtr)buffer;
  497. int length = Marshal.SizeOf(typeof(SecurityAttributes));
  498. securityAttributesPtr = Marshal.AllocHGlobal(length);
  499. Marshal.StructureToPtr(securityAttributes, securityAttributesPtr, false);
  500. }
  501. return
  502. UnsafeNativeMethods.CreateFileMapping(
  503. new SafeFileHandle(new IntPtr(-1), true), securityAttributesPtr, FileMapProtection.PageReadWrite, 0,
  504. ConsoleCommStruct.Size, fileMappingName);
  505. }
  506. }
  507. private ConsoleCommStruct AcquireCommStruct()
  508. {
  509. return new ConsoleCommStruct(_session, _fileMapping);
  510. }
  511. private bool TryCreateEvent(string name, out EventWaitHandle ev)
  512. {
  513. _logger.WriteLine("Creating event {0}", name);
  514. EventWaitHandleSecurity security = CreateSecurity(EventWaitHandleRights.FullControl);
  515. ev = new EventWaitHandle(false, EventResetMode.AutoReset, name, out bool createdNew, security);
  516. _logger.WriteLine(
  517. "Created event {0} with handle {1} with security {2}, new {3}",
  518. name, ev.SafeWaitHandle.DangerousGetHandle(),
  519. (security != null ? security.GetSecurityDescriptorSddlForm(AccessControlSections.All) : "none"), createdNew);
  520. return createdNew;
  521. }
  522. private EventWaitHandleSecurity CreateSecurity(EventWaitHandleRights eventRights)
  523. {
  524. EventWaitHandleSecurity security = null;
  525. // When "running as user", we have to grant the target user permissions to the objects (events and file mapping) explicitly
  526. if (!string.IsNullOrEmpty(_session.ExecutableProcessUserName))
  527. {
  528. security = new EventWaitHandleSecurity();
  529. IdentityReference si;
  530. try
  531. {
  532. si = new NTAccount(_session.ExecutableProcessUserName);
  533. }
  534. catch (Exception e)
  535. {
  536. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "Error resolving account {0}", _session.ExecutableProcessUserName), e));
  537. }
  538. EventWaitHandleAccessRule rule =
  539. new EventWaitHandleAccessRule(
  540. si, eventRights, AccessControlType.Allow);
  541. security.AddAccessRule(rule);
  542. }
  543. return security;
  544. }
  545. private EventWaitHandle CreateEvent(string name)
  546. {
  547. if (!TryCreateEvent(name, out EventWaitHandle ev))
  548. {
  549. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.InvariantCulture, "Event {0} already exists", name)));
  550. }
  551. return ev;
  552. }
  553. private void TestEventClosed(string name)
  554. {
  555. if (_session.TestHandlesClosedInternal)
  556. {
  557. _logger.WriteLine("Testing that event {0} is closed", name);
  558. if (TryCreateEvent(name, out EventWaitHandle ev))
  559. {
  560. ev.Close();
  561. }
  562. else
  563. {
  564. _logger.WriteLine("Exception: Event {0} was not closed yet", name);
  565. }
  566. }
  567. }
  568. private void AddInput(string str, string log)
  569. {
  570. Type structType = typeof(ConsoleInputEventStruct);
  571. FieldInfo strField = structType.GetField("Str");
  572. object[] attributes = strField.GetCustomAttributes(typeof(MarshalAsAttribute), false);
  573. if (attributes.Length != 1)
  574. {
  575. throw _logger.WriteException(new InvalidOperationException("MarshalAs attribute not found for ConsoleInputEventStruct.Str"));
  576. }
  577. MarshalAsAttribute marshalAsAttribute = (MarshalAsAttribute)attributes[0];
  578. if (marshalAsAttribute.SizeConst <= str.Length)
  579. {
  580. throw _logger.WriteException(
  581. new SessionLocalException(
  582. _session,
  583. string.Format(CultureInfo.CurrentCulture, "Input [{0}] is too long ({1} limit)", str, marshalAsAttribute.SizeConst)));
  584. }
  585. lock (_input)
  586. {
  587. _input.Add(str);
  588. _log.Add(log);
  589. _inputEvent.Set();
  590. }
  591. }
  592. public void ExecuteCommand(string command, string log)
  593. {
  594. using (_logger.CreateCallstack())
  595. {
  596. _cancel = false;
  597. AddInput(command, log);
  598. }
  599. }
  600. public void Close()
  601. {
  602. using (_logger.CreateCallstack())
  603. {
  604. int timeout;
  605. #if DEBUG
  606. // in debug build, we expect the winscp.exe to run in tracing mode, being very slow
  607. timeout = 10000;
  608. #else
  609. timeout = 2000;
  610. #endif
  611. _logger.WriteLine("Waiting for process to exit ({0} ms)", timeout);
  612. if (!_process.WaitForExit(timeout))
  613. {
  614. _logger.WriteLine("Killing process");
  615. _process.Kill();
  616. }
  617. }
  618. }
  619. public void Dispose()
  620. {
  621. using (_logger.CreateCallstack())
  622. {
  623. lock (_lock)
  624. {
  625. if (_session.TestHandlesClosedInternal)
  626. {
  627. _logger.WriteLine("Will test that handles are closed");
  628. }
  629. _abort = true;
  630. if (_thread != null)
  631. {
  632. _thread.Join();
  633. _thread = null;
  634. }
  635. if (_process != null)
  636. {
  637. _process.Dispose();
  638. _process = null;
  639. }
  640. if (_requestEvent != null)
  641. {
  642. _requestEvent.Close();
  643. TestEventClosed(ConsoleEventRequest + _instanceName);
  644. }
  645. if (_responseEvent != null)
  646. {
  647. _responseEvent.Close();
  648. TestEventClosed(ConsoleEventResponse + _instanceName);
  649. }
  650. if (_cancelEvent != null)
  651. {
  652. _cancelEvent.Close();
  653. TestEventClosed(ConsoleEventCancel + _instanceName);
  654. }
  655. if (_fileMapping != null)
  656. {
  657. _fileMapping.Dispose();
  658. _fileMapping = null;
  659. if (_session.TestHandlesClosedInternal)
  660. {
  661. _logger.WriteLine("Testing that file mapping is closed");
  662. string fileMappingName = ConsoleMapping + _instanceName;
  663. SafeFileHandle fileMapping = CreateFileMapping(fileMappingName);
  664. if (Marshal.GetLastWin32Error() == UnsafeNativeMethods.ERROR_ALREADY_EXISTS)
  665. {
  666. _logger.WriteLine("Exception: File mapping {0} was not closed yet", fileMappingName);
  667. }
  668. if (!fileMapping.IsInvalid)
  669. {
  670. fileMapping.Dispose();
  671. }
  672. }
  673. }
  674. if (_inputEvent != null)
  675. {
  676. _inputEvent.Close();
  677. _inputEvent = null;
  678. }
  679. if (_job != null)
  680. {
  681. _job.Dispose();
  682. _job = null;
  683. }
  684. }
  685. }
  686. }
  687. private string GetExecutablePath()
  688. {
  689. using (_logger.CreateCallstack())
  690. {
  691. string executablePath;
  692. if (!string.IsNullOrEmpty(_session.ExecutablePath))
  693. {
  694. executablePath = _session.ExecutablePath;
  695. if (!File.Exists(executablePath))
  696. {
  697. throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "{0} does not exists.", executablePath)));
  698. }
  699. }
  700. else
  701. {
  702. if (!TryFindExecutableInPath(GetAssemblyPath(), out executablePath) &&
  703. !TryFindExecutableInPath(GetInstallationPath(RegistryHive.CurrentUser, Registry.CurrentUser), out executablePath) &&
  704. !TryFindExecutableInPath(GetInstallationPath(RegistryHive.LocalMachine, Registry.LocalMachine), out executablePath) &&
  705. !TryFindExecutableInPath(GetDefaultInstallationPath(), out executablePath))
  706. {
  707. throw _logger.WriteException(
  708. new SessionLocalException(_session,
  709. string.Format(CultureInfo.CurrentCulture,
  710. "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}.",
  711. ExeExecutableFileName, GetAssemblyPath())));
  712. }
  713. }
  714. return executablePath;
  715. }
  716. }
  717. private static string GetDefaultInstallationPath()
  718. {
  719. string programFiles;
  720. if (IntPtr.Size == 8)
  721. {
  722. // In .NET 4 we can use Environment.SpecialFolder.ProgramFilesX86
  723. programFiles = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
  724. }
  725. else
  726. {
  727. programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  728. }
  729. return Path.Combine(programFiles, "WinSCP");
  730. }
  731. private static string GetInstallationPath(RegistryHive hive, RegistryKey rootKey)
  732. {
  733. OperatingSystem OS = Environment.OSVersion;
  734. string result;
  735. // Windows XP does not have the RegGetValue. We do not care about 64-bit XP.
  736. if ((OS.Version.Major < 5) || ((OS.Version.Major == 5) && (OS.Version.Minor <= 1)))
  737. {
  738. RegistryKey key = rootKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\winscp3_is1");
  739. result = (key != null) ? (string)key.GetValue("Inno Setup: App Path") : null;
  740. }
  741. else
  742. {
  743. // In .NET 4 we can use RegistryKey.OpenBaseKey(hive, RegistryView.Registry32);
  744. const string uninstallKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\winscp3_is1";
  745. const string appPathValue = @"Inno Setup: App Path";
  746. result = null;
  747. IntPtr data = IntPtr.Zero;
  748. uint len = 0;
  749. RegistryFlags flags = RegistryFlags.RegSz | RegistryFlags.SubKeyWow6432Key;
  750. UIntPtr key = (UIntPtr)((uint)hive);
  751. if (UnsafeNativeMethods.RegGetValue(key, uninstallKey, appPathValue, flags, out RegistryType type, data, ref len) == 0)
  752. {
  753. data = Marshal.AllocHGlobal((int)len);
  754. if (UnsafeNativeMethods.RegGetValue(key, uninstallKey, appPathValue, flags, out type, data, ref len) == 0)
  755. {
  756. result = Marshal.PtrToStringUni(data);
  757. }
  758. }
  759. }
  760. return result;
  761. }
  762. private bool TryFindExecutableInPath(string path, out string result)
  763. {
  764. if (string.IsNullOrEmpty(path))
  765. {
  766. result = null;
  767. }
  768. else
  769. {
  770. string executablePath = Path.Combine(path, ExeExecutableFileName);
  771. if (File.Exists(executablePath))
  772. {
  773. result = executablePath;
  774. _logger.WriteLine("Executable found in {0}", executablePath);
  775. }
  776. else
  777. {
  778. result = null;
  779. _logger.WriteLine("Executable not found in {0}", executablePath);
  780. }
  781. }
  782. return (result != null);
  783. }
  784. private string GetAssemblyPath()
  785. {
  786. string codeBasePath = _logger.GetAssemblyFilePath();
  787. string path = null;
  788. if (!string.IsNullOrEmpty(codeBasePath))
  789. {
  790. path = Path.GetDirectoryName(codeBasePath);
  791. Debug.Assert(path != null);
  792. }
  793. return path;
  794. }
  795. private void CheckVersion(string exePath, FileVersionInfo assemblyVersion)
  796. {
  797. using (_logger.CreateCallstack())
  798. {
  799. if (assemblyVersion == null)
  800. {
  801. _logger.WriteLine("Assembly version not known, cannot check version");
  802. }
  803. else if (assemblyVersion.ProductVersion == AssemblyConstants.UndefinedProductVersion)
  804. {
  805. _logger.WriteLine("Undefined assembly version, cannot check version");
  806. }
  807. else
  808. {
  809. FileVersionInfo version = FileVersionInfo.GetVersionInfo(exePath);
  810. _logger.WriteLine("Version of {0} is {1}, product {2} version is {3}", exePath, version.FileVersion, version.ProductName, version.ProductVersion);
  811. if (_session.DisableVersionCheckInternal)
  812. {
  813. _logger.WriteLine("Version check disabled (not recommended)");
  814. }
  815. else if (assemblyVersion.ProductVersion != version.ProductVersion)
  816. {
  817. throw _logger.WriteException(
  818. new SessionLocalException(
  819. _session, string.Format(CultureInfo.CurrentCulture,
  820. "The version of {0} ({1}) does not match version of this assembly {2} ({3}).",
  821. exePath, version.ProductVersion, _logger.GetAssemblyFilePath(), assemblyVersion.ProductVersion)));
  822. }
  823. }
  824. }
  825. }
  826. public void WriteStatus()
  827. {
  828. string executablePath = GetExecutablePath();
  829. _logger.WriteLine("{0} - exists [{1}]", executablePath, File.Exists(executablePath));
  830. }
  831. public void Cancel()
  832. {
  833. _cancel = true;
  834. }
  835. private const int MaxAttempts = 10;
  836. private const string ConsoleMapping = "WinSCPConsoleMapping";
  837. private const string ConsoleEventRequest = "WinSCPConsoleEventRequest";
  838. private const string ConsoleEventResponse = "WinSCPConsoleEventResponse";
  839. private const string ConsoleEventCancel = "WinSCPConsoleEventCancel";
  840. private const string ConsoleJob = "WinSCPConsoleJob";
  841. private const string ExeExecutableFileName = "winscp.exe";
  842. private Process _process;
  843. private readonly object _lock = new object();
  844. private readonly Logger _logger;
  845. private readonly Session _session;
  846. private EventWaitHandle _requestEvent;
  847. private EventWaitHandle _responseEvent;
  848. private EventWaitHandle _cancelEvent;
  849. private SafeFileHandle _fileMapping;
  850. private string _instanceName;
  851. private Thread _thread;
  852. private bool _abort;
  853. private string _lastFromBeginning;
  854. private string _incompleteLine;
  855. private readonly List<string> _input = new List<string>();
  856. private readonly List<string> _log = new List<string>();
  857. private AutoResetEvent _inputEvent = new AutoResetEvent(false);
  858. private Job _job;
  859. private bool _cancel;
  860. }
  861. }