ExeSessionProcess.cs 39 KB

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