Session.cs 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  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 int ReconnectTimeInMilliseconds { get { return Tools.TimeSpanToMilliseconds(ReconnectTime); } set { ReconnectTime = Tools.MillisecondsToTimeSpan(value); } }
  48. public string DebugLogPath { get { CheckNotDisposed(); return Logger.LogPath; } set { CheckNotDisposed(); Logger.LogPath = value; } }
  49. public int DebugLogLevel { get { CheckNotDisposed(); return Logger.LogLevel; } set { CheckNotDisposed(); Logger.LogLevel = value; } }
  50. public string SessionLogPath { get { return _sessionLogPath; } set { CheckNotOpened(); _sessionLogPath = value; } }
  51. public string XmlLogPath { get { return _xmlLogPath; } set { CheckNotOpened(); _xmlLogPath = value; } }
  52. #if DEBUG
  53. public bool GuardProcessWithJob { get { return GuardProcessWithJobInternal; } set { GuardProcessWithJobInternal = value; } }
  54. public bool TestHandlesClosed { get { return TestHandlesClosedInternal; } set { TestHandlesClosedInternal = value; } }
  55. #endif
  56. public string HomePath { get { CheckOpened(); return _homePath; } }
  57. public TimeSpan Timeout { get; set; }
  58. public StringCollection Output { get; private set; }
  59. public bool Opened { get { CheckNotDisposed(); return (_process != null); } }
  60. public event FileTransferredEventHandler FileTransferred;
  61. public event FailedEventHandler Failed;
  62. public event OutputDataReceivedEventHandler OutputDataReceived;
  63. public event FileTransferProgressEventHandler FileTransferProgress
  64. {
  65. add
  66. {
  67. using (Logger.CreateCallstackAndLock())
  68. {
  69. CheckNotOpened();
  70. _fileTransferProgress += value;
  71. }
  72. }
  73. remove
  74. {
  75. using (Logger.CreateCallstackAndLock())
  76. {
  77. CheckNotOpened();
  78. _fileTransferProgress -= value;
  79. }
  80. }
  81. }
  82. public Session()
  83. {
  84. Logger = new Logger();
  85. using (Logger.CreateCallstackAndLock())
  86. {
  87. Timeout = new TimeSpan(0, 1, 0);
  88. _reconnectTime = new TimeSpan(0, 2, 0); // keep in sync with TScript::OptionImpl
  89. Output = new StringCollection();
  90. _operationResults = new List<OperationResultBase>();
  91. _events = new List<Action>();
  92. _eventsEvent = new AutoResetEvent(false);
  93. _disposed = false;
  94. _defaultConfiguration = true;
  95. _logUnique = 0;
  96. _guardProcessWithJob = true;
  97. RawConfiguration = new Dictionary<string, string>();
  98. }
  99. }
  100. public void Dispose()
  101. {
  102. using (Logger.CreateCallstackAndLock())
  103. {
  104. _disposed = true;
  105. Cleanup();
  106. Logger.Dispose();
  107. if (_eventsEvent != null)
  108. {
  109. _eventsEvent.Close();
  110. _eventsEvent = null;
  111. }
  112. GC.SuppressFinalize(this);
  113. }
  114. }
  115. public void Abort()
  116. {
  117. using (Logger.CreateCallstack())
  118. {
  119. CheckOpened();
  120. _aborted = true;
  121. // double-check
  122. if (_process != null)
  123. {
  124. _process.Abort();
  125. }
  126. }
  127. }
  128. public void Open(SessionOptions sessionOptions)
  129. {
  130. using (Logger.CreateCallstackAndLock())
  131. {
  132. CheckNotDisposed();
  133. if (Opened)
  134. {
  135. throw new InvalidOperationException("Session is already opened");
  136. }
  137. try
  138. {
  139. SetupTempPath();
  140. _process = new ExeSessionProcess(this);
  141. _process.OutputDataReceived += ProcessOutputDataReceived;
  142. _process.Start();
  143. GotOutput();
  144. // setup batch mode
  145. WriteCommand("option batch on");
  146. WriteCommand("option confirm off");
  147. object reconnectTimeValue;
  148. if (ReconnectTime != TimeSpan.MaxValue)
  149. {
  150. reconnectTimeValue = (int)ReconnectTime.TotalSeconds;
  151. }
  152. else
  153. {
  154. reconnectTimeValue = "off";
  155. }
  156. string reconnectTimeCommand =
  157. string.Format(CultureInfo.InvariantCulture, "option reconnecttime {0}", reconnectTimeValue);
  158. WriteCommand(reconnectTimeCommand);
  159. string command;
  160. string log;
  161. SessionOptionsToOpenCommand(sessionOptions, out command, out log);
  162. WriteCommand(command, log);
  163. string logExplanation =
  164. string.Format(CultureInfo.CurrentCulture,
  165. "(response log file {0} was not created). This could indicate lack of write permissions to the log folder or problems starting WinSCP itself.",
  166. XmlLogPath);
  167. // Wait until the log file gets created or WinSCP terminates (in case of fatal error)
  168. do
  169. {
  170. if (_process.HasExited && !File.Exists(XmlLogPath))
  171. {
  172. string[] output = new string[Output.Count];
  173. Output.CopyTo(output, 0);
  174. Logger.WriteCounters();
  175. Logger.WriteProcesses();
  176. _process.WriteStatus();
  177. string exitCode = string.Format(CultureInfo.CurrentCulture, "{0}", _process.ExitCode);
  178. if (_process.ExitCode < 0)
  179. {
  180. exitCode = string.Format(CultureInfo.CurrentCulture, "{0} ({1:X})", exitCode, _process.ExitCode);
  181. }
  182. throw new SessionLocalException(this,
  183. string.Format(CultureInfo.CurrentCulture,
  184. "WinSCP process terminated with exit code {0} and output \"{1}\", without responding {2}",
  185. exitCode, string.Join(Environment.NewLine, output), logExplanation));
  186. }
  187. Thread.Sleep(50);
  188. CheckForTimeout(
  189. string.Format(CultureInfo.CurrentCulture,
  190. "WinSCP has not responded in time {0}",
  191. logExplanation));
  192. } while (!File.Exists(XmlLogPath));
  193. _logReader = new SessionLogReader(this);
  194. _logReader.WaitForNonEmptyElement("session", LogReadFlags.ThrowFailures);
  195. // special variant of ElementLogReader that throws when closing element (</session>) is encountered
  196. _reader = new SessionElementLogReader(_logReader);
  197. // Skip "open" command <group>
  198. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  199. {
  200. ReadElement(groupReader, LogReadFlags.ThrowFailures);
  201. }
  202. WriteCommand("pwd");
  203. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  204. using (ElementLogReader cwdReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("cwd", LogReadFlags.ThrowFailures))
  205. {
  206. while (cwdReader.Read(0))
  207. {
  208. string value;
  209. if (cwdReader.GetEmptyElementValue("cwd", out value))
  210. {
  211. _homePath = value;
  212. }
  213. }
  214. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  215. }
  216. }
  217. catch(Exception e)
  218. {
  219. Logger.WriteLine("Exception: {0}", e);
  220. Cleanup();
  221. throw;
  222. }
  223. }
  224. }
  225. public void Close()
  226. {
  227. using (Logger.CreateCallstackAndLock())
  228. {
  229. CheckOpened();
  230. Cleanup();
  231. }
  232. }
  233. public RemoteDirectoryInfo ListDirectory(string path)
  234. {
  235. using (Logger.CreateCallstackAndLock())
  236. {
  237. CheckOpened();
  238. WriteCommand(string.Format(CultureInfo.InvariantCulture, "ls -- \"{0}\"", Tools.ArgumentEscape(IncludeTrailingSlash(path))));
  239. RemoteDirectoryInfo result = new RemoteDirectoryInfo();
  240. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  241. using (ElementLogReader lsReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("ls", LogReadFlags.ThrowFailures))
  242. {
  243. if (lsReader.TryWaitForNonEmptyElement("files", 0))
  244. {
  245. using (ElementLogReader filesReader = lsReader.CreateLogReader())
  246. {
  247. while (filesReader.TryWaitForNonEmptyElement("file", 0))
  248. {
  249. RemoteFileInfo fileInfo = new RemoteFileInfo();
  250. using (ElementLogReader fileReader = filesReader.CreateLogReader())
  251. {
  252. while (fileReader.Read(0))
  253. {
  254. string value;
  255. if (fileReader.GetEmptyElementValue("filename", out value))
  256. {
  257. fileInfo.Name = value;
  258. }
  259. else
  260. {
  261. ReadFile(fileInfo, fileReader);
  262. }
  263. }
  264. result.AddFile(fileInfo);
  265. }
  266. }
  267. }
  268. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  269. }
  270. else
  271. {
  272. // "files" not found, keep reading, we expect "failure"
  273. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  274. // only if not "failure", throw "files" not found
  275. throw SessionLocalException.CreateElementNotFound(this, "files");
  276. }
  277. }
  278. return result;
  279. }
  280. }
  281. public TransferOperationResult PutFiles(string localPath, string remotePath, bool remove = false, TransferOptions options = null)
  282. {
  283. using (Logger.CreateCallstackAndLock())
  284. {
  285. if (options == null)
  286. {
  287. options = new TransferOptions();
  288. }
  289. CheckOpened();
  290. WriteCommand(
  291. string.Format(CultureInfo.InvariantCulture,
  292. "put {0} {1} -- \"{2}\" \"{3}\"",
  293. BooleanSwitch(remove, "delete"), options.ToSwitches(),
  294. Tools.ArgumentEscape(localPath), Tools.ArgumentEscape(remotePath)));
  295. TransferOperationResult result = new TransferOperationResult();
  296. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  297. using (RegisterOperationResult(result))
  298. using (CreateProgressHandler())
  299. {
  300. TransferEventArgs args = null;
  301. bool mkdir = false;
  302. while (groupReader.Read(0))
  303. {
  304. if (groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag))
  305. {
  306. AddTransfer(result, args);
  307. args = TransferEventArgs.Read(groupReader);
  308. mkdir = false;
  309. }
  310. else if (groupReader.IsNonEmptyElement(TransferEventArgs.MkDirTag))
  311. {
  312. AddTransfer(result, args);
  313. args = null;
  314. mkdir = true;
  315. // For now, silently ignoring results (even errors)
  316. // of mkdir operation, including future chmod/touch
  317. }
  318. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  319. {
  320. if (!mkdir)
  321. {
  322. if (args == null)
  323. {
  324. throw new InvalidOperationException("Tag chmod before tag upload");
  325. }
  326. args.Chmod = ChmodEventArgs.Read(groupReader);
  327. }
  328. }
  329. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  330. {
  331. if (!mkdir)
  332. {
  333. if (args == null)
  334. {
  335. throw new InvalidOperationException("Tag touch before tag upload");
  336. }
  337. args.Touch = TouchEventArgs.Read(groupReader);
  338. }
  339. }
  340. }
  341. AddTransfer(result, args);
  342. }
  343. return result;
  344. }
  345. }
  346. private void AddTransfer(TransferOperationResult result, TransferEventArgs args)
  347. {
  348. if (args != null)
  349. {
  350. result.AddTransfer(args);
  351. RaiseFileTransferredEvent(args);
  352. }
  353. }
  354. public TransferOperationResult GetFiles(string remotePath, string localPath, bool remove = false, TransferOptions options = null)
  355. {
  356. using (Logger.CreateCallstackAndLock())
  357. {
  358. if (options == null)
  359. {
  360. options = new TransferOptions();
  361. }
  362. CheckOpened();
  363. WriteCommand(
  364. string.Format(CultureInfo.InvariantCulture, "get {0} {1} -- \"{2}\" \"{3}\"",
  365. BooleanSwitch(remove, "delete"), options.ToSwitches(),
  366. Tools.ArgumentEscape(remotePath), Tools.ArgumentEscape(localPath)));
  367. TransferOperationResult result = new TransferOperationResult();
  368. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  369. using (RegisterOperationResult(result))
  370. using (CreateProgressHandler())
  371. {
  372. TransferEventArgs args = null;
  373. while (groupReader.Read(0))
  374. {
  375. if (groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
  376. {
  377. AddTransfer(result, args);
  378. args = TransferEventArgs.Read(groupReader);
  379. }
  380. else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  381. {
  382. // When "downloading and deleting" a folder,
  383. // we get "rm" tag without preceeding "download" tag.
  384. // So we use only the first "rm" tag after preceeding "download" tag,
  385. // silently ignoring the others
  386. if ((args != null) && (args.Removal == null))
  387. {
  388. args.Removal = RemovalEventArgs.Read(groupReader);
  389. }
  390. }
  391. }
  392. AddTransfer(result, args);
  393. }
  394. return result;
  395. }
  396. }
  397. public RemovalOperationResult RemoveFiles(string path)
  398. {
  399. using (Logger.CreateCallstackAndLock())
  400. {
  401. CheckOpened();
  402. WriteCommand(string.Format(CultureInfo.InvariantCulture, "rm -- \"{0}\"", Tools.ArgumentEscape(path)));
  403. RemovalOperationResult result = new RemovalOperationResult();
  404. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  405. using (RegisterOperationResult(result))
  406. {
  407. while (groupReader.Read(0))
  408. {
  409. if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  410. {
  411. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  412. }
  413. }
  414. }
  415. return result;
  416. }
  417. }
  418. public SynchronizationResult SynchronizeDirectories(
  419. SynchronizationMode mode, string localPath, string remotePath,
  420. bool removeFiles, bool mirror = false, SynchronizationCriteria criteria = SynchronizationCriteria.Time,
  421. TransferOptions options = null)
  422. {
  423. using (Logger.CreateCallstackAndLock())
  424. {
  425. if (options == null)
  426. {
  427. options = new TransferOptions();
  428. }
  429. CheckOpened();
  430. if (removeFiles && (mode == SynchronizationMode.Both))
  431. {
  432. throw new ArgumentException("Cannot delete files in synchronization mode Both");
  433. }
  434. if (mirror && (mode == SynchronizationMode.Both))
  435. {
  436. throw new ArgumentException("Cannot mirror files in synchronization mode Both");
  437. }
  438. if ((criteria != SynchronizationCriteria.Time) && (mode == SynchronizationMode.Both))
  439. {
  440. throw new ArgumentException("Only Time criteria is allowed in synchronization mode Both");
  441. }
  442. string modeName;
  443. switch (mode)
  444. {
  445. case SynchronizationMode.Local:
  446. modeName = "local";
  447. break;
  448. case SynchronizationMode.Remote:
  449. modeName = "remote";
  450. break;
  451. case SynchronizationMode.Both:
  452. modeName = "both";
  453. break;
  454. default:
  455. throw new ArgumentOutOfRangeException("mode");
  456. }
  457. string criteriaName;
  458. switch (criteria)
  459. {
  460. case SynchronizationCriteria.None:
  461. criteriaName = "none";
  462. break;
  463. case SynchronizationCriteria.Time:
  464. criteriaName = "time";
  465. break;
  466. case SynchronizationCriteria.Size:
  467. criteriaName = "size";
  468. break;
  469. case SynchronizationCriteria.Either:
  470. criteriaName = "either";
  471. break;
  472. default:
  473. throw new ArgumentOutOfRangeException("criteria");
  474. }
  475. WriteCommand(
  476. string.Format(CultureInfo.InvariantCulture,
  477. "synchronize {0} {1} {2} {3} -criteria=\"{4}\" -- \"{5}\" \"{6}\"",
  478. modeName,
  479. BooleanSwitch(removeFiles, "delete"),
  480. BooleanSwitch(mirror, "mirror"),
  481. options.ToSwitches(),
  482. criteriaName,
  483. Tools.ArgumentEscape(localPath), Tools.ArgumentEscape(remotePath)));
  484. return ReadSynchronizeDirectories();
  485. }
  486. }
  487. private SynchronizationResult ReadSynchronizeDirectories()
  488. {
  489. using (Logger.CreateCallstack())
  490. {
  491. SynchronizationResult result = new SynchronizationResult();
  492. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  493. using (RegisterOperationResult(result))
  494. using (CreateProgressHandler())
  495. {
  496. bool transferIsUpload = false;
  497. TransferEventArgs transfer = null;
  498. while (groupReader.Read(0))
  499. {
  500. bool transferWillBeUpload;
  501. if ((transferWillBeUpload = groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag)) ||
  502. groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
  503. {
  504. AddSynchronizationTransfer(result, transferIsUpload, transfer);
  505. transfer = TransferEventArgs.Read(groupReader);
  506. transferIsUpload = transferWillBeUpload;
  507. }
  508. else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  509. {
  510. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  511. }
  512. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  513. {
  514. if (transfer == null)
  515. {
  516. throw new InvalidOperationException("Tag chmod before tag download");
  517. }
  518. transfer.Chmod = ChmodEventArgs.Read(groupReader);
  519. }
  520. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  521. {
  522. if (transfer == null)
  523. {
  524. throw new InvalidOperationException("Tag touch before tag download");
  525. }
  526. transfer.Touch = TouchEventArgs.Read(groupReader);
  527. }
  528. }
  529. AddSynchronizationTransfer(result, transferIsUpload, transfer);
  530. }
  531. return result;
  532. }
  533. }
  534. public CommandExecutionResult ExecuteCommand(string command)
  535. {
  536. using (Logger.CreateCallstackAndLock())
  537. {
  538. CheckOpened();
  539. WriteCommand(string.Format(CultureInfo.InvariantCulture, "call {0}", command));
  540. CommandExecutionResult result = new CommandExecutionResult();
  541. // registering before creating group reader, so that
  542. // it is still registered, when group reader is read to the end in it's .Dispose();
  543. using (RegisterOperationResult(result))
  544. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  545. using (ElementLogReader callReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("call", LogReadFlags.ThrowFailures))
  546. {
  547. while (callReader.Read(0))
  548. {
  549. string value;
  550. if (callReader.GetEmptyElementValue("output", out value))
  551. {
  552. result.Output = value;
  553. }
  554. if (callReader.GetEmptyElementValue("erroroutput", out value))
  555. {
  556. result.ErrorOutput = value;
  557. }
  558. if (callReader.GetEmptyElementValue("exitcode", out value))
  559. {
  560. result.ExitCode = int.Parse(value, CultureInfo.InvariantCulture);
  561. }
  562. }
  563. }
  564. return result;
  565. }
  566. }
  567. public RemoteFileInfo GetFileInfo(string path)
  568. {
  569. using (Logger.CreateCallstackAndLock())
  570. {
  571. CheckOpened();
  572. return DoGetFileInfo(path);
  573. }
  574. }
  575. public bool FileExists(string path)
  576. {
  577. using (Logger.CreateCallstackAndLock())
  578. {
  579. CheckOpened();
  580. try
  581. {
  582. DoGetFileInfo(path);
  583. return true;
  584. }
  585. catch (SessionRemoteException)
  586. {
  587. return false;
  588. }
  589. }
  590. }
  591. public byte[] CalculateFileChecksum(string algorithm, string path)
  592. {
  593. using (Logger.CreateCallstack())
  594. {
  595. WriteCommand(string.Format(CultureInfo.InvariantCulture, "checksum -- \"{0}\" \"{1}\"", Tools.ArgumentEscape(algorithm), Tools.ArgumentEscape(path)));
  596. string hex = null;
  597. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  598. using (ElementLogReader checksumReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("checksum", LogReadFlags.ThrowFailures))
  599. {
  600. while (checksumReader.Read(0))
  601. {
  602. string value;
  603. if (checksumReader.GetEmptyElementValue("checksum", out value))
  604. {
  605. hex = value;
  606. }
  607. }
  608. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  609. }
  610. int len = hex.Length;
  611. if ((len % 2) != 0)
  612. {
  613. string error = string.Format(CultureInfo.CurrentCulture, "Invalid string representation of checksum - {0}", hex);
  614. throw new SessionLocalException(this, error);
  615. }
  616. int count = len / 2;
  617. byte[] bytes = new byte[count];
  618. for (int i = 0; i < count; i++)
  619. {
  620. bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
  621. }
  622. return bytes;
  623. }
  624. }
  625. public void CreateDirectory(string path)
  626. {
  627. using (Logger.CreateCallstackAndLock())
  628. {
  629. CheckOpened();
  630. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mkdir \"{0}\"", Tools.ArgumentEscape(path)));
  631. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  632. using (ElementLogReader mkdirReader = groupReader.WaitForNonEmptyElementAndCreateLogReader(TransferEventArgs.MkDirTag, LogReadFlags.ThrowFailures))
  633. {
  634. ReadElement(mkdirReader, 0);
  635. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  636. }
  637. }
  638. }
  639. public void MoveFile(string sourcePath, string targetPath)
  640. {
  641. using (Logger.CreateCallstackAndLock())
  642. {
  643. CheckOpened();
  644. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mv \"{0}\" \"{1}\"", Tools.ArgumentEscape(sourcePath), Tools.ArgumentEscape(targetPath)));
  645. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  646. using (ElementLogReader mvReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("mv", LogReadFlags.ThrowFailures))
  647. {
  648. ReadElement(mvReader, 0);
  649. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  650. }
  651. }
  652. }
  653. // This is not static method only to make it visible to COM
  654. public string EscapeFileMask(string fileMask)
  655. {
  656. if (fileMask == null)
  657. {
  658. throw new ArgumentNullException("fileMask");
  659. }
  660. int lastSlash = fileMask.LastIndexOf('/');
  661. string path = lastSlash > 0 ? fileMask.Substring(0, lastSlash + 1) : string.Empty;
  662. string mask = lastSlash > 0 ? fileMask.Substring(lastSlash + 1) : fileMask;
  663. mask = mask.Replace("[", "[[]").Replace("*", "[*]").Replace("?", "[?]");
  664. return path + mask;
  665. }
  666. public void AddRawConfiguration(string setting, string value)
  667. {
  668. RawConfiguration.Add(setting, value);
  669. }
  670. [ComRegisterFunction]
  671. private static void ComRegister(Type t)
  672. {
  673. string subKey = GetTypeLibKey(t);
  674. Assembly assembly = Assembly.GetAssembly(t);
  675. object[] attributes = assembly.GetCustomAttributes(typeof(GuidAttribute), false);
  676. if (attributes.Length == 0)
  677. {
  678. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Cannot find {0} attribute for assembly {1}", typeof(GuidAttribute), assembly));
  679. }
  680. GuidAttribute guidAttribute = (GuidAttribute)attributes[0];
  681. Registry.ClassesRoot.CreateSubKey(subKey).SetValue(null, guidAttribute.Value);
  682. }
  683. [ComUnregisterFunction]
  684. private static void ComUnregister(Type t)
  685. {
  686. string subKey = GetTypeLibKey(t);
  687. Registry.ClassesRoot.DeleteSubKey(subKey, false);
  688. }
  689. private void ReadFile(RemoteFileInfo fileInfo, CustomLogReader fileReader)
  690. {
  691. using (Logger.CreateCallstack())
  692. {
  693. string value;
  694. if (fileReader.GetEmptyElementValue("type", out value))
  695. {
  696. fileInfo.FileType = value[0];
  697. }
  698. else if (fileReader.GetEmptyElementValue("size", out value))
  699. {
  700. fileInfo.Length = long.Parse(value, CultureInfo.InvariantCulture);
  701. }
  702. else if (fileReader.GetEmptyElementValue("modification", out value))
  703. {
  704. fileInfo.LastWriteTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Local);
  705. }
  706. else if (fileReader.GetEmptyElementValue("permissions", out value))
  707. {
  708. fileInfo.FilePermissions = FilePermissions.CreateReadOnlyFromText(value);
  709. }
  710. else if (fileReader.GetEmptyElementValue("owner", out value))
  711. {
  712. fileInfo.Owner = value;
  713. }
  714. else if (fileReader.GetEmptyElementValue("group", out value))
  715. {
  716. fileInfo.Group = value;
  717. }
  718. }
  719. }
  720. internal static string BooleanSwitch(bool flag, string name)
  721. {
  722. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", name) : null;
  723. }
  724. internal static string BooleanSwitch(bool flag, string onName, string offName)
  725. {
  726. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", onName) : string.Format(CultureInfo.InvariantCulture, "-{0}", offName);
  727. }
  728. private void AddSynchronizationTransfer(SynchronizationResult result, bool transferIsUpload, TransferEventArgs transfer)
  729. {
  730. if (transfer != null)
  731. {
  732. if (transferIsUpload)
  733. {
  734. result.AddUpload(transfer);
  735. }
  736. else
  737. {
  738. result.AddDownload(transfer);
  739. }
  740. RaiseFileTransferredEvent(transfer);
  741. }
  742. }
  743. private static string IncludeTrailingSlash(string path)
  744. {
  745. if (!string.IsNullOrEmpty(path) && !path.EndsWith("/", StringComparison.Ordinal))
  746. {
  747. path += '/';
  748. }
  749. return path;
  750. }
  751. private void Cleanup()
  752. {
  753. using (Logger.CreateCallstack())
  754. {
  755. if (_process != null)
  756. {
  757. Logger.WriteLine("Terminating process");
  758. try
  759. {
  760. try
  761. {
  762. WriteCommand("exit");
  763. _process.Close();
  764. }
  765. finally
  766. {
  767. _process.Dispose();
  768. _process = null;
  769. }
  770. }
  771. catch (Exception e)
  772. {
  773. Logger.WriteLine("Process cleanup Exception: {0}", e);
  774. }
  775. }
  776. Logger.WriteLine("Disposing log readers");
  777. if (_reader != null)
  778. {
  779. _reader.Dispose();
  780. _reader = null;
  781. }
  782. if (_logReader != null)
  783. {
  784. _logReader.Dispose();
  785. _logReader = null;
  786. }
  787. // Cleanup log file
  788. if ((XmlLogPath != null) && File.Exists(XmlLogPath))
  789. {
  790. Logger.WriteLine("Deleting XML log file [{0}]", XmlLogPath);
  791. try
  792. {
  793. File.Delete(XmlLogPath);
  794. }
  795. catch (DirectoryNotFoundException e)
  796. {
  797. Logger.WriteLine("XML log cleanup DirectoryNotFoundException: {0}", e);
  798. }
  799. catch (IOException e)
  800. {
  801. Logger.WriteLine("XML log cleanup IOException: {0}", e);
  802. }
  803. catch (UnauthorizedAccessException e)
  804. {
  805. Logger.WriteLine("XML log cleanup UnauthorizedAccessException: {0}", e);
  806. }
  807. _xmlLogPath = null;
  808. }
  809. }
  810. }
  811. private void WriteCommand(string command)
  812. {
  813. WriteCommand(command, command);
  814. }
  815. private void WriteCommand(string command, string log)
  816. {
  817. Logger.WriteLine("Command: [{0}]", log);
  818. _process.ExecuteCommand(command);
  819. GotOutput();
  820. }
  821. private static void ReadElement(CustomLogReader reader, LogReadFlags flags)
  822. {
  823. while (reader.Read(flags))
  824. {
  825. }
  826. }
  827. private void SessionOptionsToOpenCommand(SessionOptions sessionOptions, out string command, out string log)
  828. {
  829. using (Logger.CreateCallstack())
  830. {
  831. if (sessionOptions.WebdavSecure)
  832. {
  833. if (sessionOptions.Protocol != Protocol.Webdav)
  834. {
  835. throw new ArgumentException("SessionOptions.WebdavSecure is set, but SessionOptions.Protocol is not Protocol.Webdav.");
  836. }
  837. }
  838. string head;
  839. switch (sessionOptions.Protocol)
  840. {
  841. case Protocol.Sftp:
  842. head = "sftp://";
  843. break;
  844. case Protocol.Scp:
  845. head = "scp://";
  846. break;
  847. case Protocol.Ftp:
  848. head = "ftp://";
  849. break;
  850. case Protocol.Webdav:
  851. if (!sessionOptions.WebdavSecure)
  852. {
  853. head = "http://";
  854. }
  855. else
  856. {
  857. head = "https://";
  858. }
  859. break;
  860. default:
  861. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.Protocol));
  862. }
  863. bool hasUsername = !string.IsNullOrEmpty(sessionOptions.UserName);
  864. if (hasUsername)
  865. {
  866. head += UriEscape(sessionOptions.UserName);
  867. }
  868. string url = head;
  869. string logUrl = head;
  870. if (sessionOptions.SecurePassword != null)
  871. {
  872. if (!hasUsername)
  873. {
  874. throw new ArgumentException("SessionOptions.Password is set, but SessionOptions.UserName is not.");
  875. }
  876. url += ":" + UriEscape(sessionOptions.Password);
  877. logUrl += ":***";
  878. }
  879. string tail = string.Empty;
  880. if (hasUsername)
  881. {
  882. tail += "@";
  883. }
  884. if (string.IsNullOrEmpty(sessionOptions.HostName))
  885. {
  886. throw new ArgumentException("SessionOptions.HostName is not set.");
  887. }
  888. // We should wrap IPv6 literals to square brackets, instead of URL-encoding them,
  889. // but it works anyway...
  890. tail += UriEscape(sessionOptions.HostName);
  891. if (sessionOptions.PortNumber != 0)
  892. {
  893. tail += ":" + sessionOptions.PortNumber.ToString(CultureInfo.InvariantCulture);
  894. }
  895. if (!string.IsNullOrEmpty(sessionOptions.WebdavRoot))
  896. {
  897. if (sessionOptions.Protocol != Protocol.Webdav)
  898. {
  899. throw new ArgumentException("SessionOptions.WebdavRoot is set, but SessionOptions.Protocol is not Protocol.Webdav.");
  900. }
  901. tail += sessionOptions.WebdavRoot;
  902. }
  903. url += tail;
  904. logUrl += tail;
  905. string arguments = SessionOptionsToOpenSwitches(sessionOptions);
  906. Tools.AddRawParameters(ref arguments, sessionOptions.RawSettings, "-rawsettings");
  907. if (!string.IsNullOrEmpty(arguments))
  908. {
  909. arguments = " " + arguments;
  910. }
  911. // Switches should (and particularly the -rawsettings MUST) come after the URL
  912. command = "open \"" + Tools.ArgumentEscape(url) + "\"" + arguments;
  913. log = "open \"" + Tools.ArgumentEscape(logUrl) + "\"" + arguments;
  914. }
  915. }
  916. private string SessionOptionsToOpenSwitches(SessionOptions sessionOptions)
  917. {
  918. using (Logger.CreateCallstack())
  919. {
  920. List<string> switches = new List<string>();
  921. if (!string.IsNullOrEmpty(sessionOptions.SshHostKeyFingerprint) ||
  922. sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey)
  923. {
  924. if (!sessionOptions.IsSsh)
  925. {
  926. throw new ArgumentException("SessionOptions.SshHostKeyFingerprint or SessionOptions.GiveUpSecurityAndAcceptAnySshHostKey is set, but SessionOptions.Protocol is neither Protocol.Sftp nor Protocol.Scp.");
  927. }
  928. string sshHostKeyFingerprint = sessionOptions.SshHostKeyFingerprint;
  929. if (sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey)
  930. {
  931. Logger.WriteLine("WARNING! Giving up security and accepting any key as configured");
  932. sshHostKeyFingerprint = AddStarToList(sshHostKeyFingerprint);
  933. }
  934. switches.Add(FormatSwitch("hostkey", sshHostKeyFingerprint));
  935. }
  936. else
  937. {
  938. if (sessionOptions.IsSsh && DefaultConfiguration)
  939. {
  940. throw new ArgumentException("SessionOptions.Protocol is Protocol.Sftp or Protocol.Scp, but SessionOptions.SshHostKeyFingerprint is not set.");
  941. }
  942. }
  943. if (!string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath))
  944. {
  945. if (!sessionOptions.IsSsh)
  946. {
  947. throw new ArgumentException("SessionOptions.SshPrivateKeyPath is set, but SessionOptions.Protocol is neither Protocol.Sftp nor Protocol.Scp.");
  948. }
  949. switches.Add(FormatSwitch("privatekey", sessionOptions.SshPrivateKeyPath));
  950. }
  951. if (!string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPassphrase))
  952. {
  953. if (string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath))
  954. {
  955. throw new ArgumentException("SessionOptions.SshPrivateKeyPassphrase is set, but sessionOptions.SshPrivateKeyPath is not.");
  956. }
  957. switches.Add(FormatSwitch("passphrase", sessionOptions.SshPrivateKeyPassphrase));
  958. }
  959. if (sessionOptions.FtpSecure != FtpSecure.None)
  960. {
  961. if (sessionOptions.Protocol != Protocol.Ftp)
  962. {
  963. throw new ArgumentException("SessionOptions.FtpSecure is not FtpSecure.None, but SessionOptions.Protocol is not Protocol.Ftp.");
  964. }
  965. switch (sessionOptions.FtpSecure)
  966. {
  967. case FtpSecure.Implicit:
  968. switches.Add(FormatSwitch("implicit"));
  969. break;
  970. case FtpSecure.Explicit: // and ExplicitTls
  971. switches.Add(FormatSwitch("explicit"));
  972. break;
  973. #pragma warning disable 618
  974. case FtpSecure.ExplicitSsl:
  975. #pragma warning restore 618
  976. switches.Add(FormatSwitch("explicitssl"));
  977. break;
  978. default:
  979. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.FtpSecure));
  980. }
  981. }
  982. if (!string.IsNullOrEmpty(sessionOptions.TlsHostCertificateFingerprint) ||
  983. sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
  984. {
  985. if ((sessionOptions.FtpSecure == FtpSecure.None) && !sessionOptions.WebdavSecure)
  986. {
  987. throw new ArgumentException("SessionOptions.TlsHostCertificateFingerprint or SessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate is set, neither SessionOptions.FtpSecure nor SessionOptions.WebdavSecure is enabled.");
  988. }
  989. string tlsHostCertificateFingerprint = sessionOptions.TlsHostCertificateFingerprint;
  990. if (sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
  991. {
  992. Logger.WriteLine("WARNING! Giving up security and accepting any certificate as configured");
  993. tlsHostCertificateFingerprint = AddStarToList(tlsHostCertificateFingerprint);
  994. }
  995. switches.Add(FormatSwitch("certificate", tlsHostCertificateFingerprint));
  996. }
  997. if (sessionOptions.Protocol == Protocol.Ftp)
  998. {
  999. switches.Add(FormatSwitch("passive", (sessionOptions.FtpMode == FtpMode.Passive)));
  1000. }
  1001. switches.Add(FormatSwitch("timeout", (int)sessionOptions.Timeout.TotalSeconds));
  1002. return string.Join(" ", switches.ToArray());
  1003. }
  1004. }
  1005. private static string AddStarToList(string list)
  1006. {
  1007. return (string.IsNullOrEmpty(list) ? string.Empty : list + ";") + "*";
  1008. }
  1009. private RemoteFileInfo DoGetFileInfo(string path)
  1010. {
  1011. using (Logger.CreateCallstack())
  1012. {
  1013. WriteCommand(string.Format(CultureInfo.InvariantCulture, "stat -- \"{0}\"", Tools.ArgumentEscape(path)));
  1014. RemoteFileInfo fileInfo = new RemoteFileInfo();
  1015. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1016. using (ElementLogReader statReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("stat", LogReadFlags.ThrowFailures))
  1017. {
  1018. while (statReader.Read(0))
  1019. {
  1020. string value;
  1021. if (statReader.GetEmptyElementValue("filename", out value))
  1022. {
  1023. fileInfo.Name = value;
  1024. }
  1025. else if (statReader.IsNonEmptyElement("file"))
  1026. {
  1027. using (ElementLogReader fileReader = statReader.CreateLogReader())
  1028. {
  1029. while (fileReader.Read(0))
  1030. {
  1031. ReadFile(fileInfo, fileReader);
  1032. }
  1033. }
  1034. }
  1035. }
  1036. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1037. }
  1038. return fileInfo;
  1039. }
  1040. }
  1041. internal static string FormatSwitch(string key)
  1042. {
  1043. return string.Format(CultureInfo.InvariantCulture, "-{0}", key);
  1044. }
  1045. internal static string FormatSwitch(string key, string value)
  1046. {
  1047. return string.Format(CultureInfo.InvariantCulture, "-{0}=\"{1}\"", key, Tools.ArgumentEscape(value));
  1048. }
  1049. internal static string FormatSwitch(string key, int value)
  1050. {
  1051. return string.Format(CultureInfo.InvariantCulture, "-{0}={1}", key, value.ToString(CultureInfo.InvariantCulture));
  1052. }
  1053. internal static string FormatSwitch(string key, bool value)
  1054. {
  1055. return FormatSwitch(key, (value ? 1 : 0));
  1056. }
  1057. private static string UriEscape(string s)
  1058. {
  1059. return Uri.EscapeDataString(s);
  1060. }
  1061. internal void GotOutput()
  1062. {
  1063. _lastOutput = DateTime.Now;
  1064. }
  1065. private void ProcessOutputDataReceived(object sender, OutputDataReceivedEventArgs e)
  1066. {
  1067. Logger.WriteLine("Scheduling output: [{0}]", e.Data);
  1068. Output.InternalAdd(e.Data);
  1069. if (Output.Count > 1000)
  1070. {
  1071. Output.InternalRemoveFirst();
  1072. }
  1073. GotOutput();
  1074. ScheduleEvent(() => RaiseOutputDataReceived(e.Data));
  1075. }
  1076. private void ScheduleEvent(Action action)
  1077. {
  1078. lock (_events)
  1079. {
  1080. _events.Add(action);
  1081. _eventsEvent.Set();
  1082. }
  1083. }
  1084. internal void CheckForTimeout(string additional = null)
  1085. {
  1086. if (DateTime.Now - _lastOutput > Timeout)
  1087. {
  1088. string message = "Timeout waiting for WinSCP to respond";
  1089. if (additional != null)
  1090. {
  1091. message += " - " + additional;
  1092. }
  1093. throw new TimeoutException(message);
  1094. }
  1095. if (_aborted)
  1096. {
  1097. throw new SessionLocalException(this, "Aborted.");
  1098. }
  1099. }
  1100. private void RaiseFileTransferredEvent(TransferEventArgs args)
  1101. {
  1102. Logger.WriteLine("FileTransferredEvent: [{0}]", args.FileName);
  1103. if (FileTransferred != null)
  1104. {
  1105. FileTransferred(this, args);
  1106. }
  1107. }
  1108. internal void RaiseFailed(SessionRemoteException e)
  1109. {
  1110. Logger.WriteLine("Failed: [{0}]", e);
  1111. if (Failed != null)
  1112. {
  1113. Failed(this, new FailedEventArgs { Error = e });
  1114. }
  1115. foreach (OperationResultBase operationResult in _operationResults)
  1116. {
  1117. operationResult.AddFailure(e);
  1118. }
  1119. }
  1120. private void CheckNotDisposed()
  1121. {
  1122. if (_disposed)
  1123. {
  1124. throw new InvalidOperationException("Object is disposed");
  1125. }
  1126. if (_aborted)
  1127. {
  1128. throw new InvalidOperationException("Session was aborted");
  1129. }
  1130. }
  1131. private void CheckOpened()
  1132. {
  1133. if (!Opened)
  1134. {
  1135. throw new InvalidOperationException("Session is not opened");
  1136. }
  1137. }
  1138. private void CheckNotOpened()
  1139. {
  1140. if (Opened)
  1141. {
  1142. throw new InvalidOperationException("Session is already opened");
  1143. }
  1144. }
  1145. private void RaiseOutputDataReceived(string data)
  1146. {
  1147. Logger.WriteLine("Output: [{0}]", data);
  1148. if (OutputDataReceived != null)
  1149. {
  1150. OutputDataReceived(this, new OutputDataReceivedEventArgs(data));
  1151. }
  1152. }
  1153. internal void DispatchEvents(int interval)
  1154. {
  1155. DateTime start = DateTime.Now;
  1156. while (_eventsEvent.WaitOne(interval, false))
  1157. {
  1158. lock (_events)
  1159. {
  1160. foreach (Action action in _events)
  1161. {
  1162. action();
  1163. }
  1164. _events.Clear();
  1165. }
  1166. interval -= (int) (DateTime.Now - start).TotalMilliseconds;
  1167. if (interval < 0)
  1168. {
  1169. break;
  1170. }
  1171. start = DateTime.Now;
  1172. }
  1173. }
  1174. private IDisposable RegisterOperationResult(OperationResultBase operationResult)
  1175. {
  1176. _operationResults.Add(operationResult);
  1177. return new OperationResultGuard(this, operationResult);
  1178. }
  1179. internal void UnregisterOperationResult(OperationResultBase operationResult)
  1180. {
  1181. _operationResults.Remove(operationResult);
  1182. }
  1183. internal bool WantsProgress
  1184. {
  1185. get
  1186. {
  1187. return (_fileTransferProgress != null);
  1188. }
  1189. }
  1190. private IDisposable CreateProgressHandler()
  1191. {
  1192. using (Logger.CreateCallstack())
  1193. {
  1194. _progressHandling++;
  1195. return new ProgressHandler(this);
  1196. }
  1197. }
  1198. internal void DisableProgressHandling()
  1199. {
  1200. using (Logger.CreateCallstack())
  1201. {
  1202. if (_progressHandling <= 0)
  1203. {
  1204. throw new InvalidOperationException("Progress handling not enabled");
  1205. }
  1206. // make sure we process all pending progress events
  1207. DispatchEvents(0);
  1208. _progressHandling--;
  1209. }
  1210. }
  1211. internal void ProcessProgress(FileTransferProgressEventArgs args)
  1212. {
  1213. ScheduleEvent(() => Progress(args));
  1214. }
  1215. private void Progress(FileTransferProgressEventArgs args)
  1216. {
  1217. if ((_progressHandling >= 0) && WantsProgress)
  1218. {
  1219. _fileTransferProgress(this, args);
  1220. }
  1221. }
  1222. private void SetupTempPath()
  1223. {
  1224. using (Logger.CreateCallstack())
  1225. {
  1226. if (!string.IsNullOrEmpty(_xmlLogPath))
  1227. {
  1228. bool exists = File.Exists(_xmlLogPath);
  1229. Logger.WriteLine("Configured temporary file: {0} - Exists [{1}]", _xmlLogPath, exists);
  1230. if (exists)
  1231. {
  1232. throw new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Configured temporary file {0} already exists", _xmlLogPath));
  1233. }
  1234. }
  1235. else
  1236. {
  1237. string path = Path.GetTempPath();
  1238. Logger.WriteLine("Temporary folder: {0}", path);
  1239. string process = Process.GetCurrentProcess().Id.ToString("X4", CultureInfo.InvariantCulture);
  1240. string instance = GetHashCode().ToString("X8", CultureInfo.InvariantCulture);
  1241. string filename;
  1242. bool exists;
  1243. do
  1244. {
  1245. string uniqueStr = (_logUnique > 0 ? "." + _logUnique.ToString(CultureInfo.InvariantCulture) : string.Empty);
  1246. ++_logUnique;
  1247. filename = Path.Combine(path, "wscp" + process + "." + instance + uniqueStr + ".tmp");
  1248. exists = File.Exists(filename);
  1249. Logger.WriteLine("Temporary file [{0}] - Exists [{1}]", filename, exists);
  1250. }
  1251. while (exists);
  1252. _xmlLogPath = filename;
  1253. }
  1254. }
  1255. }
  1256. private static string GetTypeLibKey(Type t)
  1257. {
  1258. return "CLSID\\{" + t.GUID.ToString().ToUpperInvariant() + "}\\TypeLib";
  1259. }
  1260. FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
  1261. {
  1262. using (Logger.CreateCallstack())
  1263. {
  1264. Logger.WriteLine("Name [{0}]", name);
  1265. FieldInfo result = GetType().GetField(name, bindingAttr);
  1266. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1267. return result;
  1268. }
  1269. }
  1270. FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
  1271. {
  1272. using (Logger.CreateCallstack())
  1273. {
  1274. FieldInfo[] result = GetType().GetFields(bindingAttr);
  1275. Logger.WriteLine("Fields [{0}]", result.Length);
  1276. return result;
  1277. }
  1278. }
  1279. MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
  1280. {
  1281. using (Logger.CreateCallstack())
  1282. {
  1283. Logger.WriteLine("Name [{0}]", name);
  1284. MemberInfo[] result = GetType().GetMember(name, bindingAttr);
  1285. Logger.WriteLine("Result [{0}]", result.Length);
  1286. return result;
  1287. }
  1288. }
  1289. MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
  1290. {
  1291. using (Logger.CreateCallstack())
  1292. {
  1293. MemberInfo[] result = GetType().GetMembers(bindingAttr);
  1294. Logger.WriteLine("Result [{0}]", result.Length);
  1295. return result;
  1296. }
  1297. }
  1298. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
  1299. {
  1300. using (Logger.CreateCallstack())
  1301. {
  1302. Logger.WriteLine("Name [{0}]", name);
  1303. MethodInfo result = GetType().GetMethod(name, bindingAttr);
  1304. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1305. return result;
  1306. }
  1307. }
  1308. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
  1309. {
  1310. using (Logger.CreateCallstack())
  1311. {
  1312. Logger.WriteLine("Name [{0}]", name);
  1313. MethodInfo result = GetType().GetMethod(name, bindingAttr, binder, types, modifiers);
  1314. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1315. return result;
  1316. }
  1317. }
  1318. MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
  1319. {
  1320. using (Logger.CreateCallstack())
  1321. {
  1322. MethodInfo[] result = GetType().GetMethods(bindingAttr);
  1323. Logger.WriteLine("Result [{0}]", result.Length);
  1324. return result;
  1325. }
  1326. }
  1327. PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
  1328. {
  1329. using (Logger.CreateCallstack())
  1330. {
  1331. PropertyInfo[] result = GetType().GetProperties(bindingAttr);
  1332. Logger.WriteLine("Result [{0}]", result.Length);
  1333. return result;
  1334. }
  1335. }
  1336. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
  1337. {
  1338. using (Logger.CreateCallstack())
  1339. {
  1340. Logger.WriteLine("Name [{0}]", name);
  1341. PropertyInfo result = GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
  1342. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1343. return result;
  1344. }
  1345. }
  1346. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
  1347. {
  1348. using (Logger.CreateCallstack())
  1349. {
  1350. Logger.WriteLine("Name [{0}]", name);
  1351. PropertyInfo result = GetType().GetProperty(name, bindingAttr);
  1352. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1353. return result;
  1354. }
  1355. }
  1356. object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  1357. {
  1358. using (Logger.CreateCallstack())
  1359. {
  1360. object result;
  1361. try
  1362. {
  1363. if (Logger.Logging)
  1364. {
  1365. Logger.WriteLine("Name [{0}]", name);
  1366. Logger.WriteLine("BindingFlags [{0}]", invokeAttr);
  1367. Logger.WriteLine("Binder [{0}]", binder);
  1368. Logger.WriteLine("Target [{0}]", target);
  1369. if (args != null)
  1370. {
  1371. Logger.WriteLine("Args [{0}] [{1}]", args.Length, modifiers != null ? modifiers.Length.ToString(CultureInfo.InvariantCulture) : "null");
  1372. for (int i = 0; i < args.Length; ++i)
  1373. {
  1374. Logger.WriteLine("Arg [{0}] [{1}] [{1}] [{2}]", i, args[i], (args[i] != null ? args[i].GetType().ToString() : "null"), (modifiers != null ? modifiers[i].ToString() : "null"));
  1375. }
  1376. }
  1377. Logger.WriteLine("Culture [{0}]", culture);
  1378. if (namedParameters != null)
  1379. {
  1380. foreach (string namedParameter in namedParameters)
  1381. {
  1382. Logger.WriteLine("NamedParameter [{0}]", namedParameter);
  1383. }
  1384. }
  1385. }
  1386. Type type = target.GetType();
  1387. // RuntimeType.InvokeMember below calls into Binder.BindToMethod (Binder is OleAutBinder)
  1388. // that fails to match method, if integer value is provided to enum argument
  1389. // (SynchronizeDirectories with its SynchronizationMode and SynchronizationCriteria).
  1390. // This does not happen if we do not implement IReflect, though no idea why.
  1391. // So as a workaround we check, if the method has no overloads (what is always true for Session),
  1392. // and call the only instance directly.
  1393. // Calling MethodInfo.Invoke with int values for enum arguments works.
  1394. // Only as a fallback, we call InvokeMember (what is currently actually used only when
  1395. // the method with given name does not exist at all)
  1396. MethodInfo method = null;
  1397. PropertyInfo property = null;
  1398. // would be way too difficult to implement the below involving named arguments
  1399. if (namedParameters == null)
  1400. {
  1401. try
  1402. {
  1403. BindingFlags bindingFlags = invokeAttr | BindingFlags.Instance | BindingFlags.Public;
  1404. method = type.GetMethod(name, bindingFlags);
  1405. if (method != null)
  1406. {
  1407. // MethodInfo.Invoke does not fill-in optional arguments (contrary to RuntimeType.InvokeMember)
  1408. ParameterInfo[] parameters = method.GetParameters();
  1409. if (args.Length < parameters.Length)
  1410. {
  1411. Logger.WriteLine("Provided less parameters [{0}] than defined [{1}]", args.Length, parameters.Length);
  1412. object[] args2 = new object[parameters.Length];
  1413. for (int i = 0; i < parameters.Length; i++)
  1414. {
  1415. if (i < args.Length)
  1416. {
  1417. args2[i] = args[i];
  1418. }
  1419. else
  1420. {
  1421. if (!parameters[i].IsOptional)
  1422. {
  1423. Logger.WriteLine("Parameter [{0}] of [{1}] is not optional", i, method);
  1424. args2 = null;
  1425. break;
  1426. }
  1427. else
  1428. {
  1429. Logger.WriteLine("Adding default value [{0}] for optional parameter [{1}]", parameters[i].DefaultValue, i);
  1430. args2[i] = parameters[i].DefaultValue;
  1431. }
  1432. }
  1433. }
  1434. if (args2 != null)
  1435. {
  1436. args = args2;
  1437. }
  1438. }
  1439. }
  1440. else if (args.Length == 1) // sanity check
  1441. {
  1442. property = type.GetProperty(name, bindingFlags);
  1443. }
  1444. }
  1445. catch (AmbiguousMatchException e)
  1446. {
  1447. Logger.WriteLine("Unexpected ambiguous match [{0}]", e.Message);
  1448. }
  1449. }
  1450. if (method != null)
  1451. {
  1452. Logger.WriteLine("Invoking unambiguous method [{0}]", method);
  1453. result = method.Invoke(target, invokeAttr, binder, args, culture);
  1454. }
  1455. else if (property != null)
  1456. {
  1457. Logger.WriteLine("Setting unambiguous property [{0}]", property);
  1458. property.SetValue(target, args[0], invokeAttr, binder, null, culture);
  1459. result = null;
  1460. }
  1461. else
  1462. {
  1463. Logger.WriteLine("Invoking ambiguous/non-existing method 2 [{0}]", name);
  1464. result = type.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  1465. }
  1466. Logger.WriteLine("Result [{0}] [{1}]", result, (result != null ? result.GetType().ToString() : "null"));
  1467. }
  1468. catch (Exception e)
  1469. {
  1470. Logger.WriteLine("Error [{0}]", e);
  1471. throw;
  1472. }
  1473. return result;
  1474. }
  1475. }
  1476. Type IReflect.UnderlyingSystemType
  1477. {
  1478. get { return GetType(); }
  1479. }
  1480. internal const string Namespace = "http://winscp.net/schema/session/1.0";
  1481. internal Logger Logger { get; private set; }
  1482. internal bool GuardProcessWithJobInternal { get { return _guardProcessWithJob; } set { CheckNotOpened(); _guardProcessWithJob = value; } }
  1483. internal bool TestHandlesClosedInternal { get; set; }
  1484. internal Dictionary<string, string> RawConfiguration { get; private set; }
  1485. private ExeSessionProcess _process;
  1486. private DateTime _lastOutput;
  1487. private ElementLogReader _reader;
  1488. private SessionLogReader _logReader;
  1489. private readonly IList<OperationResultBase> _operationResults;
  1490. private delegate void Action();
  1491. private readonly IList<Action> _events;
  1492. private AutoResetEvent _eventsEvent;
  1493. private bool _disposed;
  1494. private string _executablePath;
  1495. private string _additionalExecutableArguments;
  1496. private bool _defaultConfiguration;
  1497. private bool _disableVersionCheck;
  1498. private string _iniFilePath;
  1499. private TimeSpan _reconnectTime;
  1500. private string _sessionLogPath;
  1501. private bool _aborted;
  1502. private int _logUnique;
  1503. private string _xmlLogPath;
  1504. private FileTransferProgressEventHandler _fileTransferProgress;
  1505. private int _progressHandling;
  1506. private bool _guardProcessWithJob;
  1507. private string _homePath;
  1508. }
  1509. }