Session.cs 113 KB

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