Session.cs 81 KB

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