Session.cs 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Globalization;
  6. using System.Runtime.InteropServices;
  7. using System.Threading;
  8. using System.Xml;
  9. using Microsoft.Win32;
  10. using System.Diagnostics;
  11. namespace WinSCP
  12. {
  13. [Guid("38649D44-B839-4F2C-A9DC-5D45EEA4B5E9")]
  14. [ComVisible(true)]
  15. public enum SynchronizationMode
  16. {
  17. Local = 0,
  18. Remote = 1,
  19. Both = 2,
  20. };
  21. [Guid("3F770EC1-35F5-4A7B-A000-46A2F7A213D8")]
  22. [ComVisible(true)]
  23. [Flags]
  24. public enum SynchronizationCriteria
  25. {
  26. None = 0x00,
  27. Time = 0x01,
  28. Size = 0x02,
  29. Either = Time | Size,
  30. };
  31. public delegate void OutputDataReceivedEventHandler(object sender, OutputDataReceivedEventArgs e);
  32. public delegate void FileTransferredEventHandler(object sender, TransferEventArgs e);
  33. public delegate void FileTransferProgressEventHandler(object sender, FileTransferProgressEventArgs e);
  34. public delegate void FailedEventHandler(object sender, FailedEventArgs e);
  35. [Guid("56FFC5CE-3867-4EF0-A3B5-CFFBEB99EA35")]
  36. [ClassInterface(Constants.ClassInterface)]
  37. [ComVisible(true)]
  38. [ComSourceInterfaces(typeof(ISessionEvents))]
  39. public sealed class Session : IDisposable, IReflect
  40. {
  41. public string ExecutablePath { get { return _executablePath; } set { CheckNotOpened(); _executablePath = value; } }
  42. public string AdditionalExecutableArguments { get { return _additionalExecutableArguments; } set { CheckNotOpened(); _additionalExecutableArguments = value; } }
  43. public bool DefaultConfiguration { get { return _defaultConfiguration; } set { CheckNotOpened(); _defaultConfiguration = value; } }
  44. public bool DisableVersionCheck { get { return _disableVersionCheck; } set { CheckNotOpened(); _disableVersionCheck = value; } }
  45. public string IniFilePath { get { return _iniFilePath; } set { CheckNotOpened(); _iniFilePath = value; } }
  46. public TimeSpan ReconnectTime { get { return _reconnectTime; } set { CheckNotOpened(); _reconnectTime = value; } }
  47. public string DebugLogPath { get { CheckNotDisposed(); return Logger.LogPath; } set { CheckNotDisposed(); Logger.LogPath = value; } }
  48. public string SessionLogPath { get { return _sessionLogPath; } set { CheckNotOpened(); _sessionLogPath = value; } }
  49. public string XmlLogPath { get { return _xmlLogPath; } set { CheckNotOpened(); _xmlLogPath = value; } }
  50. #if DEBUG
  51. public bool GuardProcessWithJob { get { return _guardProcessWithJob; } set { CheckNotOpened(); _guardProcessWithJob = value; } }
  52. public bool TestHandlesClosed { get { return TestHandlesClosedInternal; } set { TestHandlesClosedInternal = value; } }
  53. #endif
  54. public TimeSpan Timeout { get; set; }
  55. public StringCollection Output { get; private set; }
  56. public bool Opened { get { CheckNotDisposed(); return (_process != null); } }
  57. public event FileTransferredEventHandler FileTransferred;
  58. public event FailedEventHandler Failed;
  59. public event OutputDataReceivedEventHandler OutputDataReceived;
  60. public event FileTransferProgressEventHandler FileTransferProgress
  61. {
  62. add
  63. {
  64. using (Logger.CreateCallstackAndLock())
  65. {
  66. CheckNotOpened();
  67. _fileTransferProgress += value;
  68. }
  69. }
  70. remove
  71. {
  72. using (Logger.CreateCallstackAndLock())
  73. {
  74. CheckNotOpened();
  75. _fileTransferProgress -= value;
  76. }
  77. }
  78. }
  79. public Session()
  80. {
  81. Logger = new Logger();
  82. using (Logger.CreateCallstackAndLock())
  83. {
  84. Timeout = new TimeSpan(0, 1, 0);
  85. _reconnectTime = TimeSpan.MaxValue;
  86. Output = new StringCollection();
  87. _operationResults = new List<OperationResultBase>();
  88. _events = new List<Action>();
  89. _eventsEvent = new AutoResetEvent(false);
  90. _disposed = false;
  91. _defaultConfiguration = true;
  92. _logUnique = 0;
  93. _guardProcessWithJob = true;
  94. }
  95. }
  96. public void Dispose()
  97. {
  98. using (Logger.CreateCallstackAndLock())
  99. {
  100. _disposed = true;
  101. Cleanup();
  102. Logger.Dispose();
  103. if (_eventsEvent != null)
  104. {
  105. _eventsEvent.Close();
  106. _eventsEvent = null;
  107. }
  108. GC.SuppressFinalize(this);
  109. }
  110. }
  111. public void Abort()
  112. {
  113. using (Logger.CreateCallstack())
  114. {
  115. CheckOpened();
  116. _aborted = true;
  117. // double-check
  118. if (_process != null)
  119. {
  120. _process.Abort();
  121. }
  122. }
  123. }
  124. public void Open(SessionOptions sessionOptions)
  125. {
  126. using (Logger.CreateCallstackAndLock())
  127. {
  128. CheckNotDisposed();
  129. if (Opened)
  130. {
  131. throw new InvalidOperationException("Session is already opened");
  132. }
  133. try
  134. {
  135. SetupTempPath();
  136. _process = new ExeSessionProcess(this);
  137. _process.OutputDataReceived += ProcessOutputDataReceived;
  138. _process.Start();
  139. GotOutput();
  140. // setup batch mode
  141. WriteCommand("option batch on");
  142. WriteCommand("option confirm off");
  143. if (ReconnectTime != TimeSpan.MaxValue)
  144. {
  145. WriteCommand(string.Format(CultureInfo.InvariantCulture, "option reconnecttime {0}", (int)ReconnectTime.TotalSeconds));
  146. }
  147. WriteCommand("open " + SessionOptionsToOpenArguments(sessionOptions));
  148. string logExplanation =
  149. string.Format(CultureInfo.CurrentCulture,
  150. "(response log file {0} was not created). This could indicate lack of write permissions to the log folder or problems starting WinSCP itself.",
  151. XmlLogPath);
  152. // Wait until the log file gets created or WinSCP terminates (in case of fatal error)
  153. do
  154. {
  155. if (_process.HasExited && !File.Exists(XmlLogPath))
  156. {
  157. string[] output = new string[Output.Count];
  158. Output.CopyTo(output, 0);
  159. Logger.WriteCounters();
  160. Logger.WriteProcesses();
  161. _process.WriteStatus();
  162. throw new SessionLocalException(this,
  163. string.Format(CultureInfo.CurrentCulture,
  164. "WinSCP process terminated with exit code {0} and output \"{1}\", without responding {2}",
  165. _process.ExitCode, string.Join(Environment.NewLine, output), logExplanation));
  166. }
  167. Thread.Sleep(50);
  168. CheckForTimeout(
  169. string.Format(CultureInfo.CurrentCulture,
  170. "WinSCP has not responded in time {0}",
  171. logExplanation));
  172. } while (!File.Exists(XmlLogPath));
  173. _logReader = new SessionLogReader(this);
  174. _reader = _logReader.WaitForNonEmptyElementAndCreateLogReader("session", LogReadFlags.ThrowFailures);
  175. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  176. {
  177. ReadElement(groupReader, LogReadFlags.ThrowFailures);
  178. }
  179. }
  180. catch(Exception e)
  181. {
  182. Logger.WriteLine("Exception: {0}", e);
  183. Cleanup();
  184. throw;
  185. }
  186. }
  187. }
  188. public RemoteDirectoryInfo ListDirectory(string path)
  189. {
  190. using (Logger.CreateCallstackAndLock())
  191. {
  192. CheckOpened();
  193. WriteCommand(string.Format(CultureInfo.InvariantCulture, "ls -- \"{0}\"", ArgumentEscape(IncludeTrailingSlash(path))));
  194. RemoteDirectoryInfo result = new RemoteDirectoryInfo();
  195. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  196. using (ElementLogReader lsReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("ls", LogReadFlags.ThrowFailures))
  197. {
  198. if (lsReader.TryWaitForNonEmptyElement("files", 0))
  199. {
  200. using (ElementLogReader filesReader = lsReader.CreateLogReader())
  201. {
  202. while (filesReader.TryWaitForNonEmptyElement("file", 0))
  203. {
  204. RemoteFileInfo fileInfo = new RemoteFileInfo();
  205. using (ElementLogReader fileReader = filesReader.CreateLogReader())
  206. {
  207. while (fileReader.Read(0))
  208. {
  209. string value;
  210. if (fileReader.GetEmptyElementValue("filename", out value))
  211. {
  212. fileInfo.Name = value;
  213. }
  214. else
  215. {
  216. ReadFile(fileInfo, fileReader);
  217. }
  218. }
  219. result.AddFile(fileInfo);
  220. }
  221. }
  222. }
  223. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  224. }
  225. else
  226. {
  227. // "files" not found, keep reading, we expect "failure"
  228. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  229. // only if not "failure", throw "files" not found
  230. throw SessionLocalException.CreateElementNotFound(this, "files");
  231. }
  232. }
  233. return result;
  234. }
  235. }
  236. public TransferOperationResult PutFiles(string localPath, string remotePath, bool remove = false, TransferOptions options = null)
  237. {
  238. using (Logger.CreateCallstackAndLock())
  239. {
  240. if (options == null)
  241. {
  242. options = new TransferOptions();
  243. }
  244. CheckOpened();
  245. WriteCommand(
  246. string.Format(CultureInfo.InvariantCulture,
  247. "put {0} {1} -- \"{2}\" \"{3}\"",
  248. BooleanSwitch(remove, "delete"), options.ToSwitches(),
  249. ArgumentEscape(localPath), ArgumentEscape(remotePath)));
  250. TransferOperationResult result = new TransferOperationResult();
  251. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  252. using (RegisterOperationResult(result))
  253. using (CreateProgressHandler())
  254. {
  255. TransferEventArgs args = null;
  256. while (groupReader.Read(0))
  257. {
  258. if (groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag))
  259. {
  260. if (args != null)
  261. {
  262. result.AddTransfer(args);
  263. RaiseFileTransferredEvent(args);
  264. }
  265. args = TransferEventArgs.Read(groupReader);
  266. }
  267. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  268. {
  269. if (args == null)
  270. {
  271. throw new InvalidOperationException();
  272. }
  273. args.Chmod = ChmodEventArgs.Read(groupReader);
  274. }
  275. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  276. {
  277. if (args == null)
  278. {
  279. throw new InvalidOperationException();
  280. }
  281. args.Touch = TouchEventArgs.Read(groupReader);
  282. }
  283. }
  284. if (args != null)
  285. {
  286. result.AddTransfer(args);
  287. RaiseFileTransferredEvent(args);
  288. }
  289. }
  290. return result;
  291. }
  292. }
  293. public TransferOperationResult GetFiles(string remotePath, string localPath, bool remove = false, TransferOptions options = null)
  294. {
  295. using (Logger.CreateCallstackAndLock())
  296. {
  297. if (options == null)
  298. {
  299. options = new TransferOptions();
  300. }
  301. CheckOpened();
  302. WriteCommand(
  303. string.Format(CultureInfo.InvariantCulture, "get {0} {1} -- \"{2}\" \"{3}\"",
  304. BooleanSwitch(remove, "delete"), options.ToSwitches(),
  305. ArgumentEscape(remotePath), ArgumentEscape(localPath)));
  306. TransferOperationResult result = new TransferOperationResult();
  307. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  308. using (RegisterOperationResult(result))
  309. using (CreateProgressHandler())
  310. {
  311. TransferEventArgs args = null;
  312. while (groupReader.Read(0))
  313. {
  314. if (groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
  315. {
  316. if (args != null)
  317. {
  318. result.AddTransfer(args);
  319. RaiseFileTransferredEvent(args);
  320. }
  321. args = TransferEventArgs.Read(groupReader);
  322. }
  323. else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  324. {
  325. if (args == null)
  326. {
  327. throw new InvalidOperationException();
  328. }
  329. args.Removal = RemovalEventArgs.Read(groupReader);
  330. }
  331. }
  332. if (args != null)
  333. {
  334. result.AddTransfer(args);
  335. RaiseFileTransferredEvent(args);
  336. }
  337. }
  338. return result;
  339. }
  340. }
  341. public RemovalOperationResult RemoveFiles(string path)
  342. {
  343. using (Logger.CreateCallstackAndLock())
  344. {
  345. CheckOpened();
  346. WriteCommand(string.Format(CultureInfo.InvariantCulture, "rm -- \"{0}\"", ArgumentEscape(path)));
  347. RemovalOperationResult result = new RemovalOperationResult();
  348. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  349. using (RegisterOperationResult(result))
  350. {
  351. while (groupReader.Read(0))
  352. {
  353. if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  354. {
  355. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  356. }
  357. }
  358. }
  359. return result;
  360. }
  361. }
  362. public SynchronizationResult SynchronizeDirectories(
  363. SynchronizationMode mode, string localPath, string remotePath,
  364. bool removeFiles, bool mirror = false, SynchronizationCriteria criteria = SynchronizationCriteria.Time,
  365. TransferOptions options = null)
  366. {
  367. using (Logger.CreateCallstackAndLock())
  368. {
  369. if (options == null)
  370. {
  371. options = new TransferOptions();
  372. }
  373. CheckOpened();
  374. if (removeFiles && (mode == SynchronizationMode.Both))
  375. {
  376. throw new ArgumentException("Cannot delete files in synchronization mode Both");
  377. }
  378. if (mirror && (mode == SynchronizationMode.Both))
  379. {
  380. throw new ArgumentException("Cannot mirror files in synchronization mode Both");
  381. }
  382. if ((criteria != SynchronizationCriteria.Time) && (mode == SynchronizationMode.Both))
  383. {
  384. throw new ArgumentException("Only Time criteria is allowed in synchronization mode Both");
  385. }
  386. string modeName;
  387. switch (mode)
  388. {
  389. case SynchronizationMode.Local:
  390. modeName = "local";
  391. break;
  392. case SynchronizationMode.Remote:
  393. modeName = "remote";
  394. break;
  395. case SynchronizationMode.Both:
  396. modeName = "both";
  397. break;
  398. default:
  399. throw new ArgumentOutOfRangeException("mode");
  400. }
  401. List<string> criteriaNames = new List<string>();
  402. if ((criteria & SynchronizationCriteria.Time) == SynchronizationCriteria.Time)
  403. {
  404. criteria -= SynchronizationCriteria.Time;
  405. criteriaNames.Add("time");
  406. }
  407. if ((criteria & SynchronizationCriteria.Size) == SynchronizationCriteria.Size)
  408. {
  409. criteria -= SynchronizationCriteria.Size;
  410. criteriaNames.Add("size");
  411. }
  412. if (criteria != 0)
  413. {
  414. throw new ArgumentOutOfRangeException("criteria");
  415. }
  416. WriteCommand(
  417. string.Format(CultureInfo.InvariantCulture,
  418. "synchronize {0} {1} {2} {3} {4} -- \"{5}\" \"{6}\"",
  419. modeName,
  420. BooleanSwitch(removeFiles, "delete"),
  421. BooleanSwitch(mirror, "mirror"),
  422. options.ToSwitches(),
  423. FormatSwitch("criteria", string.Join(",", criteriaNames.ToArray())),
  424. ArgumentEscape(localPath), ArgumentEscape(remotePath)));
  425. return ReadSynchronizeDirectories();
  426. }
  427. }
  428. private SynchronizationResult ReadSynchronizeDirectories()
  429. {
  430. using (Logger.CreateCallstack())
  431. {
  432. SynchronizationResult result = new SynchronizationResult();
  433. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  434. using (RegisterOperationResult(result))
  435. using (CreateProgressHandler())
  436. {
  437. bool transferIsUpload = false;
  438. TransferEventArgs transfer = null;
  439. while (groupReader.Read(0))
  440. {
  441. bool transferWillBeUpload;
  442. if ((transferWillBeUpload = groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag)) ||
  443. groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
  444. {
  445. if (transfer != null)
  446. {
  447. AddSynchronizationTransfer(result, transferIsUpload, transfer);
  448. }
  449. transfer = TransferEventArgs.Read(groupReader);
  450. transferIsUpload = transferWillBeUpload;
  451. }
  452. else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  453. {
  454. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  455. }
  456. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  457. {
  458. if (transfer == null)
  459. {
  460. throw new InvalidOperationException();
  461. }
  462. transfer.Chmod = ChmodEventArgs.Read(groupReader);
  463. }
  464. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  465. {
  466. if (transfer == null)
  467. {
  468. throw new InvalidOperationException();
  469. }
  470. transfer.Touch = TouchEventArgs.Read(groupReader);
  471. }
  472. }
  473. if (transfer != null)
  474. {
  475. AddSynchronizationTransfer(result, transferIsUpload, transfer);
  476. }
  477. }
  478. return result;
  479. }
  480. }
  481. public CommandExecutionResult ExecuteCommand(string command)
  482. {
  483. using (Logger.CreateCallstackAndLock())
  484. {
  485. CheckOpened();
  486. WriteCommand(string.Format(CultureInfo.InvariantCulture, "call {0}", command));
  487. CommandExecutionResult result = new CommandExecutionResult();
  488. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  489. using (ElementLogReader callReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("call", LogReadFlags.ThrowFailures))
  490. {
  491. while (callReader.Read(0))
  492. {
  493. string value;
  494. if (callReader.GetEmptyElementValue("output", out value))
  495. {
  496. result.Output = value;
  497. }
  498. if (callReader.GetEmptyElementValue("erroroutput", out value))
  499. {
  500. result.ErrorOutput = value;
  501. }
  502. }
  503. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  504. }
  505. return result;
  506. }
  507. }
  508. public RemoteFileInfo GetFileInfo(string path)
  509. {
  510. using (Logger.CreateCallstackAndLock())
  511. {
  512. CheckOpened();
  513. return DoGetFileInfo(path);
  514. }
  515. }
  516. public bool FileExists(string path)
  517. {
  518. using (Logger.CreateCallstackAndLock())
  519. {
  520. CheckOpened();
  521. try
  522. {
  523. DoGetFileInfo(path);
  524. return true;
  525. }
  526. catch (SessionRemoteException)
  527. {
  528. return false;
  529. }
  530. }
  531. }
  532. public void CreateDirectory(string path)
  533. {
  534. using (Logger.CreateCallstackAndLock())
  535. {
  536. CheckOpened();
  537. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mkdir \"{0}\"", ArgumentEscape(path)));
  538. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  539. using (ElementLogReader mkdirReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("mkdir", LogReadFlags.ThrowFailures))
  540. {
  541. ReadElement(mkdirReader, 0);
  542. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  543. }
  544. }
  545. }
  546. public void MoveFile(string sourcePath, string targetPath)
  547. {
  548. using (Logger.CreateCallstackAndLock())
  549. {
  550. CheckOpened();
  551. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mv \"{0}\" \"{1}\"", ArgumentEscape(sourcePath), ArgumentEscape(targetPath)));
  552. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  553. using (ElementLogReader mvReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("mv", LogReadFlags.ThrowFailures))
  554. {
  555. ReadElement(mvReader, 0);
  556. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  557. }
  558. }
  559. }
  560. // This is not static method only to make it visible to COM
  561. public string EscapeFileMask(string fileMask)
  562. {
  563. if (fileMask == null)
  564. {
  565. throw new ArgumentNullException("fileMask");
  566. }
  567. int lastSlash = fileMask.LastIndexOf('/');
  568. string path = lastSlash > 0 ? fileMask.Substring(0, lastSlash + 1) : string.Empty;
  569. string mask = lastSlash > 0 ? fileMask.Substring(lastSlash + 1) : fileMask;
  570. mask = mask.Replace("[", "[[]").Replace("*", "[*]").Replace("?", "[?]");
  571. return path + mask;
  572. }
  573. [ComRegisterFunction]
  574. private static void ComRegister(Type t)
  575. {
  576. string subKey = GetTypeLibKey(t);
  577. Assembly assembly = Assembly.GetAssembly(t);
  578. object[] attributes = assembly.GetCustomAttributes(typeof(GuidAttribute), false);
  579. if (attributes.Length == 0)
  580. {
  581. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Cannot find {0} attribute for assembly {1}", typeof(GuidAttribute), assembly));
  582. }
  583. GuidAttribute guidAttribute = (GuidAttribute)attributes[0];
  584. Registry.ClassesRoot.CreateSubKey(subKey).SetValue(null, guidAttribute.Value);
  585. }
  586. [ComUnregisterFunction]
  587. private static void ComUnregister(Type t)
  588. {
  589. string subKey = GetTypeLibKey(t);
  590. Registry.ClassesRoot.DeleteSubKey(subKey, false);
  591. }
  592. private void ReadFile(RemoteFileInfo fileInfo, CustomLogReader fileReader)
  593. {
  594. using (Logger.CreateCallstack())
  595. {
  596. string value;
  597. if (fileReader.GetEmptyElementValue("type", out value))
  598. {
  599. fileInfo.FileType = value[0];
  600. }
  601. else if (fileReader.GetEmptyElementValue("size", out value))
  602. {
  603. fileInfo.Length = long.Parse(value, CultureInfo.InvariantCulture);
  604. }
  605. else if (fileReader.GetEmptyElementValue("modification", out value))
  606. {
  607. fileInfo.LastWriteTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Local);
  608. }
  609. else if (fileReader.GetEmptyElementValue("permissions", out value))
  610. {
  611. fileInfo.FilePermissions = FilePermissions.CreateReadOnlyFromText(value);
  612. }
  613. }
  614. }
  615. internal static string BooleanSwitch(bool flag, string name)
  616. {
  617. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", name) : null;
  618. }
  619. internal static string BooleanSwitch(bool flag, string onName, string offName)
  620. {
  621. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", onName) : string.Format(CultureInfo.InvariantCulture, "-{0}", offName);
  622. }
  623. private void AddSynchronizationTransfer(SynchronizationResult result, bool transferIsUpload, TransferEventArgs transfer)
  624. {
  625. if (transferIsUpload)
  626. {
  627. result.AddUpload(transfer);
  628. }
  629. else
  630. {
  631. result.AddDownload(transfer);
  632. }
  633. RaiseFileTransferredEvent(transfer);
  634. }
  635. private static string IncludeTrailingSlash(string path)
  636. {
  637. if (!string.IsNullOrEmpty(path) && !path.EndsWith("/", StringComparison.Ordinal))
  638. {
  639. path += '/';
  640. }
  641. return path;
  642. }
  643. private void Cleanup()
  644. {
  645. using (Logger.CreateCallstack())
  646. {
  647. if (_process != null)
  648. {
  649. Logger.WriteLine("Terminating process");
  650. try
  651. {
  652. try
  653. {
  654. WriteCommand("exit");
  655. _process.Close();
  656. }
  657. finally
  658. {
  659. _process.Dispose();
  660. _process = null;
  661. }
  662. }
  663. catch (Exception e)
  664. {
  665. Logger.WriteLine("Process cleanup Exception: {0}", e);
  666. }
  667. }
  668. Logger.WriteLine("Disposing log readers");
  669. if (_reader != null)
  670. {
  671. _reader.Dispose();
  672. _reader = null;
  673. }
  674. if (_logReader != null)
  675. {
  676. _logReader.Dispose();
  677. _logReader = null;
  678. }
  679. // Cleanup log file
  680. if ((XmlLogPath != null) && File.Exists(XmlLogPath))
  681. {
  682. Logger.WriteLine("Deleting XML log file [{0}]", XmlLogPath);
  683. try
  684. {
  685. File.Delete(XmlLogPath);
  686. }
  687. catch (DirectoryNotFoundException e)
  688. {
  689. Logger.WriteLine("XML log cleanup DirectoryNotFoundException: {0}", e);
  690. }
  691. catch (IOException e)
  692. {
  693. Logger.WriteLine("XML log cleanup IOException: {0}", e);
  694. }
  695. catch (UnauthorizedAccessException e)
  696. {
  697. Logger.WriteLine("XML log cleanup UnauthorizedAccessException: {0}", e);
  698. }
  699. _xmlLogPath = null;
  700. }
  701. }
  702. }
  703. private void WriteCommand(string command)
  704. {
  705. Logger.WriteLine("Command: [{0}]", command);
  706. _process.ExecuteCommand(command);
  707. GotOutput();
  708. }
  709. private static void ReadElement(CustomLogReader reader, LogReadFlags flags)
  710. {
  711. while (reader.Read(flags))
  712. {
  713. }
  714. }
  715. private string SessionOptionsToOpenArguments(SessionOptions sessionOptions)
  716. {
  717. using (Logger.CreateCallstack())
  718. {
  719. string url;
  720. switch (sessionOptions.Protocol)
  721. {
  722. case Protocol.Sftp:
  723. url = "sftp://";
  724. break;
  725. case Protocol.Scp:
  726. url = "scp://";
  727. break;
  728. case Protocol.Ftp:
  729. url = "ftp://";
  730. break;
  731. default:
  732. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.Protocol));
  733. }
  734. bool hasUsername = !string.IsNullOrEmpty(sessionOptions.UserName);
  735. if (hasUsername)
  736. {
  737. url += UriEscape(sessionOptions.UserName);
  738. }
  739. if (!string.IsNullOrEmpty(sessionOptions.Password))
  740. {
  741. if (!hasUsername)
  742. {
  743. throw new ArgumentException("SessionOptions.Password is set, but SessionOptions.UserName is not.");
  744. }
  745. url += ":" + UriEscape(sessionOptions.Password);
  746. }
  747. if (hasUsername)
  748. {
  749. url += "@";
  750. }
  751. if (string.IsNullOrEmpty(sessionOptions.HostName))
  752. {
  753. throw new ArgumentException("SessionOptions.HostName is not set.");
  754. }
  755. url += UriEscape(sessionOptions.HostName);
  756. if (sessionOptions.PortNumber != 0)
  757. {
  758. url += ":" + sessionOptions.PortNumber.ToString(CultureInfo.InvariantCulture);
  759. }
  760. string arguments = SessionOptionsToOpenSwitches(sessionOptions);
  761. arguments += (!string.IsNullOrEmpty(arguments) ? " " : "") + "\"" + ArgumentEscape(url) + "\"";
  762. if (sessionOptions.RawSettings.Count > 0)
  763. {
  764. arguments += " -rawsettings";
  765. foreach (KeyValuePair<string, string> rawSetting in sessionOptions.RawSettings)
  766. {
  767. arguments += string.Format(CultureInfo.InvariantCulture, " {0}=\"{1}\"", rawSetting.Key, ArgumentEscape(rawSetting.Value));
  768. }
  769. }
  770. return arguments;
  771. }
  772. }
  773. private string SessionOptionsToOpenSwitches(SessionOptions sessionOptions)
  774. {
  775. using (Logger.CreateCallstack())
  776. {
  777. List<string> switches = new List<string>();
  778. if (!string.IsNullOrEmpty(sessionOptions.SshHostKeyFingerprint) ||
  779. sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey)
  780. {
  781. if (!sessionOptions.IsSsh)
  782. {
  783. throw new ArgumentException("SessionOptions.SshHostKey or SessionOptions.GiveUpSecurityAndAcceptAnySshHostKey is set, but SessionOptions.Protocol is not Protocol.Sftp nor Protocol.Scp.");
  784. }
  785. string sshHostKeyFingerprint = sessionOptions.SshHostKeyFingerprint;
  786. if (sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey)
  787. {
  788. Logger.WriteLine("WARNING! Giving up security and accepting any key as configured");
  789. sshHostKeyFingerprint = AddStarToList(sshHostKeyFingerprint);
  790. }
  791. switches.Add(FormatSwitch("hostkey", sshHostKeyFingerprint));
  792. }
  793. else
  794. {
  795. if (sessionOptions.IsSsh && DefaultConfiguration)
  796. {
  797. throw new ArgumentException("SessionOptions.Protocol is Protocol.Sftp or Protocol.Scp, but SessionOptions.HostKey is not set.");
  798. }
  799. }
  800. if (!string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath))
  801. {
  802. if (!sessionOptions.IsSsh)
  803. {
  804. throw new ArgumentException("SessionOptions.SshPrivateKey is set, but SessionOptions.Protocol is not Protocol.Sftp nor Protocol.Scp.");
  805. }
  806. switches.Add(FormatSwitch("privatekey", sessionOptions.SshPrivateKeyPath));
  807. }
  808. if (sessionOptions.FtpSecure != FtpSecure.None)
  809. {
  810. if (sessionOptions.Protocol != Protocol.Ftp)
  811. {
  812. throw new ArgumentException("SessionOptions.FtpSecure is not FtpSecure.None, but SessionOptions.Protocol is not Protocol.Ftp.");
  813. }
  814. switch (sessionOptions.FtpSecure)
  815. {
  816. case FtpSecure.Implicit:
  817. switches.Add(FormatSwitch("implicit"));
  818. break;
  819. case FtpSecure.ExplicitSsl:
  820. switches.Add(FormatSwitch("explicitssl"));
  821. break;
  822. case FtpSecure.ExplicitTls:
  823. switches.Add(FormatSwitch("explicittls"));
  824. break;
  825. default:
  826. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.FtpSecure));
  827. }
  828. }
  829. if (!string.IsNullOrEmpty(sessionOptions.TlsHostCertificateFingerprint) ||
  830. sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
  831. {
  832. if (sessionOptions.FtpSecure == FtpSecure.None)
  833. {
  834. throw new ArgumentException("SessionOptions.TlsHostCertificateFingerprint or SessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate is set, but SessionOptions.FtpSecure is FtpSecure.None.");
  835. }
  836. string tlsHostCertificateFingerprint = sessionOptions.TlsHostCertificateFingerprint;
  837. if (sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
  838. {
  839. Logger.WriteLine("WARNING! Giving up security and accepting any certificate as configured");
  840. tlsHostCertificateFingerprint = AddStarToList(tlsHostCertificateFingerprint);
  841. }
  842. switches.Add(FormatSwitch("certificate", tlsHostCertificateFingerprint));
  843. }
  844. if (sessionOptions.Protocol == Protocol.Ftp)
  845. {
  846. switches.Add(FormatSwitch("passive", (sessionOptions.FtpMode == FtpMode.Passive)));
  847. }
  848. switches.Add(FormatSwitch("timeout", (int)sessionOptions.Timeout.TotalSeconds));
  849. return string.Join(" ", switches.ToArray());
  850. }
  851. }
  852. private static string AddStarToList(string list)
  853. {
  854. return (string.IsNullOrEmpty(list) ? string.Empty : list + ";") + "*";
  855. }
  856. private RemoteFileInfo DoGetFileInfo(string path)
  857. {
  858. using (Logger.CreateCallstack())
  859. {
  860. WriteCommand(string.Format(CultureInfo.InvariantCulture, "stat -- \"{0}\"", ArgumentEscape(path)));
  861. RemoteFileInfo fileInfo = new RemoteFileInfo();
  862. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  863. using (ElementLogReader statReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("stat", LogReadFlags.ThrowFailures))
  864. {
  865. while (statReader.Read(0))
  866. {
  867. string value;
  868. if (statReader.GetEmptyElementValue("filename", out value))
  869. {
  870. fileInfo.Name = value;
  871. }
  872. else if (statReader.IsNonEmptyElement("file"))
  873. {
  874. using (ElementLogReader fileReader = statReader.CreateLogReader())
  875. {
  876. while (fileReader.Read(0))
  877. {
  878. ReadFile(fileInfo, fileReader);
  879. }
  880. }
  881. }
  882. }
  883. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  884. }
  885. return fileInfo;
  886. }
  887. }
  888. internal static string FormatSwitch(string key)
  889. {
  890. return string.Format(CultureInfo.InvariantCulture, "-{0}", key);
  891. }
  892. internal static string FormatSwitch(string key, string value)
  893. {
  894. return string.Format(CultureInfo.InvariantCulture, "-{0}=\"{1}\"", key, ArgumentEscape(value));
  895. }
  896. internal static string FormatSwitch(string key, int value)
  897. {
  898. return string.Format(CultureInfo.InvariantCulture, "-{0}={1}", key, value.ToString(CultureInfo.InvariantCulture));
  899. }
  900. internal static string FormatSwitch(string key, bool value)
  901. {
  902. return FormatSwitch(key, (value ? 1 : 0));
  903. }
  904. internal static string ArgumentEscape(string value)
  905. {
  906. int i = 0;
  907. while (i < value.Length)
  908. {
  909. if (value[i] == '"')
  910. {
  911. value = value.Insert(i, "\"");
  912. ++i;
  913. }
  914. ++i;
  915. }
  916. return value;
  917. }
  918. private static string UriEscape(string s)
  919. {
  920. return Uri.EscapeDataString(s);
  921. }
  922. internal void GotOutput()
  923. {
  924. _lastOutput = DateTime.Now;
  925. }
  926. private void ProcessOutputDataReceived(object sender, OutputDataReceivedEventArgs e)
  927. {
  928. Logger.WriteLine("Scheduling output: [{0}]", e.Data);
  929. Output.InternalAdd(e.Data);
  930. GotOutput();
  931. ScheduleEvent(() => RaiseOutputDataReceived(e.Data));
  932. }
  933. private void ScheduleEvent(Action action)
  934. {
  935. lock (_events)
  936. {
  937. _events.Add(action);
  938. _eventsEvent.Set();
  939. }
  940. }
  941. internal void CheckForTimeout(string additional = null)
  942. {
  943. if (DateTime.Now - _lastOutput > Timeout)
  944. {
  945. string message = "Timeout waiting for WinSCP to respond";
  946. if (additional != null)
  947. {
  948. message += " - " + additional;
  949. }
  950. throw new TimeoutException(message);
  951. }
  952. if (_aborted)
  953. {
  954. throw new SessionLocalException(this, "Aborted.");
  955. }
  956. }
  957. private void RaiseFileTransferredEvent(TransferEventArgs args)
  958. {
  959. Logger.WriteLine("FileTransferredEvent: [{0}]", args.FileName);
  960. if (FileTransferred != null)
  961. {
  962. FileTransferred(this, args);
  963. }
  964. }
  965. internal void RaiseFailed(SessionRemoteException e)
  966. {
  967. Logger.WriteLine("Failed: [{0}]", e);
  968. if (Failed != null)
  969. {
  970. Failed(this, new FailedEventArgs { Error = e });
  971. }
  972. foreach (OperationResultBase operationResult in _operationResults)
  973. {
  974. operationResult.AddFailure(e);
  975. }
  976. }
  977. private void CheckNotDisposed()
  978. {
  979. if (_disposed)
  980. {
  981. throw new InvalidOperationException("Object is disposed");
  982. }
  983. if (_aborted)
  984. {
  985. throw new InvalidOperationException("Session was aborted");
  986. }
  987. }
  988. private void CheckOpened()
  989. {
  990. if (!Opened)
  991. {
  992. throw new InvalidOperationException("Session is not opened");
  993. }
  994. }
  995. private void CheckNotOpened()
  996. {
  997. if (Opened)
  998. {
  999. throw new InvalidOperationException("Session is already opened");
  1000. }
  1001. }
  1002. private void RaiseOutputDataReceived(string data)
  1003. {
  1004. Logger.WriteLine("Output: [{0}]", data);
  1005. if (OutputDataReceived != null)
  1006. {
  1007. OutputDataReceived(this, new OutputDataReceivedEventArgs(data));
  1008. }
  1009. }
  1010. internal void DispatchEvents(int interval)
  1011. {
  1012. DateTime start = DateTime.Now;
  1013. while (_eventsEvent.WaitOne(interval, false))
  1014. {
  1015. lock (_events)
  1016. {
  1017. foreach (Action action in _events)
  1018. {
  1019. action();
  1020. }
  1021. _events.Clear();
  1022. }
  1023. interval -= (int) (DateTime.Now - start).TotalMilliseconds;
  1024. if (interval < 0)
  1025. {
  1026. break;
  1027. }
  1028. start = DateTime.Now;
  1029. }
  1030. }
  1031. private IDisposable RegisterOperationResult(OperationResultBase operationResult)
  1032. {
  1033. _operationResults.Add(operationResult);
  1034. return new OperationResultGuard(this, operationResult);
  1035. }
  1036. internal void UnregisterOperationResult(OperationResultBase operationResult)
  1037. {
  1038. _operationResults.Remove(operationResult);
  1039. }
  1040. internal bool WantsProgress
  1041. {
  1042. get
  1043. {
  1044. return (_fileTransferProgress != null);
  1045. }
  1046. }
  1047. private IDisposable CreateProgressHandler()
  1048. {
  1049. _progressHandling++;
  1050. return new ProgressHandler(this);
  1051. }
  1052. internal void DisableProgressHandling()
  1053. {
  1054. if (_progressHandling <= 0)
  1055. {
  1056. throw new InvalidOperationException();
  1057. }
  1058. // make sure we process all pending progress events
  1059. DispatchEvents(0);
  1060. _progressHandling--;
  1061. }
  1062. internal void ProcessProgress(FileTransferProgressEventArgs args)
  1063. {
  1064. ScheduleEvent(() => Progress(args));
  1065. }
  1066. private void Progress(FileTransferProgressEventArgs args)
  1067. {
  1068. if ((_progressHandling >= 0) && WantsProgress)
  1069. {
  1070. _fileTransferProgress(this, args);
  1071. }
  1072. }
  1073. private void SetupTempPath()
  1074. {
  1075. using (Logger.CreateCallstack())
  1076. {
  1077. if (!string.IsNullOrEmpty(_xmlLogPath))
  1078. {
  1079. bool exists = File.Exists(_xmlLogPath);
  1080. Logger.WriteLine("Configured temporary file: {0} - Exists [{1}]", _xmlLogPath, exists);
  1081. if (exists)
  1082. {
  1083. throw new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Configured temporary file {0} already exists", _xmlLogPath));
  1084. }
  1085. }
  1086. else
  1087. {
  1088. string path = Path.GetTempPath();
  1089. Logger.WriteLine("Temporary folder: {0}", path);
  1090. string process = Process.GetCurrentProcess().Id.ToString("X4", CultureInfo.InvariantCulture);
  1091. string instance = GetHashCode().ToString("X8", CultureInfo.InvariantCulture);
  1092. string filename;
  1093. bool exists;
  1094. do
  1095. {
  1096. string uniqueStr = (_logUnique > 0 ? "." + _logUnique.ToString(CultureInfo.InvariantCulture) : string.Empty);
  1097. ++_logUnique;
  1098. filename = Path.Combine(path, "wscp" + process + "." + instance + uniqueStr + ".tmp");
  1099. exists = File.Exists(filename);
  1100. Logger.WriteLine("Temporary file [{0}] - Exists [{1}]", filename, exists);
  1101. }
  1102. while (exists);
  1103. _xmlLogPath = filename;
  1104. }
  1105. }
  1106. }
  1107. private static string GetTypeLibKey(Type t)
  1108. {
  1109. return "CLSID\\{" + t.GUID.ToString().ToUpperInvariant() + "}\\TypeLib";
  1110. }
  1111. FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
  1112. {
  1113. using (Logger.CreateCallstack())
  1114. {
  1115. Logger.WriteLine("Name [{0}]", name);
  1116. FieldInfo result = typeof(Session).GetField(name, bindingAttr);
  1117. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1118. return result;
  1119. }
  1120. }
  1121. FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
  1122. {
  1123. using (Logger.CreateCallstack())
  1124. {
  1125. FieldInfo[] result = typeof(Session).GetFields(bindingAttr);
  1126. Logger.WriteLine("Fields [{0}]", result.Length);
  1127. return result;
  1128. }
  1129. }
  1130. MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
  1131. {
  1132. using (Logger.CreateCallstack())
  1133. {
  1134. Logger.WriteLine("Name [{0}]", name);
  1135. MemberInfo[] result = typeof(Session).GetMember(name, bindingAttr);
  1136. Logger.WriteLine("Result [{0}]", result.Length);
  1137. return result;
  1138. }
  1139. }
  1140. MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
  1141. {
  1142. using (Logger.CreateCallstack())
  1143. {
  1144. MemberInfo[] result = typeof(Session).GetMembers(bindingAttr);
  1145. Logger.WriteLine("Result [{0}]", result.Length);
  1146. return result;
  1147. }
  1148. }
  1149. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
  1150. {
  1151. using (Logger.CreateCallstack())
  1152. {
  1153. Logger.WriteLine("Name [{0}]", name);
  1154. MethodInfo result = typeof(Session).GetMethod(name, bindingAttr);
  1155. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1156. return result;
  1157. }
  1158. }
  1159. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
  1160. {
  1161. using (Logger.CreateCallstack())
  1162. {
  1163. Logger.WriteLine("Name [{0}]", name);
  1164. MethodInfo result = typeof(Session).GetMethod(name, bindingAttr, binder, types, modifiers);
  1165. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1166. return result;
  1167. }
  1168. }
  1169. MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
  1170. {
  1171. using (Logger.CreateCallstack())
  1172. {
  1173. MethodInfo[] result = typeof(Session).GetMethods(bindingAttr);
  1174. Logger.WriteLine("Result [{0}]", result.Length);
  1175. return result;
  1176. }
  1177. }
  1178. PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
  1179. {
  1180. using (Logger.CreateCallstack())
  1181. {
  1182. PropertyInfo[] result = typeof(Session).GetProperties(bindingAttr);
  1183. Logger.WriteLine("Result [{0}]", result.Length);
  1184. return result;
  1185. }
  1186. }
  1187. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
  1188. {
  1189. using (Logger.CreateCallstack())
  1190. {
  1191. Logger.WriteLine("Name [{0}]", name);
  1192. PropertyInfo result = typeof(Session).GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
  1193. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1194. return result;
  1195. }
  1196. }
  1197. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
  1198. {
  1199. using (Logger.CreateCallstack())
  1200. {
  1201. Logger.WriteLine("Name [{0}]", name);
  1202. PropertyInfo result = typeof(Session).GetProperty(name, bindingAttr);
  1203. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1204. return result;
  1205. }
  1206. }
  1207. object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  1208. {
  1209. using (Logger.CreateCallstack())
  1210. {
  1211. Logger.WriteLine("Name [{0}]", name);
  1212. object result;
  1213. try
  1214. {
  1215. Logger.WriteLine("Target [{0}]", target);
  1216. if (args != null)
  1217. {
  1218. Logger.WriteLine("Args [{0}] [{1}]", args.Length, modifiers != null ? modifiers.Length.ToString(CultureInfo.InvariantCulture) : "null");
  1219. for (int i = 0; i < args.Length; ++i)
  1220. {
  1221. Logger.WriteLine("Arg [{0}] [{1}] [{2}]", i, args[i], (modifiers != null ? modifiers[i].ToString() : "null"));
  1222. }
  1223. }
  1224. Logger.WriteLine("Culture [{0}]", culture);
  1225. if (namedParameters != null)
  1226. {
  1227. foreach (string namedParameter in namedParameters)
  1228. {
  1229. Logger.WriteLine("NamedParameter [{0}]", namedParameter);
  1230. }
  1231. }
  1232. Logger.WriteLine("Invoking");
  1233. result = typeof(Session).InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  1234. Logger.WriteLine("Result [{0}]", result);
  1235. }
  1236. catch (Exception e)
  1237. {
  1238. Logger.WriteLine("Error [{0}]", e);
  1239. throw;
  1240. }
  1241. return result;
  1242. }
  1243. }
  1244. Type IReflect.UnderlyingSystemType
  1245. {
  1246. get { return typeof(Session); }
  1247. }
  1248. internal const string Namespace = "http://winscp.net/schema/session/1.0";
  1249. internal Logger Logger { get; private set; }
  1250. internal bool GuardProcessWithJobInternal { get { return _guardProcessWithJob; } set { CheckNotOpened(); _guardProcessWithJob = value; } }
  1251. internal bool TestHandlesClosedInternal { get; set; }
  1252. private ExeSessionProcess _process;
  1253. private DateTime _lastOutput;
  1254. private ElementLogReader _reader;
  1255. private SessionLogReader _logReader;
  1256. private readonly IList<OperationResultBase> _operationResults;
  1257. private delegate void Action();
  1258. private readonly IList<Action> _events;
  1259. private AutoResetEvent _eventsEvent;
  1260. private bool _disposed;
  1261. private string _executablePath;
  1262. private string _additionalExecutableArguments;
  1263. private bool _defaultConfiguration;
  1264. private bool _disableVersionCheck;
  1265. private string _iniFilePath;
  1266. private TimeSpan _reconnectTime;
  1267. private string _sessionLogPath;
  1268. private bool _aborted;
  1269. private int _logUnique;
  1270. private string _xmlLogPath;
  1271. private FileTransferProgressEventHandler _fileTransferProgress;
  1272. private int _progressHandling;
  1273. private bool _guardProcessWithJob;
  1274. }
  1275. }