Session.cs 115 KB

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