Session.cs 108 KB

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