Session.cs 86 KB

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