Session.cs 78 KB

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