Session.cs 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  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.SshHostKey or SessionOptions.GiveUpSecurityAndAcceptAnySshHostKey is set, but SessionOptions.Protocol is not 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.HostKey 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 not 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. GotOutput();
  1070. ScheduleEvent(() => RaiseOutputDataReceived(e.Data));
  1071. }
  1072. private void ScheduleEvent(Action action)
  1073. {
  1074. lock (_events)
  1075. {
  1076. _events.Add(action);
  1077. _eventsEvent.Set();
  1078. }
  1079. }
  1080. internal void CheckForTimeout(string additional = null)
  1081. {
  1082. if (DateTime.Now - _lastOutput > Timeout)
  1083. {
  1084. string message = "Timeout waiting for WinSCP to respond";
  1085. if (additional != null)
  1086. {
  1087. message += " - " + additional;
  1088. }
  1089. throw new TimeoutException(message);
  1090. }
  1091. if (_aborted)
  1092. {
  1093. throw new SessionLocalException(this, "Aborted.");
  1094. }
  1095. }
  1096. private void RaiseFileTransferredEvent(TransferEventArgs args)
  1097. {
  1098. Logger.WriteLine("FileTransferredEvent: [{0}]", args.FileName);
  1099. if (FileTransferred != null)
  1100. {
  1101. FileTransferred(this, args);
  1102. }
  1103. }
  1104. internal void RaiseFailed(SessionRemoteException e)
  1105. {
  1106. Logger.WriteLine("Failed: [{0}]", e);
  1107. if (Failed != null)
  1108. {
  1109. Failed(this, new FailedEventArgs { Error = e });
  1110. }
  1111. foreach (OperationResultBase operationResult in _operationResults)
  1112. {
  1113. operationResult.AddFailure(e);
  1114. }
  1115. }
  1116. private void CheckNotDisposed()
  1117. {
  1118. if (_disposed)
  1119. {
  1120. throw new InvalidOperationException("Object is disposed");
  1121. }
  1122. if (_aborted)
  1123. {
  1124. throw new InvalidOperationException("Session was aborted");
  1125. }
  1126. }
  1127. private void CheckOpened()
  1128. {
  1129. if (!Opened)
  1130. {
  1131. throw new InvalidOperationException("Session is not opened");
  1132. }
  1133. }
  1134. private void CheckNotOpened()
  1135. {
  1136. if (Opened)
  1137. {
  1138. throw new InvalidOperationException("Session is already opened");
  1139. }
  1140. }
  1141. private void RaiseOutputDataReceived(string data)
  1142. {
  1143. Logger.WriteLine("Output: [{0}]", data);
  1144. if (OutputDataReceived != null)
  1145. {
  1146. OutputDataReceived(this, new OutputDataReceivedEventArgs(data));
  1147. }
  1148. }
  1149. internal void DispatchEvents(int interval)
  1150. {
  1151. DateTime start = DateTime.Now;
  1152. while (_eventsEvent.WaitOne(interval, false))
  1153. {
  1154. lock (_events)
  1155. {
  1156. foreach (Action action in _events)
  1157. {
  1158. action();
  1159. }
  1160. _events.Clear();
  1161. }
  1162. interval -= (int) (DateTime.Now - start).TotalMilliseconds;
  1163. if (interval < 0)
  1164. {
  1165. break;
  1166. }
  1167. start = DateTime.Now;
  1168. }
  1169. }
  1170. private IDisposable RegisterOperationResult(OperationResultBase operationResult)
  1171. {
  1172. _operationResults.Add(operationResult);
  1173. return new OperationResultGuard(this, operationResult);
  1174. }
  1175. internal void UnregisterOperationResult(OperationResultBase operationResult)
  1176. {
  1177. _operationResults.Remove(operationResult);
  1178. }
  1179. internal bool WantsProgress
  1180. {
  1181. get
  1182. {
  1183. return (_fileTransferProgress != null);
  1184. }
  1185. }
  1186. private IDisposable CreateProgressHandler()
  1187. {
  1188. using (Logger.CreateCallstack())
  1189. {
  1190. _progressHandling++;
  1191. return new ProgressHandler(this);
  1192. }
  1193. }
  1194. internal void DisableProgressHandling()
  1195. {
  1196. using (Logger.CreateCallstack())
  1197. {
  1198. if (_progressHandling <= 0)
  1199. {
  1200. throw new InvalidOperationException("Progress handling not enabled");
  1201. }
  1202. // make sure we process all pending progress events
  1203. DispatchEvents(0);
  1204. _progressHandling--;
  1205. }
  1206. }
  1207. internal void ProcessProgress(FileTransferProgressEventArgs args)
  1208. {
  1209. ScheduleEvent(() => Progress(args));
  1210. }
  1211. private void Progress(FileTransferProgressEventArgs args)
  1212. {
  1213. if ((_progressHandling >= 0) && WantsProgress)
  1214. {
  1215. _fileTransferProgress(this, args);
  1216. }
  1217. }
  1218. private void SetupTempPath()
  1219. {
  1220. using (Logger.CreateCallstack())
  1221. {
  1222. if (!string.IsNullOrEmpty(_xmlLogPath))
  1223. {
  1224. bool exists = File.Exists(_xmlLogPath);
  1225. Logger.WriteLine("Configured temporary file: {0} - Exists [{1}]", _xmlLogPath, exists);
  1226. if (exists)
  1227. {
  1228. throw new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Configured temporary file {0} already exists", _xmlLogPath));
  1229. }
  1230. }
  1231. else
  1232. {
  1233. string path = Path.GetTempPath();
  1234. Logger.WriteLine("Temporary folder: {0}", path);
  1235. string process = Process.GetCurrentProcess().Id.ToString("X4", CultureInfo.InvariantCulture);
  1236. string instance = GetHashCode().ToString("X8", CultureInfo.InvariantCulture);
  1237. string filename;
  1238. bool exists;
  1239. do
  1240. {
  1241. string uniqueStr = (_logUnique > 0 ? "." + _logUnique.ToString(CultureInfo.InvariantCulture) : string.Empty);
  1242. ++_logUnique;
  1243. filename = Path.Combine(path, "wscp" + process + "." + instance + uniqueStr + ".tmp");
  1244. exists = File.Exists(filename);
  1245. Logger.WriteLine("Temporary file [{0}] - Exists [{1}]", filename, exists);
  1246. }
  1247. while (exists);
  1248. _xmlLogPath = filename;
  1249. }
  1250. }
  1251. }
  1252. private static string GetTypeLibKey(Type t)
  1253. {
  1254. return "CLSID\\{" + t.GUID.ToString().ToUpperInvariant() + "}\\TypeLib";
  1255. }
  1256. FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
  1257. {
  1258. using (Logger.CreateCallstack())
  1259. {
  1260. Logger.WriteLine("Name [{0}]", name);
  1261. FieldInfo result = GetType().GetField(name, bindingAttr);
  1262. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1263. return result;
  1264. }
  1265. }
  1266. FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
  1267. {
  1268. using (Logger.CreateCallstack())
  1269. {
  1270. FieldInfo[] result = GetType().GetFields(bindingAttr);
  1271. Logger.WriteLine("Fields [{0}]", result.Length);
  1272. return result;
  1273. }
  1274. }
  1275. MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
  1276. {
  1277. using (Logger.CreateCallstack())
  1278. {
  1279. Logger.WriteLine("Name [{0}]", name);
  1280. MemberInfo[] result = GetType().GetMember(name, bindingAttr);
  1281. Logger.WriteLine("Result [{0}]", result.Length);
  1282. return result;
  1283. }
  1284. }
  1285. MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
  1286. {
  1287. using (Logger.CreateCallstack())
  1288. {
  1289. MemberInfo[] result = GetType().GetMembers(bindingAttr);
  1290. Logger.WriteLine("Result [{0}]", result.Length);
  1291. return result;
  1292. }
  1293. }
  1294. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
  1295. {
  1296. using (Logger.CreateCallstack())
  1297. {
  1298. Logger.WriteLine("Name [{0}]", name);
  1299. MethodInfo result = GetType().GetMethod(name, bindingAttr);
  1300. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1301. return result;
  1302. }
  1303. }
  1304. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
  1305. {
  1306. using (Logger.CreateCallstack())
  1307. {
  1308. Logger.WriteLine("Name [{0}]", name);
  1309. MethodInfo result = GetType().GetMethod(name, bindingAttr, binder, types, modifiers);
  1310. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1311. return result;
  1312. }
  1313. }
  1314. MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
  1315. {
  1316. using (Logger.CreateCallstack())
  1317. {
  1318. MethodInfo[] result = GetType().GetMethods(bindingAttr);
  1319. Logger.WriteLine("Result [{0}]", result.Length);
  1320. return result;
  1321. }
  1322. }
  1323. PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
  1324. {
  1325. using (Logger.CreateCallstack())
  1326. {
  1327. PropertyInfo[] result = GetType().GetProperties(bindingAttr);
  1328. Logger.WriteLine("Result [{0}]", result.Length);
  1329. return result;
  1330. }
  1331. }
  1332. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
  1333. {
  1334. using (Logger.CreateCallstack())
  1335. {
  1336. Logger.WriteLine("Name [{0}]", name);
  1337. PropertyInfo result = GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
  1338. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1339. return result;
  1340. }
  1341. }
  1342. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
  1343. {
  1344. using (Logger.CreateCallstack())
  1345. {
  1346. Logger.WriteLine("Name [{0}]", name);
  1347. PropertyInfo result = GetType().GetProperty(name, bindingAttr);
  1348. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1349. return result;
  1350. }
  1351. }
  1352. object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  1353. {
  1354. using (Logger.CreateCallstack())
  1355. {
  1356. object result;
  1357. try
  1358. {
  1359. if (Logger.Logging)
  1360. {
  1361. Logger.WriteLine("Name [{0}]", name);
  1362. Logger.WriteLine("BindingFlags [{0}]", invokeAttr);
  1363. Logger.WriteLine("Binder [{0}]", binder);
  1364. Logger.WriteLine("Target [{0}]", target);
  1365. if (args != null)
  1366. {
  1367. Logger.WriteLine("Args [{0}] [{1}]", args.Length, modifiers != null ? modifiers.Length.ToString(CultureInfo.InvariantCulture) : "null");
  1368. for (int i = 0; i < args.Length; ++i)
  1369. {
  1370. Logger.WriteLine("Arg [{0}] [{1}] [{1}] [{2}]", i, args[i], (args[i] != null ? args[i].GetType().ToString() : "null"), (modifiers != null ? modifiers[i].ToString() : "null"));
  1371. }
  1372. }
  1373. Logger.WriteLine("Culture [{0}]", culture);
  1374. if (namedParameters != null)
  1375. {
  1376. foreach (string namedParameter in namedParameters)
  1377. {
  1378. Logger.WriteLine("NamedParameter [{0}]", namedParameter);
  1379. }
  1380. }
  1381. }
  1382. Type type = target.GetType();
  1383. // RuntimeType.InvokeMember below calls into Binder.BindToMethod (Binder is OleAutBinder)
  1384. // that fails to match method, if integer value is provided to enum argument
  1385. // (SynchronizeDirectories with its SynchronizationMode and SynchronizationCriteria).
  1386. // This does not happen if we do not implement IReflect, though no idea why.
  1387. // So as a workaround we check, if the method has no overloads (what is always true for Session),
  1388. // and call the only instance directly.
  1389. // Calling MethodInfo.Invoke with int values for enum arguments works.
  1390. // Only as a fallback, we call InvokeMember (what is currently actually used only when
  1391. // the method with given name does not exist at all)
  1392. MethodInfo method = null;
  1393. PropertyInfo property = null;
  1394. // would be way too difficult to implement the below involving named arguments
  1395. if (namedParameters == null)
  1396. {
  1397. try
  1398. {
  1399. BindingFlags bindingFlags = invokeAttr | BindingFlags.Instance | BindingFlags.Public;
  1400. method = type.GetMethod(name, bindingFlags);
  1401. if (method != null)
  1402. {
  1403. // MethodInfo.Invoke does not fill-in optional arguments (contrary to RuntimeType.InvokeMember)
  1404. ParameterInfo[] parameters = method.GetParameters();
  1405. if (args.Length < parameters.Length)
  1406. {
  1407. Logger.WriteLine("Provided less parameters [{0}] than defined [{1}]", args.Length, parameters.Length);
  1408. object[] args2 = new object[parameters.Length];
  1409. for (int i = 0; i < parameters.Length; i++)
  1410. {
  1411. if (i < args.Length)
  1412. {
  1413. args2[i] = args[i];
  1414. }
  1415. else
  1416. {
  1417. if (!parameters[i].IsOptional)
  1418. {
  1419. Logger.WriteLine("Parameter [{0}] of [{1}] is not optional", i, method);
  1420. args2 = null;
  1421. break;
  1422. }
  1423. else
  1424. {
  1425. Logger.WriteLine("Adding default value [{0}] for optional parameter [{1}]", parameters[i].DefaultValue, i);
  1426. args2[i] = parameters[i].DefaultValue;
  1427. }
  1428. }
  1429. }
  1430. if (args2 != null)
  1431. {
  1432. args = args2;
  1433. }
  1434. }
  1435. }
  1436. else if (args.Length == 1) // sanity check
  1437. {
  1438. property = type.GetProperty(name, bindingFlags);
  1439. }
  1440. }
  1441. catch (AmbiguousMatchException e)
  1442. {
  1443. Logger.WriteLine("Unexpected ambiguous match [{0}]", e.Message);
  1444. }
  1445. }
  1446. if (method != null)
  1447. {
  1448. Logger.WriteLine("Invoking unambiguous method [{0}]", method);
  1449. result = method.Invoke(target, invokeAttr, binder, args, culture);
  1450. }
  1451. else if (property != null)
  1452. {
  1453. Logger.WriteLine("Setting unambiguous property [{0}]", property);
  1454. property.SetValue(target, args[0], invokeAttr, binder, null, culture);
  1455. result = null;
  1456. }
  1457. else
  1458. {
  1459. Logger.WriteLine("Invoking ambiguous/non-existing method 2 [{0}]", name);
  1460. result = type.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  1461. }
  1462. Logger.WriteLine("Result [{0}] [{1}]", result, (result != null ? result.GetType().ToString() : "null"));
  1463. }
  1464. catch (Exception e)
  1465. {
  1466. Logger.WriteLine("Error [{0}]", e);
  1467. throw;
  1468. }
  1469. return result;
  1470. }
  1471. }
  1472. Type IReflect.UnderlyingSystemType
  1473. {
  1474. get { return GetType(); }
  1475. }
  1476. internal const string Namespace = "http://winscp.net/schema/session/1.0";
  1477. internal Logger Logger { get; private set; }
  1478. internal bool GuardProcessWithJobInternal { get { return _guardProcessWithJob; } set { CheckNotOpened(); _guardProcessWithJob = value; } }
  1479. internal bool TestHandlesClosedInternal { get; set; }
  1480. internal Dictionary<string, string> RawConfiguration { get; private set; }
  1481. private ExeSessionProcess _process;
  1482. private DateTime _lastOutput;
  1483. private ElementLogReader _reader;
  1484. private SessionLogReader _logReader;
  1485. private readonly IList<OperationResultBase> _operationResults;
  1486. private delegate void Action();
  1487. private readonly IList<Action> _events;
  1488. private AutoResetEvent _eventsEvent;
  1489. private bool _disposed;
  1490. private string _executablePath;
  1491. private string _additionalExecutableArguments;
  1492. private bool _defaultConfiguration;
  1493. private bool _disableVersionCheck;
  1494. private string _iniFilePath;
  1495. private TimeSpan _reconnectTime;
  1496. private string _sessionLogPath;
  1497. private bool _aborted;
  1498. private int _logUnique;
  1499. private string _xmlLogPath;
  1500. private FileTransferProgressEventHandler _fileTransferProgress;
  1501. private int _progressHandling;
  1502. private bool _guardProcessWithJob;
  1503. private string _homePath;
  1504. }
  1505. }