Session.cs 91 KB

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