Session.cs 116 KB

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