Session.cs 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810
  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 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. using (Logger.CreateCallstack())
  910. {
  911. try
  912. {
  913. // This can throw
  914. progressHandler?.Dispose();
  915. }
  916. finally
  917. {
  918. try
  919. {
  920. groupReader?.Dispose();
  921. }
  922. finally
  923. {
  924. _process.StdOut = null;
  925. // Only after disposing the group reader, so when called from onGetEndWithExit, the Check() has all failures.
  926. operationResultGuard?.Dispose();
  927. }
  928. }
  929. }
  930. }
  931. void onGetEndWithExit()
  932. {
  933. using (Logger.CreateCallstack())
  934. {
  935. Logger.WriteLine("Closing download stream");
  936. try
  937. {
  938. onGetEnd();
  939. }
  940. finally
  941. {
  942. Logger.Lock.Exit();
  943. Logger.WriteLine("Closed download stream");
  944. result.Check();
  945. }
  946. }
  947. }
  948. try
  949. {
  950. StartGetCommand(remotePath, "-", false, options, additionalParams);
  951. groupReader = _reader.WaitForGroupAndCreateLogReader();
  952. operationResultGuard = RegisterOperationResult(result);
  953. progressHandler = CreateProgressHandler();
  954. if (_throwStdOut)
  955. {
  956. throw Logger.WriteException(new InvalidOperationException());
  957. }
  958. _throwStdOut = true;
  959. bool downloadFound;
  960. try
  961. {
  962. // Not using WaitForNonEmptyElement only to allow throwing better exception message below.
  963. // Not using ThrowFailures as we need to return the stream, if there's <download>,
  964. // even if there's a <failure> as well.
  965. downloadFound = groupReader.TryWaitForNonEmptyElement(TransferEventArgs.DownloadTag, 0);
  966. }
  967. catch (StdOutException)
  968. {
  969. downloadFound = true;
  970. }
  971. finally
  972. {
  973. _throwStdOut = false;
  974. }
  975. if (downloadFound)
  976. {
  977. callstackAndLock.DisarmLock();
  978. stream.OnDispose = onGetEndWithExit;
  979. return stream;
  980. }
  981. else
  982. {
  983. // First throw any specific error from <failure>
  984. result.Check();
  985. // And only then fallback to the generic one.
  986. // See also the comment in GetOnlyFileOperation.
  987. throw Logger.WriteException(new FileNotFoundException("File not found"));
  988. }
  989. }
  990. catch
  991. {
  992. onGetEnd();
  993. throw;
  994. }
  995. }
  996. }
  997. public RemovalOperationResult RemoveFiles(string path)
  998. {
  999. using (Logger.CreateCallstackAndLock())
  1000. {
  1001. return DoRemoveFiles(path, string.Empty);
  1002. }
  1003. }
  1004. private RemovalOperationResult DoRemoveFiles(string path, string additionalParams)
  1005. {
  1006. using (Logger.CreateCallstack())
  1007. {
  1008. CheckOpened();
  1009. WriteCommand(string.Format(CultureInfo.InvariantCulture, "rm {0} -- \"{1}\"", additionalParams, Tools.ArgumentEscape(path)));
  1010. RemovalOperationResult result = new RemovalOperationResult();
  1011. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1012. using (RegisterOperationResult(result))
  1013. {
  1014. while (groupReader.Read(0))
  1015. {
  1016. if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  1017. {
  1018. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  1019. }
  1020. }
  1021. }
  1022. return result;
  1023. }
  1024. }
  1025. public RemovalEventArgs RemoveFile(string path)
  1026. {
  1027. using (Logger.CreateCallstackAndLock())
  1028. {
  1029. RemovalOperationResult operationResult = RemoveEntry(path, "-onlyfile");
  1030. return GetOnlyFileOperation(operationResult.Removals);
  1031. }
  1032. }
  1033. internal RemovalOperationResult RemoveEntry(string path, string additionalParams = null)
  1034. {
  1035. using (Logger.CreateCallstack())
  1036. {
  1037. if (string.IsNullOrEmpty(path))
  1038. {
  1039. throw Logger.WriteException(new ArgumentException("File to path cannot be empty", nameof(path)));
  1040. }
  1041. string remoteDirectory = RemotePath.GetDirectoryName(path);
  1042. string filemask = RemotePath.EscapeFileMask(RemotePath.GetFileName(path));
  1043. if (string.IsNullOrEmpty(filemask))
  1044. {
  1045. throw Logger.WriteException(new ArgumentException("File name cannot be empty", nameof(path)));
  1046. }
  1047. path = RemotePath.Combine(remoteDirectory, filemask);
  1048. RemovalOperationResult operationResult = DoRemoveFiles(path, additionalParams ?? string.Empty);
  1049. operationResult.Check();
  1050. return operationResult;
  1051. }
  1052. }
  1053. public SynchronizationResult SynchronizeDirectories(
  1054. SynchronizationMode mode, string localPath, string remotePath,
  1055. bool removeFiles, bool mirror = false, SynchronizationCriteria criteria = SynchronizationCriteria.Time,
  1056. TransferOptions options = null)
  1057. {
  1058. using (Logger.CreateCallstackAndLock())
  1059. {
  1060. DoSynchronizeDirectories(mode, localPath, remotePath, removeFiles, mirror, criteria, options, string.Empty);
  1061. return ReadSynchronizeDirectories();
  1062. }
  1063. }
  1064. private void DoSynchronizeDirectories(
  1065. SynchronizationMode mode, string localPath, string remotePath, bool removeFiles, bool mirror,
  1066. SynchronizationCriteria criteria, TransferOptions options, string additionalParameters)
  1067. {
  1068. if (options == null)
  1069. {
  1070. options = new TransferOptions();
  1071. }
  1072. CheckOpened();
  1073. if (removeFiles && (mode == SynchronizationMode.Both))
  1074. {
  1075. throw Logger.WriteException(new ArgumentException("Cannot delete files in synchronization mode Both"));
  1076. }
  1077. if (mirror && (mode == SynchronizationMode.Both))
  1078. {
  1079. throw Logger.WriteException(new ArgumentException("Cannot mirror files in synchronization mode Both"));
  1080. }
  1081. if ((criteria != SynchronizationCriteria.Time) && (mode == SynchronizationMode.Both))
  1082. {
  1083. throw Logger.WriteException(new ArgumentException("Only Time criteria is allowed in synchronization mode Both"));
  1084. }
  1085. string modeName;
  1086. switch (mode)
  1087. {
  1088. case SynchronizationMode.Local:
  1089. modeName = "local";
  1090. break;
  1091. case SynchronizationMode.Remote:
  1092. modeName = "remote";
  1093. break;
  1094. case SynchronizationMode.Both:
  1095. modeName = "both";
  1096. break;
  1097. default:
  1098. throw Logger.WriteException(new ArgumentOutOfRangeException(nameof(mode)));
  1099. }
  1100. string criteriaName;
  1101. switch (criteria)
  1102. {
  1103. case SynchronizationCriteria.None:
  1104. criteriaName = "none";
  1105. break;
  1106. case SynchronizationCriteria.Time:
  1107. criteriaName = "time";
  1108. break;
  1109. case SynchronizationCriteria.Size:
  1110. criteriaName = "size";
  1111. break;
  1112. case SynchronizationCriteria.Either:
  1113. criteriaName = "either";
  1114. break;
  1115. default:
  1116. throw Logger.WriteException(new ArgumentOutOfRangeException(nameof(criteria)));
  1117. }
  1118. WriteCommand(
  1119. string.Format(CultureInfo.InvariantCulture,
  1120. "synchronize {0} {1} {2} {3} -criteria=\"{4}\" {5} -- \"{6}\" \"{7}\"",
  1121. modeName,
  1122. BooleanSwitch(removeFiles, "delete"),
  1123. BooleanSwitch(mirror, "mirror"),
  1124. options.ToSwitches(),
  1125. criteriaName,
  1126. additionalParameters,
  1127. Tools.ArgumentEscape(localPath), Tools.ArgumentEscape(remotePath)));
  1128. }
  1129. private SynchronizationResult ReadSynchronizeDirectories()
  1130. {
  1131. using (Logger.CreateCallstack())
  1132. {
  1133. SynchronizationResult result = new SynchronizationResult();
  1134. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1135. using (RegisterOperationResult(result))
  1136. using (CreateProgressHandler())
  1137. {
  1138. TransferEventArgs transfer = null;
  1139. bool mkdir = false;
  1140. while (groupReader.Read(0))
  1141. {
  1142. ProgressSide? newSide = null;
  1143. if (groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag))
  1144. {
  1145. newSide = ProgressSide.Local;
  1146. }
  1147. else if (groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
  1148. {
  1149. newSide = ProgressSide.Remote;
  1150. }
  1151. if (newSide.HasValue)
  1152. {
  1153. AddSynchronizationTransfer(result, transfer);
  1154. transfer = TransferEventArgs.Read(newSide.Value, groupReader);
  1155. mkdir = false;
  1156. }
  1157. else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  1158. {
  1159. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  1160. }
  1161. else if (groupReader.IsNonEmptyElement(TransferEventArgs.MkDirTag))
  1162. {
  1163. AddSynchronizationTransfer(result, transfer);
  1164. transfer = null;
  1165. mkdir = true;
  1166. // For now, silently ignoring results (even errors)
  1167. // of mkdir operation, including future chmod/touch
  1168. }
  1169. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  1170. {
  1171. if (!mkdir)
  1172. {
  1173. if (transfer == null)
  1174. {
  1175. throw Logger.WriteException(new InvalidOperationException("Tag chmod before tag download"));
  1176. }
  1177. transfer.Chmod = ChmodEventArgs.Read(groupReader);
  1178. }
  1179. }
  1180. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  1181. {
  1182. if (!mkdir)
  1183. {
  1184. if (transfer == null)
  1185. {
  1186. throw Logger.WriteException(new InvalidOperationException("Tag touch before tag download"));
  1187. }
  1188. transfer.Touch = TouchEventArgs.Read(groupReader);
  1189. }
  1190. }
  1191. }
  1192. AddSynchronizationTransfer(result, transfer);
  1193. }
  1194. return result;
  1195. }
  1196. }
  1197. public ComparisonDifferenceCollection CompareDirectories(
  1198. SynchronizationMode mode, string localPath, string remotePath,
  1199. bool removeFiles, bool mirror = false, SynchronizationCriteria criteria = SynchronizationCriteria.Time,
  1200. TransferOptions options = null)
  1201. {
  1202. using (Logger.CreateCallstackAndLock())
  1203. {
  1204. DoSynchronizeDirectories(mode, localPath, remotePath, removeFiles, mirror, criteria, options, "-preview");
  1205. return ReadCompareDirectories(localPath, remotePath);
  1206. }
  1207. }
  1208. private ComparisonDifferenceCollection ReadCompareDirectories(string localPath, string remotePath)
  1209. {
  1210. using (Logger.CreateCallstack())
  1211. {
  1212. ComparisonDifferenceCollection result = new ComparisonDifferenceCollection();
  1213. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1214. {
  1215. while (groupReader.TryWaitForNonEmptyElement("difference", LogReadFlags.ThrowFailures))
  1216. {
  1217. using (ElementLogReader differenceReader = groupReader.CreateLogReader())
  1218. {
  1219. ComparisonDifference difference = new ComparisonDifference(localPath, remotePath);
  1220. ComparisonFileInfo current = null;
  1221. while (differenceReader.Read(0))
  1222. {
  1223. if (differenceReader.GetEmptyElementValue("action", out string actionName))
  1224. {
  1225. if ((difference.Local != null) || (difference.Remote != null))
  1226. {
  1227. throw Logger.WriteException(new InvalidOperationException("Tag action after filename"));
  1228. }
  1229. if (actionName.Equals("uploadnew", StringComparison.OrdinalIgnoreCase))
  1230. {
  1231. difference.Action = SynchronizationAction.UploadNew;
  1232. difference.Local = new ComparisonFileInfo();
  1233. }
  1234. else if (actionName.Equals("downloadnew", StringComparison.OrdinalIgnoreCase))
  1235. {
  1236. difference.Action = SynchronizationAction.DownloadNew;
  1237. difference.Remote = new ComparisonFileInfo();
  1238. }
  1239. else if (actionName.Equals("uploadupdate", StringComparison.OrdinalIgnoreCase))
  1240. {
  1241. difference.Action = SynchronizationAction.UploadUpdate;
  1242. difference.Local = new ComparisonFileInfo();
  1243. difference.Remote = new ComparisonFileInfo();
  1244. }
  1245. else if (actionName.Equals("downloadupdate", StringComparison.OrdinalIgnoreCase))
  1246. {
  1247. difference.Action = SynchronizationAction.DownloadUpdate;
  1248. difference.Remote = new ComparisonFileInfo();
  1249. difference.Local = new ComparisonFileInfo();
  1250. }
  1251. else if (actionName.Equals("deleteremote", StringComparison.OrdinalIgnoreCase))
  1252. {
  1253. difference.Action = SynchronizationAction.DeleteRemote;
  1254. difference.Remote = new ComparisonFileInfo();
  1255. }
  1256. else if (actionName.Equals("deletelocal", StringComparison.OrdinalIgnoreCase))
  1257. {
  1258. difference.Action = SynchronizationAction.DeleteLocal;
  1259. difference.Local = new ComparisonFileInfo();
  1260. }
  1261. else
  1262. {
  1263. throw Logger.WriteException(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Unknown synchronization action \"{0}\"", actionName)));
  1264. }
  1265. }
  1266. else if (differenceReader.GetEmptyElementValue("type", out string fileType))
  1267. {
  1268. difference.IsDirectory = (fileType.Length == 1) && RemoteFileInfo.IsDirectoryFileType(fileType[0]);
  1269. }
  1270. else if (differenceReader.GetEmptyElementValue("filename", out string value))
  1271. {
  1272. if (current == null)
  1273. {
  1274. current = difference.Local ?? difference.Remote;
  1275. }
  1276. else if (current == difference.Local)
  1277. {
  1278. current = difference.Remote;
  1279. }
  1280. if (current == null)
  1281. {
  1282. throw Logger.WriteException(new InvalidOperationException("Unexpected filename tag"));
  1283. }
  1284. current.FileName = value;
  1285. }
  1286. else if (differenceReader.GetEmptyElementValue("modification", out value))
  1287. {
  1288. if (current == null)
  1289. {
  1290. throw Logger.WriteException(new InvalidOperationException("Unexpected modification tag"));
  1291. }
  1292. current.LastWriteTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Local);
  1293. }
  1294. else if (differenceReader.GetEmptyElementValue("size", out value))
  1295. {
  1296. if (current == null)
  1297. {
  1298. throw Logger.WriteException(new InvalidOperationException("Unexpected size tag"));
  1299. }
  1300. current.Length = long.Parse(value, CultureInfo.InvariantCulture);
  1301. }
  1302. }
  1303. if (difference.Action == default)
  1304. {
  1305. throw Logger.WriteException(new InvalidOperationException("No action tag found"));
  1306. }
  1307. if (((difference.Local != null) && string.IsNullOrEmpty(difference.Local.FileName)) ||
  1308. ((difference.Remote != null) && string.IsNullOrEmpty(difference.Remote.FileName)))
  1309. {
  1310. throw Logger.WriteException(new InvalidOperationException("Missing file information"));
  1311. }
  1312. result.InternalAdd(difference);
  1313. }
  1314. }
  1315. }
  1316. return result;
  1317. }
  1318. }
  1319. public CommandExecutionResult ExecuteCommand(string command)
  1320. {
  1321. using (Logger.CreateCallstackAndLock())
  1322. {
  1323. CheckOpened();
  1324. WriteCommand(string.Format(CultureInfo.InvariantCulture, "call {0}", command));
  1325. CommandExecutionResult result = new CommandExecutionResult();
  1326. // registering before creating group reader, so that
  1327. // it is still registered, when group reader is read to the end in its .Dispose();
  1328. using (RegisterOperationResult(result))
  1329. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1330. using (ElementLogReader callReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("call", LogReadFlags.ThrowFailures))
  1331. {
  1332. while (callReader.Read(0))
  1333. {
  1334. if (callReader.GetEmptyElementValue("output", out string value))
  1335. {
  1336. result.Output = value;
  1337. }
  1338. if (callReader.GetEmptyElementValue("erroroutput", out value))
  1339. {
  1340. result.ErrorOutput = value;
  1341. }
  1342. if (callReader.GetEmptyElementValue("exitcode", out value))
  1343. {
  1344. result.ExitCode = int.Parse(value, CultureInfo.InvariantCulture);
  1345. }
  1346. }
  1347. }
  1348. return result;
  1349. }
  1350. }
  1351. public RemoteFileInfo GetFileInfo(string path)
  1352. {
  1353. using (Logger.CreateCallstackAndLock())
  1354. {
  1355. CheckOpened();
  1356. return DoGetFileInfo(path);
  1357. }
  1358. }
  1359. public bool FileExists(string path)
  1360. {
  1361. using (Logger.CreateCallstackAndLock())
  1362. {
  1363. CheckOpened();
  1364. try
  1365. {
  1366. _ignoreFailed = true;
  1367. try
  1368. {
  1369. DoGetFileInfo(path);
  1370. }
  1371. finally
  1372. {
  1373. _ignoreFailed = false;
  1374. }
  1375. return true;
  1376. }
  1377. catch (SessionRemoteException)
  1378. {
  1379. return false;
  1380. }
  1381. }
  1382. }
  1383. public byte[] CalculateFileChecksum(string algorithm, string path)
  1384. {
  1385. using (Logger.CreateCallstackAndLock())
  1386. {
  1387. WriteCommand(string.Format(CultureInfo.InvariantCulture, "checksum -- \"{0}\" \"{1}\"", Tools.ArgumentEscape(algorithm), Tools.ArgumentEscape(path)));
  1388. string hex = null;
  1389. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1390. using (ElementLogReader checksumReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("checksum", LogReadFlags.ThrowFailures))
  1391. {
  1392. while (checksumReader.Read(0))
  1393. {
  1394. if (checksumReader.GetEmptyElementValue("checksum", out string value))
  1395. {
  1396. hex = value;
  1397. }
  1398. }
  1399. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1400. }
  1401. int len = hex.Length;
  1402. if ((len % 2) != 0)
  1403. {
  1404. string error = string.Format(CultureInfo.CurrentCulture, "Invalid string representation of checksum - {0}", hex);
  1405. throw Logger.WriteException(new SessionLocalException(this, error));
  1406. }
  1407. int count = len / 2;
  1408. byte[] bytes = new byte[count];
  1409. for (int i = 0; i < count; i++)
  1410. {
  1411. bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
  1412. }
  1413. return bytes;
  1414. }
  1415. }
  1416. public void CreateDirectory(string path)
  1417. {
  1418. using (Logger.CreateCallstackAndLock())
  1419. {
  1420. CheckOpened();
  1421. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mkdir \"{0}\"", Tools.ArgumentEscape(path)));
  1422. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1423. using (ElementLogReader mkdirReader = groupReader.WaitForNonEmptyElementAndCreateLogReader(TransferEventArgs.MkDirTag, LogReadFlags.ThrowFailures))
  1424. {
  1425. ReadElement(mkdirReader, 0);
  1426. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1427. }
  1428. }
  1429. }
  1430. public void MoveFile(string sourcePath, string targetPath)
  1431. {
  1432. using (Logger.CreateCallstackAndLock())
  1433. {
  1434. CheckOpened();
  1435. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mv \"{0}\" \"{1}\"", Tools.ArgumentEscape(sourcePath), Tools.ArgumentEscape(targetPath)));
  1436. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1437. {
  1438. if (!groupReader.TryWaitForNonEmptyElement("mv", LogReadFlags.ThrowFailures))
  1439. {
  1440. throw Logger.WriteException(new SessionRemoteException(this, string.Format(CultureInfo.CurrentCulture, "{0} not found.", sourcePath)));
  1441. }
  1442. else
  1443. {
  1444. using (ElementLogReader mvReader = groupReader.CreateLogReader())
  1445. {
  1446. ReadElement(mvReader, 0);
  1447. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1448. }
  1449. }
  1450. }
  1451. }
  1452. }
  1453. public void DuplicateFile(string sourcePath, string targetPath)
  1454. {
  1455. using (Logger.CreateCallstackAndLock())
  1456. {
  1457. CheckOpened();
  1458. string sourceArgument = Tools.ArgumentEscape(RemotePath.EscapeFileMask(sourcePath));
  1459. string targetArgument = Tools.ArgumentEscape(targetPath);
  1460. string command = string.Format(CultureInfo.InvariantCulture, "cp \"{0}\" \"{1}\"", sourceArgument, targetArgument);
  1461. WriteCommand(command);
  1462. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1463. {
  1464. if (!groupReader.TryWaitForNonEmptyElement("cp", LogReadFlags.ThrowFailures))
  1465. {
  1466. throw Logger.WriteException(new SessionRemoteException(this, string.Format(CultureInfo.CurrentCulture, "{0} not found.", sourcePath)));
  1467. }
  1468. else
  1469. {
  1470. using (ElementLogReader cpReader = groupReader.CreateLogReader())
  1471. {
  1472. ReadElement(cpReader, 0);
  1473. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1474. }
  1475. }
  1476. }
  1477. }
  1478. }
  1479. [Obsolete("Use RemotePath.EscapeFileMask")]
  1480. public string EscapeFileMask(string fileMask)
  1481. {
  1482. return RemotePath.EscapeFileMask(fileMask);
  1483. }
  1484. [Obsolete("Use RemotePath.TranslateRemotePathToLocal")]
  1485. public string TranslateRemotePathToLocal(string remotePath, string remoteRoot, string localRoot)
  1486. {
  1487. return RemotePath.TranslateRemotePathToLocal(remotePath, remoteRoot, localRoot);
  1488. }
  1489. [Obsolete("Use RemotePath.TranslateLocalPathToRemote")]
  1490. public string TranslateLocalPathToRemote(string localPath, string localRoot, string remoteRoot)
  1491. {
  1492. return RemotePath.TranslateLocalPathToRemote(localPath, localRoot, remoteRoot);
  1493. }
  1494. [Obsolete("Use RemotePath.CombinePaths")]
  1495. public string CombinePaths(string path1, string path2)
  1496. {
  1497. return RemotePath.Combine(path1, path2);
  1498. }
  1499. public void AddRawConfiguration(string setting, string value)
  1500. {
  1501. CheckNotOpened();
  1502. RawConfiguration.Add(setting, value);
  1503. }
  1504. #if !NETSTANDARD
  1505. [ComRegisterFunction]
  1506. private static void ComRegister(Type t)
  1507. {
  1508. string subKey = GetTypeLibKey(t);
  1509. Assembly assembly = Assembly.GetAssembly(t);
  1510. object[] attributes = assembly.GetCustomAttributes(typeof(GuidAttribute), false);
  1511. if (attributes.Length == 0)
  1512. {
  1513. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Cannot find {0} attribute for assembly {1}", typeof(GuidAttribute), assembly));
  1514. }
  1515. GuidAttribute guidAttribute = (GuidAttribute)attributes[0];
  1516. Registry.ClassesRoot.CreateSubKey(subKey).SetValue(null, guidAttribute.Value);
  1517. }
  1518. [ComUnregisterFunction]
  1519. private static void ComUnregister(Type t)
  1520. {
  1521. string subKey = GetTypeLibKey(t);
  1522. Registry.ClassesRoot.DeleteSubKey(subKey, false);
  1523. }
  1524. #endif
  1525. private void ReadFile(RemoteFileInfo fileInfo, CustomLogReader fileReader)
  1526. {
  1527. using (Logger.CreateCallstack())
  1528. {
  1529. if (fileReader.GetEmptyElementValue("type", out string value))
  1530. {
  1531. fileInfo.FileType = value[0];
  1532. }
  1533. else if (fileReader.GetEmptyElementValue("size", out value))
  1534. {
  1535. fileInfo.Length = long.Parse(value, CultureInfo.InvariantCulture);
  1536. }
  1537. else if (fileReader.GetEmptyElementValue("modification", out value))
  1538. {
  1539. fileInfo.LastWriteTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Local);
  1540. }
  1541. else if (fileReader.GetEmptyElementValue("permissions", out value))
  1542. {
  1543. fileInfo.FilePermissions = FilePermissions.CreateReadOnlyFromText(value);
  1544. }
  1545. else if (fileReader.GetEmptyElementValue("owner", out value))
  1546. {
  1547. fileInfo.Owner = value;
  1548. }
  1549. else if (fileReader.GetEmptyElementValue("group", out value))
  1550. {
  1551. fileInfo.Group = value;
  1552. }
  1553. }
  1554. }
  1555. internal static string BooleanSwitch(bool flag, string name)
  1556. {
  1557. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", name) : null;
  1558. }
  1559. internal static string BooleanSwitch(bool flag, string onName, string offName)
  1560. {
  1561. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", onName) : string.Format(CultureInfo.InvariantCulture, "-{0}", offName);
  1562. }
  1563. private void AddSynchronizationTransfer(SynchronizationResult result, TransferEventArgs transfer)
  1564. {
  1565. if (transfer != null)
  1566. {
  1567. if (transfer.Side == ProgressSide.Local)
  1568. {
  1569. result.AddUpload(transfer);
  1570. }
  1571. else
  1572. {
  1573. result.AddDownload(transfer);
  1574. }
  1575. RaiseFileTransferredEvent(transfer);
  1576. }
  1577. }
  1578. private static string IncludeTrailingSlash(string path)
  1579. {
  1580. if (!string.IsNullOrEmpty(path) && !path.EndsWith("/", StringComparison.Ordinal))
  1581. {
  1582. path += '/';
  1583. }
  1584. return path;
  1585. }
  1586. private void Cleanup()
  1587. {
  1588. using (Logger.CreateCallstack())
  1589. {
  1590. if (_process != null)
  1591. {
  1592. Logger.WriteLine("Terminating process");
  1593. try
  1594. {
  1595. try
  1596. {
  1597. WriteCommand("exit");
  1598. _process.Close();
  1599. }
  1600. finally
  1601. {
  1602. _process.Dispose();
  1603. _process = null;
  1604. }
  1605. }
  1606. catch (Exception e)
  1607. {
  1608. Logger.WriteLine("Process cleanup Exception: {0}", e);
  1609. }
  1610. }
  1611. Logger.WriteLine("Disposing log readers");
  1612. if (_reader != null)
  1613. {
  1614. _reader.Dispose();
  1615. _reader = null;
  1616. }
  1617. if (_logReader != null)
  1618. {
  1619. _logReader.Dispose();
  1620. _logReader = null;
  1621. }
  1622. // Cleanup log file
  1623. if ((XmlLogPath != null) && File.Exists(XmlLogPath) && !XmlLogPreserve)
  1624. {
  1625. Logger.WriteLine("Deleting XML log file [{0}]", XmlLogPath);
  1626. try
  1627. {
  1628. File.Delete(XmlLogPath);
  1629. }
  1630. catch (DirectoryNotFoundException e)
  1631. {
  1632. Logger.WriteLine("XML log cleanup DirectoryNotFoundException: {0}", e);
  1633. }
  1634. catch (IOException e)
  1635. {
  1636. Logger.WriteLine("XML log cleanup IOException: {0}", e);
  1637. }
  1638. catch (UnauthorizedAccessException e)
  1639. {
  1640. Logger.WriteLine("XML log cleanup UnauthorizedAccessException: {0}", e);
  1641. }
  1642. _xmlLogPath = null;
  1643. }
  1644. }
  1645. }
  1646. private void WriteCommand(string command)
  1647. {
  1648. WriteCommand(command, command);
  1649. }
  1650. private void WriteCommand(string command, string log)
  1651. {
  1652. Logger.WriteLine("Command: [{0}]", log);
  1653. _process.ExecuteCommand(command, log);
  1654. GotOutput();
  1655. }
  1656. private static void ReadElement(CustomLogReader reader, LogReadFlags flags)
  1657. {
  1658. while (reader.Read(flags))
  1659. {
  1660. }
  1661. }
  1662. private void SessionOptionsToUrlAndSwitches(SessionOptions sessionOptions, bool scanFingerprint, out string command, out string log)
  1663. {
  1664. using (Logger.CreateCallstack())
  1665. {
  1666. if (sessionOptions.WebdavSecure)
  1667. {
  1668. if (sessionOptions.Protocol != Protocol.Webdav)
  1669. {
  1670. throw Logger.WriteException(new ArgumentException("SessionOptions.WebdavSecure is set, but SessionOptions.Protocol is not Protocol.Webdav."));
  1671. }
  1672. }
  1673. string head;
  1674. switch (sessionOptions.Protocol)
  1675. {
  1676. case Protocol.Sftp:
  1677. head = "sftp://";
  1678. break;
  1679. case Protocol.Scp:
  1680. head = "scp://";
  1681. break;
  1682. case Protocol.Ftp:
  1683. head = "ftp://";
  1684. break;
  1685. case Protocol.Webdav:
  1686. if (!sessionOptions.WebdavSecure)
  1687. {
  1688. head = "dav://";
  1689. }
  1690. else
  1691. {
  1692. head = "davs://";
  1693. }
  1694. break;
  1695. case Protocol.S3:
  1696. head = "s3://";
  1697. break;
  1698. default:
  1699. throw Logger.WriteException(new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.Protocol)));
  1700. }
  1701. bool hasUsername;
  1702. if (!scanFingerprint)
  1703. {
  1704. hasUsername = !string.IsNullOrEmpty(sessionOptions.UserName);
  1705. if (hasUsername)
  1706. {
  1707. head += UriEscape(sessionOptions.UserName);
  1708. }
  1709. }
  1710. else
  1711. {
  1712. hasUsername = false;
  1713. }
  1714. string url = head;
  1715. string logUrl = head;
  1716. if ((sessionOptions.SecurePassword != null) && !scanFingerprint)
  1717. {
  1718. if (!hasUsername)
  1719. {
  1720. throw Logger.WriteException(new ArgumentException("SessionOptions.Password is set, but SessionOptions.UserName is not."));
  1721. }
  1722. url += ":" + UriEscape(sessionOptions.Password);
  1723. logUrl += ":***";
  1724. }
  1725. string tail = string.Empty;
  1726. if (hasUsername)
  1727. {
  1728. tail += "@";
  1729. }
  1730. if (string.IsNullOrEmpty(sessionOptions.HostName))
  1731. {
  1732. throw Logger.WriteException(new ArgumentException("SessionOptions.HostName is not set."));
  1733. }
  1734. // We should wrap IPv6 literals to square brackets, instead of URL-encoding them,
  1735. // but it works anyway...
  1736. tail += UriEscape(sessionOptions.HostName);
  1737. if (sessionOptions.PortNumber != 0)
  1738. {
  1739. tail += ":" + sessionOptions.PortNumber.ToString(CultureInfo.InvariantCulture);
  1740. }
  1741. if (!string.IsNullOrEmpty(sessionOptions.RootPath) && !scanFingerprint)
  1742. {
  1743. if ((sessionOptions.Protocol != Protocol.Webdav) && (sessionOptions.Protocol != Protocol.S3))
  1744. {
  1745. throw Logger.WriteException(new ArgumentException("SessionOptions.RootPath is set, but SessionOptions.Protocol is not Protocol.Webdav nor Protocol.S3."));
  1746. }
  1747. tail += sessionOptions.RootPath;
  1748. }
  1749. url += tail;
  1750. logUrl += tail;
  1751. SessionOptionsToSwitches(sessionOptions, scanFingerprint, out string arguments, out string logArguments);
  1752. const string switchName = "-rawsettings";
  1753. Tools.AddRawParameters(ref arguments, sessionOptions.RawSettings, switchName, false);
  1754. Tools.AddRawParameters(ref logArguments, sessionOptions.RawSettings, switchName, false);
  1755. if (!string.IsNullOrEmpty(arguments))
  1756. {
  1757. arguments = " " + arguments;
  1758. logArguments = " " + logArguments;
  1759. }
  1760. // Switches should (and particularly the -rawsettings MUST) come after the URL
  1761. command = "\"" + Tools.ArgumentEscape(url) + "\"" + arguments;
  1762. log = "\"" + Tools.ArgumentEscape(logUrl) + "\"" + logArguments;
  1763. }
  1764. }
  1765. private void SessionOptionsToSwitches(SessionOptions sessionOptions, bool scanFingerprint, out string arguments, out string logArguments)
  1766. {
  1767. using (Logger.CreateCallstack())
  1768. {
  1769. List<string> switches = new List<string>();
  1770. if (!string.IsNullOrEmpty(sessionOptions.SshHostKeyFingerprint) ||
  1771. ((sessionOptions.SshHostKeyPolicy != SshHostKeyPolicy.Check) && !scanFingerprint))
  1772. {
  1773. if (!sessionOptions.IsSsh)
  1774. {
  1775. 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."));
  1776. }
  1777. string sshHostKeyFingerprint = sessionOptions.SshHostKeyFingerprint;
  1778. switch (sessionOptions.SshHostKeyPolicy)
  1779. {
  1780. case SshHostKeyPolicy.Check:
  1781. // noop
  1782. break;
  1783. case SshHostKeyPolicy.GiveUpSecurityAndAcceptAny:
  1784. sshHostKeyFingerprint = AddStarToList(sshHostKeyFingerprint);
  1785. Logger.WriteLine("WARNING! Giving up security and accepting any key as configured");
  1786. break;
  1787. case SshHostKeyPolicy.AcceptNew:
  1788. if (!string.IsNullOrEmpty(sshHostKeyFingerprint))
  1789. {
  1790. throw Logger.WriteException(new ArgumentException("SessionOptions.SshHostKeyFingerprint is set and SshHostKeyPolicy is not Check"));
  1791. }
  1792. sshHostKeyFingerprint = "acceptnew";
  1793. break;
  1794. }
  1795. switches.Add(FormatSwitch("hostkey", sshHostKeyFingerprint));
  1796. }
  1797. else
  1798. {
  1799. if (sessionOptions.IsSsh && DefaultConfigurationInternal && !scanFingerprint)
  1800. {
  1801. throw Logger.WriteException(new ArgumentException("SessionOptions.Protocol is Protocol.Sftp or Protocol.Scp, but SessionOptions.SshHostKeyFingerprint is not set."));
  1802. }
  1803. }
  1804. if (!string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath) && !scanFingerprint)
  1805. {
  1806. if (!sessionOptions.IsSsh)
  1807. {
  1808. throw Logger.WriteException(new ArgumentException("SessionOptions.SshPrivateKeyPath is set, but SessionOptions.Protocol is neither Protocol.Sftp nor Protocol.Scp."));
  1809. }
  1810. switches.Add(FormatSwitch("privatekey", sessionOptions.SshPrivateKeyPath));
  1811. }
  1812. if (!string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath) && !scanFingerprint)
  1813. {
  1814. if (!sessionOptions.IsTls)
  1815. {
  1816. throw Logger.WriteException(new ArgumentException("SessionOptions.TlsClientCertificatePath is set, but neither SessionOptions.FtpSecure nor SessionOptions.WebdavSecure is enabled nor is the protocol S3."));
  1817. }
  1818. switches.Add(FormatSwitch("clientcert", sessionOptions.TlsClientCertificatePath));
  1819. }
  1820. if (sessionOptions.FtpSecure != FtpSecure.None)
  1821. {
  1822. if (sessionOptions.Protocol != Protocol.Ftp)
  1823. {
  1824. throw Logger.WriteException(new ArgumentException("SessionOptions.FtpSecure is not FtpSecure.None, but SessionOptions.Protocol is not Protocol.Ftp."));
  1825. }
  1826. switch (sessionOptions.FtpSecure)
  1827. {
  1828. case FtpSecure.Implicit:
  1829. switches.Add(FormatSwitch("implicit"));
  1830. break;
  1831. case FtpSecure.Explicit:
  1832. switches.Add(FormatSwitch("explicit"));
  1833. break;
  1834. default:
  1835. throw Logger.WriteException(new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.FtpSecure)));
  1836. }
  1837. }
  1838. if ((!string.IsNullOrEmpty(sessionOptions.TlsHostCertificateFingerprint) ||
  1839. sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate) &&
  1840. !scanFingerprint)
  1841. {
  1842. if (!sessionOptions.IsTls)
  1843. {
  1844. 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."));
  1845. }
  1846. string tlsHostCertificateFingerprint = sessionOptions.TlsHostCertificateFingerprint;
  1847. if (sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
  1848. {
  1849. Logger.WriteLine("WARNING! Giving up security and accepting any certificate as configured");
  1850. tlsHostCertificateFingerprint = AddStarToList(tlsHostCertificateFingerprint);
  1851. }
  1852. switches.Add(FormatSwitch("certificate", tlsHostCertificateFingerprint));
  1853. }
  1854. if ((sessionOptions.Protocol == Protocol.Ftp) && !scanFingerprint)
  1855. {
  1856. switches.Add(FormatSwitch("passive", (sessionOptions.FtpMode == FtpMode.Passive)));
  1857. }
  1858. switches.Add(FormatSwitch("timeout", (int)sessionOptions.Timeout.TotalSeconds));
  1859. List<string> logSwitches = new List<string>(switches);
  1860. if ((sessionOptions.SecurePrivateKeyPassphrase != null) && !scanFingerprint)
  1861. {
  1862. if (string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath) && string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath))
  1863. {
  1864. throw Logger.WriteException(new ArgumentException("SessionOptions.PrivateKeyPassphrase is set, but neither SessionOptions.SshPrivateKeyPath nor SessionOptions.TlsClientCertificatePath is set."));
  1865. }
  1866. switches.Add(FormatSwitch("passphrase", sessionOptions.PrivateKeyPassphrase));
  1867. logSwitches.Add(FormatSwitch("passphrase", "***"));
  1868. }
  1869. if ((sessionOptions.SecureNewPassword != null) && !scanFingerprint)
  1870. {
  1871. if (sessionOptions.SecurePassword == null)
  1872. {
  1873. throw Logger.WriteException(new ArgumentException("SessionOptions.SecureNewPassword is set, but SessionOptions.SecurePassword is not."));
  1874. }
  1875. switches.Add(FormatSwitch("newpassword", sessionOptions.NewPassword));
  1876. logSwitches.Add(FormatSwitch("newpassword", "***"));
  1877. }
  1878. arguments = string.Join(" ", switches.ToArray());
  1879. logArguments = string.Join(" ", logSwitches.ToArray());
  1880. }
  1881. }
  1882. private static string AddStarToList(string list)
  1883. {
  1884. return (string.IsNullOrEmpty(list) ? string.Empty : list + ";") + "*";
  1885. }
  1886. private RemoteFileInfo DoGetFileInfo(string path)
  1887. {
  1888. using (Logger.CreateCallstack())
  1889. {
  1890. WriteCommand(string.Format(CultureInfo.InvariantCulture, "stat -- \"{0}\"", Tools.ArgumentEscape(path)));
  1891. RemoteFileInfo fileInfo = new RemoteFileInfo();
  1892. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1893. using (ElementLogReader statReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("stat", LogReadFlags.ThrowFailures))
  1894. {
  1895. while (statReader.Read(0))
  1896. {
  1897. if (statReader.GetEmptyElementValue("filename", out string value))
  1898. {
  1899. string name = value;
  1900. int p = name.LastIndexOf('/');
  1901. if (p >= 0)
  1902. {
  1903. name = name.Substring(p + 1);
  1904. }
  1905. fileInfo.Name = name;
  1906. fileInfo.FullName = value;
  1907. }
  1908. else if (statReader.IsNonEmptyElement("file"))
  1909. {
  1910. using (ElementLogReader fileReader = statReader.CreateLogReader())
  1911. {
  1912. while (fileReader.Read(0))
  1913. {
  1914. ReadFile(fileInfo, fileReader);
  1915. }
  1916. }
  1917. }
  1918. }
  1919. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1920. }
  1921. return fileInfo;
  1922. }
  1923. }
  1924. internal static string FormatSwitch(string key)
  1925. {
  1926. return string.Format(CultureInfo.InvariantCulture, "-{0}", key);
  1927. }
  1928. internal static string FormatSwitch(string key, string value)
  1929. {
  1930. return string.Format(CultureInfo.InvariantCulture, "-{0}=\"{1}\"", key, Tools.ArgumentEscape(value));
  1931. }
  1932. internal static string FormatSwitch(string key, int value)
  1933. {
  1934. return string.Format(CultureInfo.InvariantCulture, "-{0}={1}", key, value.ToString(CultureInfo.InvariantCulture));
  1935. }
  1936. internal static string FormatSwitch(string key, bool value)
  1937. {
  1938. return FormatSwitch(key, (value ? 1 : 0));
  1939. }
  1940. private static string UriEscape(string s)
  1941. {
  1942. return Uri.EscapeDataString(s);
  1943. }
  1944. internal void GotOutput()
  1945. {
  1946. _lastOutput = DateTime.Now;
  1947. }
  1948. private void ProcessOutputDataReceived(object sender, OutputDataReceivedEventArgs e)
  1949. {
  1950. if (e == null)
  1951. {
  1952. Logger.WriteLine("Got incomplete progress output");
  1953. }
  1954. else
  1955. {
  1956. Logger.WriteLine("Scheduling output: [{0}]", e.Data);
  1957. string s = e.Data.TrimEnd(new[] { '\r' });
  1958. lock (Output)
  1959. {
  1960. Output.InternalAdd(s);
  1961. if (Output.Count > 1000)
  1962. {
  1963. Output.InternalRemoveFirst();
  1964. }
  1965. if (e.Error)
  1966. {
  1967. _error.InternalAdd(s);
  1968. if (_error.Count > 1000)
  1969. {
  1970. _error.InternalRemoveFirst();
  1971. }
  1972. }
  1973. }
  1974. ScheduleEvent(() => RaiseOutputDataReceived(e.Data, e.Error));
  1975. }
  1976. GotOutput();
  1977. }
  1978. private void ScheduleEvent(Action action)
  1979. {
  1980. lock (_events)
  1981. {
  1982. _events.Add(action);
  1983. _eventsEvent.Set();
  1984. }
  1985. }
  1986. internal void CheckForTimeout(string additional = null)
  1987. {
  1988. TimeSpan timeout = Timeout;
  1989. if (timeout < _sessionTimeout)
  1990. {
  1991. timeout = _sessionTimeout + TimeSpan.FromSeconds(1);
  1992. }
  1993. if (DateTime.Now - _lastOutput > timeout)
  1994. {
  1995. Logger.WriteLine("Timeout waiting for WinSCP to respond - asking for callstack");
  1996. _process.RequestCallstack();
  1997. string message = "Timeout waiting for WinSCP to respond";
  1998. if (additional != null)
  1999. {
  2000. message += " - " + additional;
  2001. }
  2002. if (_logReader != null)
  2003. {
  2004. _logReader.SetTimeouted();
  2005. }
  2006. Cleanup();
  2007. throw Logger.WriteException(new TimeoutException(message));
  2008. }
  2009. if (_aborted)
  2010. {
  2011. throw Logger.WriteException(new SessionLocalException(this, "Aborted."));
  2012. }
  2013. if (_throwStdOut && (_process.StdOut != null) && _process.StdOut.ReadAvailable(1))
  2014. {
  2015. // This is here to return from GetFile asap (?)
  2016. throw Logger.WriteException(new StdOutException());
  2017. }
  2018. }
  2019. private void RaiseFileTransferredEvent(TransferEventArgs args)
  2020. {
  2021. Logger.WriteLine("FileTransferredEvent: [{0}]", args.FileName);
  2022. FileTransferred?.Invoke(this, args);
  2023. }
  2024. internal void RaiseFailed(SessionRemoteException e)
  2025. {
  2026. Logger.WriteLine("Failed: [{0}]", e);
  2027. if ((Failed != null) && !_ignoreFailed)
  2028. {
  2029. Failed(this, new FailedEventArgs { Error = e });
  2030. }
  2031. foreach (OperationResultBase operationResult in _operationResults)
  2032. {
  2033. operationResult.AddFailure(e);
  2034. }
  2035. }
  2036. private void CheckNotDisposed()
  2037. {
  2038. if (_disposed)
  2039. {
  2040. throw Logger.WriteException(new InvalidOperationException("Object is disposed"));
  2041. }
  2042. if (_aborted)
  2043. {
  2044. throw Logger.WriteException(new InvalidOperationException("Session was aborted"));
  2045. }
  2046. }
  2047. private void CheckOpened()
  2048. {
  2049. if (!Opened)
  2050. {
  2051. throw Logger.WriteException(new InvalidOperationException("Session is not opened"));
  2052. }
  2053. }
  2054. private void CheckNotOpened()
  2055. {
  2056. if (Opened)
  2057. {
  2058. throw Logger.WriteException(new InvalidOperationException("Session is already opened"));
  2059. }
  2060. }
  2061. private void RaiseOutputDataReceived(string data, bool error)
  2062. {
  2063. Logger.WriteLine("Output: [{0}]", data);
  2064. OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(data, error));
  2065. }
  2066. internal void DispatchEvents(int interval)
  2067. {
  2068. DateTime start = DateTime.Now;
  2069. while (_eventsEvent.WaitOne(interval, false))
  2070. {
  2071. lock (_events)
  2072. {
  2073. foreach (Action action in _events)
  2074. {
  2075. action();
  2076. }
  2077. _events.Clear();
  2078. }
  2079. interval -= (int) (DateTime.Now - start).TotalMilliseconds;
  2080. if (interval < 0)
  2081. {
  2082. break;
  2083. }
  2084. start = DateTime.Now;
  2085. }
  2086. }
  2087. private IDisposable RegisterOperationResult(OperationResultBase operationResult)
  2088. {
  2089. _operationResults.Add(operationResult);
  2090. return new OperationResultGuard(this, operationResult);
  2091. }
  2092. internal void UnregisterOperationResult(OperationResultBase operationResult)
  2093. {
  2094. // GetFile relies on this not to throw
  2095. _operationResults.Remove(operationResult);
  2096. }
  2097. internal bool WantsProgress
  2098. {
  2099. get
  2100. {
  2101. return (_fileTransferProgress != null);
  2102. }
  2103. }
  2104. private IDisposable CreateProgressHandler()
  2105. {
  2106. using (Logger.CreateCallstack())
  2107. {
  2108. _progressHandling++;
  2109. return new ProgressHandler(this);
  2110. }
  2111. }
  2112. internal void DisableProgressHandling()
  2113. {
  2114. using (Logger.CreateCallstack())
  2115. {
  2116. if (_progressHandling <= 0)
  2117. {
  2118. throw Logger.WriteException(new InvalidOperationException("Progress handling not enabled"));
  2119. }
  2120. // make sure we process all pending progress events
  2121. DispatchEvents(0);
  2122. _progressHandling--;
  2123. }
  2124. }
  2125. internal void ProcessChoice(QueryReceivedEventArgs args)
  2126. {
  2127. if (_queryReceived != null) // optimization
  2128. {
  2129. _choiceEvent.Reset();
  2130. ScheduleEvent(() => Choice(args));
  2131. _choiceEvent.WaitOne();
  2132. }
  2133. }
  2134. private void Choice(QueryReceivedEventArgs args)
  2135. {
  2136. _queryReceived?.Invoke(this, args);
  2137. _choiceEvent.Set();
  2138. }
  2139. internal void ProcessProgress(FileTransferProgressEventArgs args)
  2140. {
  2141. ScheduleEvent(() => Progress(args));
  2142. }
  2143. private void Progress(FileTransferProgressEventArgs args)
  2144. {
  2145. if ((_progressHandling >= 0) && WantsProgress)
  2146. {
  2147. _fileTransferProgress(this, args);
  2148. if (args.Cancel)
  2149. {
  2150. _process.Cancel();
  2151. }
  2152. }
  2153. }
  2154. private void SetupTempPath()
  2155. {
  2156. using (Logger.CreateCallstack())
  2157. {
  2158. if (!string.IsNullOrEmpty(_xmlLogPath))
  2159. {
  2160. bool exists = File.Exists(_xmlLogPath);
  2161. Logger.WriteLine("Configured temporary file: {0} - Exists [{1}]", _xmlLogPath, exists);
  2162. if (exists)
  2163. {
  2164. throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Configured temporary file {0} already exists", _xmlLogPath)));
  2165. }
  2166. }
  2167. else
  2168. {
  2169. string path = Path.GetTempPath();
  2170. Logger.WriteLine("Temporary folder: {0}", path);
  2171. string process = Process.GetCurrentProcess().Id.ToString("X4", CultureInfo.InvariantCulture);
  2172. string instance = GetHashCode().ToString("X8", CultureInfo.InvariantCulture);
  2173. string filename;
  2174. bool exists;
  2175. do
  2176. {
  2177. string uniqueStr = (_logUnique > 0 ? "." + _logUnique.ToString(CultureInfo.InvariantCulture) : string.Empty);
  2178. ++_logUnique;
  2179. filename = Path.Combine(path, "wscp" + process + "." + instance + uniqueStr + ".tmp");
  2180. exists = File.Exists(filename);
  2181. Logger.WriteLine("Temporary file [{0}] - Exists [{1}]", filename, exists);
  2182. }
  2183. while (exists);
  2184. _xmlLogPath = filename;
  2185. }
  2186. }
  2187. }
  2188. #if !NETSTANDARD
  2189. private static string GetTypeLibKey(Type t)
  2190. {
  2191. return "CLSID\\{" + t.GUID.ToString().ToUpperInvariant() + "}\\TypeLib";
  2192. }
  2193. #endif
  2194. FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
  2195. {
  2196. using (Logger.CreateCallstack())
  2197. {
  2198. Logger.WriteLine("Name [{0}]", name);
  2199. FieldInfo result = GetType().GetField(name, bindingAttr);
  2200. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2201. return result;
  2202. }
  2203. }
  2204. FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
  2205. {
  2206. using (Logger.CreateCallstack())
  2207. {
  2208. FieldInfo[] result = GetType().GetFields(bindingAttr);
  2209. Logger.WriteLine("Fields [{0}]", result.Length);
  2210. return result;
  2211. }
  2212. }
  2213. MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
  2214. {
  2215. using (Logger.CreateCallstack())
  2216. {
  2217. Logger.WriteLine("Name [{0}]", name);
  2218. MemberInfo[] result = GetType().GetMember(name, bindingAttr);
  2219. Logger.WriteLine("Result [{0}]", result.Length);
  2220. return result;
  2221. }
  2222. }
  2223. MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
  2224. {
  2225. using (Logger.CreateCallstack())
  2226. {
  2227. MemberInfo[] result = GetType().GetMembers(bindingAttr);
  2228. Logger.WriteLine("Result [{0}]", result.Length);
  2229. return result;
  2230. }
  2231. }
  2232. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
  2233. {
  2234. using (Logger.CreateCallstack())
  2235. {
  2236. Logger.WriteLine("Name [{0}]", name);
  2237. MethodInfo result = GetType().GetMethod(name, bindingAttr);
  2238. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2239. return result;
  2240. }
  2241. }
  2242. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
  2243. {
  2244. using (Logger.CreateCallstack())
  2245. {
  2246. Logger.WriteLine("Name [{0}]", name);
  2247. MethodInfo result = GetType().GetMethod(name, bindingAttr, binder, types, modifiers);
  2248. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2249. return result;
  2250. }
  2251. }
  2252. MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
  2253. {
  2254. using (Logger.CreateCallstack())
  2255. {
  2256. MethodInfo[] result = GetType().GetMethods(bindingAttr);
  2257. Logger.WriteLine("Result [{0}]", result.Length);
  2258. return result;
  2259. }
  2260. }
  2261. PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
  2262. {
  2263. using (Logger.CreateCallstack())
  2264. {
  2265. PropertyInfo[] result = GetType().GetProperties(bindingAttr);
  2266. Logger.WriteLine("Result [{0}]", result.Length);
  2267. return result;
  2268. }
  2269. }
  2270. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
  2271. {
  2272. using (Logger.CreateCallstack())
  2273. {
  2274. Logger.WriteLine("Name [{0}]", name);
  2275. PropertyInfo result = GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
  2276. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2277. return result;
  2278. }
  2279. }
  2280. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
  2281. {
  2282. using (Logger.CreateCallstack())
  2283. {
  2284. Logger.WriteLine("Name [{0}]", name);
  2285. PropertyInfo result = GetType().GetProperty(name, bindingAttr);
  2286. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2287. return result;
  2288. }
  2289. }
  2290. private void LogInvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  2291. {
  2292. Logger.WriteLine("Name [{0}]", name);
  2293. Logger.WriteLine("BindingFlags [{0}]", invokeAttr);
  2294. Logger.WriteLine("Binder [{0}]", binder);
  2295. Logger.WriteLine("Target [{0}]", target);
  2296. if (args != null)
  2297. {
  2298. Logger.WriteLine("Args [{0}] [{1}]", args.Length, modifiers != null ? modifiers.Length.ToString(CultureInfo.InvariantCulture) : "null");
  2299. for (int i = 0; i < args.Length; ++i)
  2300. {
  2301. Logger.WriteLine("Arg [{0}] [{1}] [{1}] [{2}]", i, args[i], (args[i] != null ? args[i].GetType().ToString() : "null"), (modifiers != null ? modifiers[i].ToString() : "null"));
  2302. }
  2303. }
  2304. Logger.WriteLine("Culture [{0}]", culture);
  2305. if (namedParameters != null)
  2306. {
  2307. foreach (string namedParameter in namedParameters)
  2308. {
  2309. Logger.WriteLine("NamedParameter [{0}]", namedParameter);
  2310. }
  2311. }
  2312. }
  2313. object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  2314. {
  2315. using (Logger.CreateCallstack())
  2316. {
  2317. object result;
  2318. try
  2319. {
  2320. bool wasLogging = Logger.Logging;
  2321. if (wasLogging)
  2322. {
  2323. // factored out to reduce this method complexity
  2324. LogInvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  2325. }
  2326. if (target == null)
  2327. {
  2328. throw Logger.WriteException(new ArgumentNullException(nameof(target)));
  2329. }
  2330. Type type = target.GetType();
  2331. // RuntimeType.InvokeMember below calls into Binder.BindToMethod (Binder is OleAutBinder)
  2332. // that fails to match method, if integer value is provided to enum argument
  2333. // (SynchronizeDirectories with its SynchronizationMode and SynchronizationCriteria).
  2334. // This does not happen if we do not implement IReflect, though no idea why.
  2335. // So as a workaround we check, if the method has no overloads (what is always true for Session),
  2336. // and call the only instance directly.
  2337. // Calling MethodInfo.Invoke with int values for enum arguments works.
  2338. // Only as a fallback, we call InvokeMember (what is currently actually used only when
  2339. // the method with given name does not exist at all)
  2340. MethodInfo method = null;
  2341. PropertyInfo property = null;
  2342. // would be way too difficult to implement the below involving named arguments
  2343. if (namedParameters == null)
  2344. {
  2345. try
  2346. {
  2347. BindingFlags bindingFlags = invokeAttr | BindingFlags.Instance | BindingFlags.Public;
  2348. method = type.GetMethod(name, bindingFlags);
  2349. if (args == null)
  2350. {
  2351. throw Logger.WriteException(new ArgumentNullException(nameof(args)));
  2352. }
  2353. if (method != null)
  2354. {
  2355. // MethodInfo.Invoke does not fill-in optional arguments (contrary to RuntimeType.InvokeMember)
  2356. ParameterInfo[] parameters = method.GetParameters();
  2357. if (args.Length < parameters.Length)
  2358. {
  2359. Logger.WriteLine("Provided less parameters [{0}] than defined [{1}]", args.Length, parameters.Length);
  2360. object[] args2 = new object[parameters.Length];
  2361. for (int i = 0; i < parameters.Length; i++)
  2362. {
  2363. if (i < args.Length)
  2364. {
  2365. args2[i] = args[i];
  2366. }
  2367. else
  2368. {
  2369. if (!parameters[i].IsOptional)
  2370. {
  2371. Logger.WriteLine("Parameter [{0}] of [{1}] is not optional", i, method);
  2372. args2 = null;
  2373. break;
  2374. }
  2375. else
  2376. {
  2377. Logger.WriteLine("Adding default value [{0}] for optional parameter [{1}]", parameters[i].DefaultValue, i);
  2378. args2[i] = parameters[i].DefaultValue;
  2379. }
  2380. }
  2381. }
  2382. if (args2 != null)
  2383. {
  2384. args = args2;
  2385. }
  2386. }
  2387. }
  2388. else if (args.Length == 1) // sanity check
  2389. {
  2390. property = type.GetProperty(name, bindingFlags);
  2391. }
  2392. }
  2393. catch (AmbiguousMatchException e)
  2394. {
  2395. Logger.WriteLine("Unexpected ambiguous match [{0}]", e.Message);
  2396. }
  2397. }
  2398. if (method != null)
  2399. {
  2400. Logger.WriteLine("Invoking unambiguous method [{0}]", method);
  2401. result = method.Invoke(target, invokeAttr, binder, args, culture);
  2402. }
  2403. else if (property != null)
  2404. {
  2405. Logger.WriteLine("Setting unambiguous property [{0}]", property);
  2406. property.SetValue(target, args[0], invokeAttr, binder, null, culture);
  2407. result = null;
  2408. }
  2409. else
  2410. {
  2411. Logger.WriteLine("Invoking ambiguous/non-existing method 2 [{0}]", name);
  2412. result = type.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  2413. }
  2414. if (!wasLogging && Logger.Logging)
  2415. {
  2416. Logger.WriteLine("Invoking member {0} enabled debug logging", name);
  2417. // Might call LogInvokeMember here, but it's not really useful.
  2418. }
  2419. Logger.WriteLine("Result [{0}] [{1}]", result, (result != null ? result.GetType().ToString() : "null"));
  2420. }
  2421. catch (Exception e)
  2422. {
  2423. Logger.WriteLine("Error [{0}]", e);
  2424. throw;
  2425. }
  2426. return result;
  2427. }
  2428. }
  2429. Type IReflect.UnderlyingSystemType
  2430. {
  2431. get { return GetType(); }
  2432. }
  2433. internal const string Namespace = "http://winscp.net/schema/session/1.0";
  2434. internal Logger Logger { get; private set; }
  2435. internal bool GuardProcessWithJobInternal { get { return _guardProcessWithJob; } set { CheckNotOpened(); _guardProcessWithJob = value; } }
  2436. internal bool TestHandlesClosedInternal { get; set; }
  2437. internal Dictionary<string, string> RawConfiguration { get; private set; }
  2438. internal bool DefaultConfigurationInternal { get { return _defaultConfiguration; } }
  2439. internal string IniFilePathInternal { get { return _iniFilePath; } }
  2440. private ExeSessionProcess _process;
  2441. private DateTime _lastOutput;
  2442. private ElementLogReader _reader;
  2443. private SessionLogReader _logReader;
  2444. private readonly IList<OperationResultBase> _operationResults;
  2445. private readonly IList<Action> _events;
  2446. private AutoResetEvent _eventsEvent;
  2447. private ManualResetEvent _choiceEvent;
  2448. private bool _disposed;
  2449. private string _executablePath;
  2450. private string _additionalExecutableArguments;
  2451. private bool _defaultConfiguration;
  2452. private bool _disableVersionCheck;
  2453. private string _iniFilePath;
  2454. private TimeSpan _reconnectTime;
  2455. private string _sessionLogPath;
  2456. private bool _aborted;
  2457. private int _logUnique;
  2458. private string _xmlLogPath;
  2459. private FileTransferProgressEventHandler _fileTransferProgress;
  2460. private int _progressHandling;
  2461. private bool _guardProcessWithJob;
  2462. private string _homePath;
  2463. #if !NETSTANDARD
  2464. private string _executableProcessUserName;
  2465. private SecureString _executableProcessPassword;
  2466. #endif
  2467. private StringCollection _error;
  2468. private bool _ignoreFailed;
  2469. private TimeSpan _sessionTimeout;
  2470. private QueryReceivedEventHandler _queryReceived;
  2471. private bool _throwStdOut;
  2472. }
  2473. }