1
0

Session.cs 99 KB

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