Session.cs 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Globalization;
  6. using System.Runtime.InteropServices;
  7. using System.Threading;
  8. using System.Xml;
  9. #if !NETSTANDARD
  10. using Microsoft.Win32;
  11. #endif
  12. using System.Diagnostics;
  13. #if !NETSTANDARD
  14. using System.Security;
  15. #endif
  16. using System.Text.RegularExpressions;
  17. using System.Linq;
  18. namespace WinSCP
  19. {
  20. [Guid("38649D44-B839-4F2C-A9DC-5D45EEA4B5E9")]
  21. [ComVisible(true)]
  22. public enum SynchronizationMode
  23. {
  24. Local = 0,
  25. Remote = 1,
  26. Both = 2,
  27. }
  28. [Guid("3F770EC1-35F5-4A7B-A000-46A2F7A213D8")]
  29. [ComVisible(true)]
  30. [Flags]
  31. public enum SynchronizationCriteria
  32. {
  33. None = 0x00,
  34. Time = 0x01,
  35. Size = 0x02,
  36. Either = Time | Size,
  37. }
  38. [Guid("6C441F60-26AA-44FC-9B93-08884768507B")]
  39. [ComVisible(true)]
  40. [Flags]
  41. public enum EnumerationOptions
  42. {
  43. None = 0x00,
  44. AllDirectories = 0x01,
  45. MatchDirectories = 0x02,
  46. EnumerateDirectories = 0x04,
  47. }
  48. [Guid("16B6D8F6-C0B4-487D-9546-A25BBF582ED6")]
  49. [ComVisible(true)]
  50. public enum ProgressSide
  51. {
  52. Local = 0,
  53. Remote = 1,
  54. }
  55. public delegate void OutputDataReceivedEventHandler(object sender, OutputDataReceivedEventArgs e);
  56. public delegate void FileTransferredEventHandler(object sender, TransferEventArgs e);
  57. public delegate void FileTransferProgressEventHandler(object sender, FileTransferProgressEventArgs e);
  58. public delegate void FailedEventHandler(object sender, FailedEventArgs e);
  59. public delegate void QueryReceivedEventHandler(object sender, QueryReceivedEventArgs e);
  60. [Guid("56FFC5CE-3867-4EF0-A3B5-CFFBEB99EA35")]
  61. [ClassInterface(Constants.ClassInterface)]
  62. [ComVisible(true)]
  63. [ComSourceInterfaces(typeof(ISessionEvents))]
  64. public sealed class Session : IDisposable, IReflect
  65. {
  66. public string ExecutablePath { get { return _executablePath; } set { CheckNotOpened(); _executablePath = value; } }
  67. #if !NETSTANDARD
  68. public string ExecutableProcessUserName { get { return _executableProcessUserName; } set { CheckNotOpened(); _executableProcessUserName = value; } }
  69. public SecureString ExecutableProcessPassword { get { return _executableProcessPassword; } set { CheckNotOpened(); _executableProcessPassword = value; } }
  70. #endif
  71. public string AdditionalExecutableArguments { get { return _additionalExecutableArguments; } set { CheckNotOpened(); _additionalExecutableArguments = value; } }
  72. [Obsolete("Use AddRawConfiguration")]
  73. public bool DefaultConfiguration { get { return _defaultConfiguration; } set { CheckNotOpened(); _defaultConfiguration = value; } }
  74. public bool DisableVersionCheck { get { return _disableVersionCheck; } set { CheckNotOpened(); _disableVersionCheck = value; } }
  75. [Obsolete("Use AddRawConfiguration")]
  76. public string IniFilePath { get { return _iniFilePath; } set { CheckNotOpened(); _iniFilePath = value; } }
  77. public TimeSpan ReconnectTime { get { return _reconnectTime; } set { CheckNotOpened(); _reconnectTime = value; } }
  78. public int ReconnectTimeInMilliseconds { get { return Tools.TimeSpanToMilliseconds(ReconnectTime); } set { ReconnectTime = Tools.MillisecondsToTimeSpan(value); } }
  79. public string DebugLogPath { get { CheckNotDisposed(); return Logger.LogPath; } set { CheckNotDisposed(); Logger.LogPath = value; } }
  80. public int DebugLogLevel { get { CheckNotDisposed(); return Logger.LogLevel; } set { CheckNotDisposed(); Logger.LogLevel = value; } }
  81. public string SessionLogPath { get { return _sessionLogPath; } set { CheckNotOpened(); _sessionLogPath = value; } }
  82. public string XmlLogPath { get { return _xmlLogPath; } set { CheckNotOpened(); _xmlLogPath = value; } }
  83. public bool XmlLogPreserve { get; set; }
  84. #if DEBUG
  85. public bool GuardProcessWithJob { get { return GuardProcessWithJobInternal; } set { GuardProcessWithJobInternal = value; } }
  86. public bool TestHandlesClosed { get { return TestHandlesClosedInternal; } set { TestHandlesClosedInternal = value; } }
  87. #endif
  88. public string HomePath { get { CheckOpened(); return _homePath; } }
  89. public TimeSpan Timeout { get; set; }
  90. public StringCollection Output { get; private set; }
  91. public bool Opened { get { CheckNotDisposed(); return (_process != null); } }
  92. public event FileTransferredEventHandler FileTransferred;
  93. public event FailedEventHandler Failed;
  94. public event OutputDataReceivedEventHandler OutputDataReceived;
  95. public event FileTransferProgressEventHandler FileTransferProgress
  96. {
  97. add
  98. {
  99. using (Logger.CreateCallstackAndLock())
  100. {
  101. CheckNotOpened();
  102. _fileTransferProgress += value;
  103. }
  104. }
  105. remove
  106. {
  107. using (Logger.CreateCallstackAndLock())
  108. {
  109. CheckNotOpened();
  110. _fileTransferProgress -= value;
  111. }
  112. }
  113. }
  114. public event QueryReceivedEventHandler QueryReceived { add { AddQueryReceived(value); } remove { RemoveQueryReceived(value); } }
  115. private void AddQueryReceived(QueryReceivedEventHandler value)
  116. {
  117. using (Logger.CreateCallstackAndLock())
  118. {
  119. bool send = (_queryReceived == null);
  120. _queryReceived += value;
  121. if (Opened && send)
  122. {
  123. SendOptionBatchCommand();
  124. WaitForGroup();
  125. }
  126. }
  127. }
  128. private void RemoveQueryReceived(QueryReceivedEventHandler value)
  129. {
  130. using (Logger.CreateCallstackAndLock())
  131. {
  132. if (_queryReceived != null)
  133. {
  134. _queryReceived -= value;
  135. if (Opened && (_queryReceived == null))
  136. {
  137. SendOptionBatchCommand();
  138. WaitForGroup();
  139. }
  140. }
  141. }
  142. }
  143. public Session()
  144. {
  145. Logger = new Logger();
  146. using (Logger.CreateCallstackAndLock())
  147. {
  148. Timeout = new TimeSpan(0, 1, 0);
  149. _reconnectTime = new TimeSpan(0, 2, 0); // keep in sync with TScript::OptionImpl
  150. ResetOutput();
  151. _operationResults = new List<OperationResultBase>();
  152. _events = new List<Action>();
  153. _eventsEvent = new AutoResetEvent(false);
  154. _choiceEvent = new ManualResetEvent(false);
  155. _disposed = false;
  156. _defaultConfiguration = true;
  157. _logUnique = 0;
  158. _guardProcessWithJob = true;
  159. RawConfiguration = new Dictionary<string, string>();
  160. }
  161. }
  162. private void ResetOutput()
  163. {
  164. Output = new StringCollection();
  165. _error = new StringCollection();
  166. }
  167. public void Dispose()
  168. {
  169. using (Logger.CreateCallstackAndLock())
  170. {
  171. _disposed = true;
  172. Cleanup();
  173. Logger.Dispose();
  174. if (_eventsEvent != null)
  175. {
  176. _eventsEvent.Close();
  177. _eventsEvent = null;
  178. }
  179. if (_choiceEvent != null)
  180. {
  181. _choiceEvent.Close();
  182. _choiceEvent = null;
  183. }
  184. GC.SuppressFinalize(this);
  185. }
  186. }
  187. public void Abort()
  188. {
  189. using (Logger.CreateCallstack())
  190. {
  191. CheckOpened();
  192. _aborted = true;
  193. // double-check
  194. if (_process != null)
  195. {
  196. _process.Abort();
  197. }
  198. }
  199. }
  200. public void Open(SessionOptions sessionOptions)
  201. {
  202. using (Logger.CreateCallstackAndLock())
  203. {
  204. CheckNotDisposed();
  205. if (Opened)
  206. {
  207. throw Logger.WriteException(new InvalidOperationException("Session is already opened"));
  208. }
  209. if (sessionOptions == null)
  210. {
  211. throw Logger.WriteException(new ArgumentNullException(nameof(sessionOptions)));
  212. }
  213. try
  214. {
  215. SetupTempPath();
  216. ResetOutput();
  217. _process = ExeSessionProcess.CreateForSession(this);
  218. _process.OutputDataReceived += ProcessOutputDataReceived;
  219. _process.Start();
  220. GotOutput();
  221. // setup batch mode
  222. SendOptionBatchCommand();
  223. WriteCommand("option confirm off");
  224. object reconnectTimeValue;
  225. if (ReconnectTime != TimeSpan.MaxValue)
  226. {
  227. reconnectTimeValue = (int)ReconnectTime.TotalSeconds;
  228. }
  229. else
  230. {
  231. reconnectTimeValue = "off";
  232. }
  233. string reconnectTimeCommand =
  234. string.Format(CultureInfo.InvariantCulture, "option reconnecttime {0}", reconnectTimeValue);
  235. WriteCommand(reconnectTimeCommand);
  236. SessionOptionsToUrlAndSwitches(sessionOptions, false, out string command, out string log);
  237. const string openCommand = "open ";
  238. command = openCommand + command;
  239. log = openCommand + log;
  240. WriteCommand(command, log);
  241. Logger.WriteLine("Waiting for XML log file");
  242. // Wait until the log file gets created or WinSCP terminates (in case of fatal error)
  243. do
  244. {
  245. string logExplanation;
  246. lock (Output)
  247. {
  248. if (_error.Count > 0)
  249. {
  250. logExplanation = GetErrorOutputMessage();
  251. }
  252. else if (Output.Count > 0)
  253. {
  254. logExplanation =
  255. string.Format(
  256. CultureInfo.CurrentCulture, "Output was \"{0}\". ", ListToString(Output));
  257. }
  258. else
  259. {
  260. logExplanation = "There was no output. ";
  261. }
  262. }
  263. logExplanation +=
  264. string.Format(CultureInfo.CurrentCulture,
  265. "Response log file {0} was not created. This could indicate lack of write permissions to the log folder or problems starting WinSCP itself.",
  266. XmlLogPath);
  267. if (_process.HasExited && !File.Exists(XmlLogPath))
  268. {
  269. #if !NETSTANDARD
  270. Logger.WriteCounters();
  271. #endif
  272. Logger.WriteProcesses();
  273. _process.WriteStatus();
  274. string exitCode = string.Format(CultureInfo.CurrentCulture, "{0}", _process.ExitCode);
  275. if (_process.ExitCode < 0)
  276. {
  277. exitCode = string.Format(CultureInfo.CurrentCulture, "{0} ({1:X})", exitCode, _process.ExitCode);
  278. }
  279. throw Logger.WriteException(
  280. new SessionLocalException(this,
  281. string.Format(CultureInfo.CurrentCulture, "WinSCP process terminated with exit code {0}. ", exitCode) +
  282. logExplanation));
  283. }
  284. Thread.Sleep(50);
  285. CheckForTimeout(
  286. "WinSCP has not responded in time. " +
  287. logExplanation);
  288. } while (!File.Exists(XmlLogPath));
  289. Logger.WriteLine("XML log file created");
  290. _logReader = new SessionLogReader(this);
  291. _logReader.WaitForNonEmptyElement("session", LogReadFlags.ThrowFailures);
  292. // special variant of ElementLogReader that throws when closing element (</session>) is encountered
  293. _reader = new SessionElementLogReader(_logReader);
  294. // Skip "open" command <group>
  295. WaitForGroup();
  296. WriteCommand("pwd");
  297. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  298. using (ElementLogReader cwdReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("cwd", LogReadFlags.ThrowFailures))
  299. {
  300. while (cwdReader.Read(0))
  301. {
  302. if (cwdReader.GetEmptyElementValue("cwd", out string value))
  303. {
  304. _homePath = value;
  305. }
  306. }
  307. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  308. }
  309. _sessionTimeout = sessionOptions.Timeout;
  310. }
  311. catch (Exception e)
  312. {
  313. Logger.WriteLine("Exception: {0}", e);
  314. Cleanup();
  315. throw;
  316. }
  317. }
  318. }
  319. private void SendOptionBatchCommand()
  320. {
  321. string command = string.Format(CultureInfo.InvariantCulture, "option batch {0}", (_queryReceived != null ? "off" : "on"));
  322. WriteCommand(command);
  323. }
  324. private void WaitForGroup()
  325. {
  326. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  327. {
  328. ReadElement(groupReader, LogReadFlags.ThrowFailures);
  329. }
  330. }
  331. internal string GetErrorOutputMessage()
  332. {
  333. string result = null;
  334. if (_error.Count > 0)
  335. {
  336. result = string.Format(CultureInfo.CurrentCulture, "Error output was \"{0}\". ", ListToString(_error));
  337. }
  338. return result;
  339. }
  340. private static string ListToString(StringCollection list)
  341. {
  342. string[] stringArray = new string[list.Count];
  343. list.CopyTo(stringArray, 0);
  344. string s = string.Join(Environment.NewLine, stringArray);
  345. return s;
  346. }
  347. public string ScanFingerprint(SessionOptions sessionOptions, string algorithm)
  348. {
  349. using (Logger.CreateCallstackAndLock())
  350. {
  351. string normalizeAlgorithm = NormalizeIdent(algorithm);
  352. if (string.IsNullOrEmpty(normalizeAlgorithm))
  353. {
  354. throw Logger.WriteException(new ArgumentException("Algorithm cannot be empty", nameof(algorithm)));
  355. }
  356. string result;
  357. CheckNotDisposed();
  358. if (Opened)
  359. {
  360. throw Logger.WriteException(new InvalidOperationException("Session is already opened"));
  361. }
  362. try
  363. {
  364. ResetOutput();
  365. SessionOptionsToUrlAndSwitches(sessionOptions, true, out string command, out string log);
  366. string additionalArguments = "/fingerprintscan " + command;
  367. _process = ExeSessionProcess.CreateForConsole(this, additionalArguments);
  368. _process.OutputDataReceived += ProcessOutputDataReceived;
  369. _process.Start();
  370. GotOutput();
  371. while (!_process.HasExited)
  372. {
  373. Thread.Sleep(50);
  374. CheckForTimeout();
  375. }
  376. if (_process.ExitCode == 0)
  377. {
  378. result = null;
  379. foreach (string s in Output)
  380. {
  381. int p = s.IndexOf(":", StringComparison.Ordinal);
  382. if (p < 0)
  383. {
  384. throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Unexpected fingerprint scan result line '{0}'", s)));
  385. }
  386. string a = NormalizeIdent(s.Substring(0, p).Trim());
  387. if (normalizeAlgorithm.Equals(a, StringComparison.OrdinalIgnoreCase))
  388. {
  389. result = s.Substring(p + 1).Trim();
  390. break;
  391. }
  392. }
  393. if (result == null)
  394. {
  395. throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Fingerprint for algorithm {0} not supported", algorithm)));
  396. }
  397. }
  398. else
  399. {
  400. throw Logger.WriteException(new SessionRemoteException(this, ListToString(Output)));
  401. }
  402. }
  403. catch (Exception e)
  404. {
  405. Logger.WriteLine("Exception: {0}", e);
  406. throw;
  407. }
  408. finally
  409. {
  410. Cleanup();
  411. }
  412. return result;
  413. }
  414. }
  415. private static string NormalizeIdent(string algorithm)
  416. {
  417. return algorithm.Replace("-", string.Empty);
  418. }
  419. public void Close()
  420. {
  421. using (Logger.CreateCallstackAndLock())
  422. {
  423. CheckOpened();
  424. Cleanup();
  425. }
  426. }
  427. public RemoteDirectoryInfo ListDirectory(string path)
  428. {
  429. using (Logger.CreateCallstackAndLock())
  430. {
  431. CheckOpened();
  432. WriteCommand(string.Format(CultureInfo.InvariantCulture, "ls -- \"{0}\"", Tools.ArgumentEscape(IncludeTrailingSlash(path))));
  433. RemoteDirectoryInfo result = new RemoteDirectoryInfo();
  434. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  435. using (ElementLogReader lsReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("ls", LogReadFlags.ThrowFailures))
  436. {
  437. string destination = null;
  438. if (lsReader.TryWaitForEmptyElement("destination", 0))
  439. {
  440. lsReader.GetEmptyElementValue("destination", out destination);
  441. }
  442. if ((destination != null) && lsReader.TryWaitForNonEmptyElement("files", 0))
  443. {
  444. destination = IncludeTrailingSlash(destination);
  445. using (ElementLogReader filesReader = lsReader.CreateLogReader())
  446. {
  447. while (filesReader.TryWaitForNonEmptyElement("file", 0))
  448. {
  449. RemoteFileInfo fileInfo = new RemoteFileInfo();
  450. using (ElementLogReader fileReader = filesReader.CreateLogReader())
  451. {
  452. while (fileReader.Read(0))
  453. {
  454. if (fileReader.GetEmptyElementValue("filename", out string value))
  455. {
  456. fileInfo.Name = value;
  457. fileInfo.FullName = destination + value;
  458. }
  459. else
  460. {
  461. ReadFile(fileInfo, fileReader);
  462. }
  463. }
  464. result.AddFile(fileInfo);
  465. }
  466. }
  467. }
  468. lsReader.ReadToEnd(LogReadFlags.ThrowFailures);
  469. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  470. }
  471. else
  472. {
  473. // "files" not found, keep reading, we expect "failure"
  474. // This happens only in case of fatal errors,
  475. // in case of normal error (non existing folder),
  476. // the "failure" is caught in "group" already, before the "ls".
  477. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  478. // only if not "failure", throw "files" not found
  479. throw Logger.WriteException(SessionLocalException.CreateElementNotFound(this, "files"));
  480. }
  481. }
  482. return result;
  483. }
  484. }
  485. private IEnumerable<RemoteFileInfo> DoEnumerateRemoteFiles(string path, Regex regex, EnumerationOptions options, bool throwReadErrors)
  486. {
  487. Logger.WriteLine("Starting enumeration of {0} ...", path);
  488. bool allDirectories = ((options & EnumerationOptions.AllDirectories) == EnumerationOptions.AllDirectories);
  489. bool matchDirectories = ((options & EnumerationOptions.MatchDirectories) == EnumerationOptions.MatchDirectories);
  490. bool enumerateDirectories = ((options & EnumerationOptions.EnumerateDirectories) == EnumerationOptions.EnumerateDirectories);
  491. if (enumerateDirectories && !allDirectories)
  492. {
  493. throw Logger.WriteException(new ArgumentException("Cannot use enumeration option EnumerateDirectories without AllDirectories"));
  494. }
  495. if (enumerateDirectories && matchDirectories)
  496. {
  497. throw Logger.WriteException(new ArgumentException("Cannot combine enumeration option EnumerateDirectories with MatchDirectories"));
  498. }
  499. RemoteDirectoryInfo directoryInfo;
  500. try
  501. {
  502. // Need to use guarded method for the listing, see a comment in EnumerateRemoteFiles
  503. directoryInfo = ListDirectory(path);
  504. }
  505. catch (SessionRemoteException)
  506. {
  507. if (throwReadErrors)
  508. {
  509. throw;
  510. }
  511. else
  512. {
  513. directoryInfo = null;
  514. }
  515. }
  516. if (directoryInfo != null)
  517. {
  518. foreach (RemoteFileInfo fileInfo in directoryInfo.Files)
  519. {
  520. if (!fileInfo.IsThisDirectory && !fileInfo.IsParentDirectory)
  521. {
  522. bool matches = regex.IsMatch(fileInfo.Name);
  523. bool enumerate;
  524. if (!fileInfo.IsDirectory)
  525. {
  526. enumerate = matches;
  527. }
  528. else
  529. {
  530. if (enumerateDirectories)
  531. {
  532. enumerate = true;
  533. }
  534. else if (matchDirectories)
  535. {
  536. enumerate = matches;
  537. }
  538. else
  539. {
  540. enumerate = false;
  541. }
  542. }
  543. if (enumerate)
  544. {
  545. Logger.WriteLine("Enumerating {0}", fileInfo.FullName);
  546. yield return fileInfo;
  547. }
  548. if (fileInfo.IsDirectory && allDirectories)
  549. {
  550. foreach (RemoteFileInfo fileInfo2 in DoEnumerateRemoteFiles(RemotePath.Combine(path, fileInfo.Name), regex, options, false))
  551. {
  552. yield return fileInfo2;
  553. }
  554. }
  555. }
  556. }
  557. }
  558. Logger.WriteLine("Ended enumeration of {0}", path);
  559. }
  560. public IEnumerable<RemoteFileInfo> EnumerateRemoteFiles(string path, string mask, EnumerationOptions options)
  561. {
  562. // Note that this method exits as soon as DoEnumerateRemoteFiles is entered,
  563. // so the Session object is not guarded during the whole enumeration.
  564. // Though it should not matter as it uses only guarded methods (ListDirectory)
  565. // for the actual work on the session
  566. using (Logger.CreateCallstackAndLock())
  567. {
  568. CheckOpened();
  569. Regex regex = MaskToRegex(mask);
  570. return DoEnumerateRemoteFiles(path, regex, options, true);
  571. }
  572. }
  573. internal static Regex MaskToRegex(string mask)
  574. {
  575. if (string.IsNullOrEmpty(mask) ||
  576. // *.* has to match even filename without dot
  577. (mask == "*.*"))
  578. {
  579. mask = "*";
  580. }
  581. return
  582. new Regex(
  583. '^' +
  584. mask
  585. .Replace(".", "[.]")
  586. .Replace("*", ".*")
  587. .Replace("?", ".") +
  588. '$',
  589. RegexOptions.IgnoreCase);
  590. }
  591. public TransferOperationResult PutFiles(string localPath, string remotePath, bool remove = false, TransferOptions options = null)
  592. {
  593. using (Logger.CreateCallstackAndLock())
  594. {
  595. return DoPutFiles(localPath, remotePath, remove, options);
  596. }
  597. }
  598. public TransferOperationResult DoPutFiles(string localPath, string remotePath, bool remove, TransferOptions options)
  599. {
  600. using (Logger.CreateCallstack())
  601. {
  602. if (options == null)
  603. {
  604. options = new TransferOptions();
  605. }
  606. CheckOpened();
  607. WriteCommand(
  608. string.Format(CultureInfo.InvariantCulture,
  609. "put {0} {1} -- \"{2}\" \"{3}\"",
  610. BooleanSwitch(remove, "delete"), options.ToSwitches(),
  611. Tools.ArgumentEscape(localPath), Tools.ArgumentEscape(remotePath)));
  612. TransferOperationResult result = new TransferOperationResult();
  613. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  614. using (RegisterOperationResult(result))
  615. using (CreateProgressHandler())
  616. {
  617. TransferEventArgs args = null;
  618. bool mkdir = false;
  619. while (groupReader.Read(0))
  620. {
  621. if (groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag))
  622. {
  623. AddTransfer(result, args);
  624. args = TransferEventArgs.Read(ProgressSide.Local, groupReader);
  625. mkdir = false;
  626. }
  627. else if (groupReader.IsNonEmptyElement(TransferEventArgs.MkDirTag))
  628. {
  629. AddTransfer(result, args);
  630. args = null;
  631. mkdir = true;
  632. // For now, silently ignoring results (even errors)
  633. // of mkdir operation, including future chmod/touch
  634. }
  635. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  636. {
  637. if (!mkdir)
  638. {
  639. if (args == null)
  640. {
  641. throw Logger.WriteException(new InvalidOperationException("Tag chmod before tag upload"));
  642. }
  643. args.Chmod = ChmodEventArgs.Read(groupReader);
  644. }
  645. }
  646. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  647. {
  648. if (!mkdir)
  649. {
  650. if (args == null)
  651. {
  652. throw Logger.WriteException(new InvalidOperationException("Tag touch before tag upload"));
  653. }
  654. args.Touch = TouchEventArgs.Read(groupReader);
  655. }
  656. }
  657. }
  658. AddTransfer(result, args);
  659. }
  660. return result;
  661. }
  662. }
  663. public TransferOperationResult PutFilesToDirectory(
  664. string localDirectory, string remoteDirectory, string filemask = null, bool remove = false, TransferOptions options = null)
  665. {
  666. // Not locking, locked in PutFiles
  667. using (Logger.CreateCallstack())
  668. {
  669. if (localDirectory == null)
  670. {
  671. throw Logger.WriteException(new ArgumentNullException(nameof(localDirectory)));
  672. }
  673. if (remoteDirectory == null)
  674. {
  675. throw Logger.WriteException(new ArgumentNullException(nameof(remoteDirectory)));
  676. }
  677. if (string.IsNullOrEmpty(filemask))
  678. {
  679. filemask = "*";
  680. }
  681. string localPath = Path.Combine(localDirectory, filemask);
  682. const string remoteSeparator = "/";
  683. string remotePath =
  684. remoteDirectory +
  685. (remoteDirectory.EndsWith(remoteSeparator, StringComparison.Ordinal) ? string.Empty : remoteSeparator);
  686. return PutFiles(localPath, remotePath, remove, options);
  687. }
  688. }
  689. public TransferEventArgs PutFileToDirectory(string localFilePath, string remoteDirectory, bool remove = false, TransferOptions options = null)
  690. {
  691. // Not locking, locked in PutFiles (within PutFilesToDirectory)
  692. using (Logger.CreateCallstack())
  693. {
  694. if (!File.Exists(localFilePath))
  695. {
  696. throw Logger.WriteException(new FileNotFoundException($"File {localFilePath} does not exist", localFilePath));
  697. }
  698. TransferOperationResult operationResult = PutEntryToDirectory(localFilePath, remoteDirectory, remove, options);
  699. return GetOnlyFileOperation(operationResult.Transfers);
  700. }
  701. }
  702. public void PutFile(Stream stream, string remoteFilePath, TransferOptions options = null)
  703. {
  704. using (Logger.CreateCallstackAndLock())
  705. {
  706. if (remoteFilePath == null)
  707. {
  708. throw Logger.WriteException(new ArgumentNullException(nameof(remoteFilePath)));
  709. }
  710. if (_process.StdIn != null)
  711. {
  712. throw Logger.WriteException(new InvalidOperationException("Already uploading from a stream"));
  713. }
  714. _process.StdIn = stream ?? throw Logger.WriteException(new ArgumentNullException(nameof(stream)));
  715. try
  716. {
  717. remoteFilePath = RemotePath.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)
  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. Cleanup();
  1992. throw Logger.WriteException(new TimeoutException(message));
  1993. }
  1994. if (_aborted)
  1995. {
  1996. throw Logger.WriteException(new SessionLocalException(this, "Aborted."));
  1997. }
  1998. if ((_process.StdOut != null) && _process.StdOut.ReadAvailable(1))
  1999. {
  2000. throw new StdOutException();
  2001. }
  2002. }
  2003. private void RaiseFileTransferredEvent(TransferEventArgs args)
  2004. {
  2005. Logger.WriteLine("FileTransferredEvent: [{0}]", args.FileName);
  2006. FileTransferred?.Invoke(this, args);
  2007. }
  2008. internal void RaiseFailed(SessionRemoteException e)
  2009. {
  2010. Logger.WriteLine("Failed: [{0}]", e);
  2011. if ((Failed != null) && !_ignoreFailed)
  2012. {
  2013. Failed(this, new FailedEventArgs { Error = e });
  2014. }
  2015. foreach (OperationResultBase operationResult in _operationResults)
  2016. {
  2017. operationResult.AddFailure(e);
  2018. }
  2019. }
  2020. private void CheckNotDisposed()
  2021. {
  2022. if (_disposed)
  2023. {
  2024. throw Logger.WriteException(new InvalidOperationException("Object is disposed"));
  2025. }
  2026. if (_aborted)
  2027. {
  2028. throw Logger.WriteException(new InvalidOperationException("Session was aborted"));
  2029. }
  2030. }
  2031. private void CheckOpened()
  2032. {
  2033. if (!Opened)
  2034. {
  2035. throw Logger.WriteException(new InvalidOperationException("Session is not opened"));
  2036. }
  2037. }
  2038. private void CheckNotOpened()
  2039. {
  2040. if (Opened)
  2041. {
  2042. throw Logger.WriteException(new InvalidOperationException("Session is already opened"));
  2043. }
  2044. }
  2045. private void RaiseOutputDataReceived(string data, bool error)
  2046. {
  2047. Logger.WriteLine("Output: [{0}]", data);
  2048. OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(data, error));
  2049. }
  2050. internal void DispatchEvents(int interval)
  2051. {
  2052. DateTime start = DateTime.Now;
  2053. while (_eventsEvent.WaitOne(interval, false))
  2054. {
  2055. lock (_events)
  2056. {
  2057. foreach (Action action in _events)
  2058. {
  2059. action();
  2060. }
  2061. _events.Clear();
  2062. }
  2063. interval -= (int) (DateTime.Now - start).TotalMilliseconds;
  2064. if (interval < 0)
  2065. {
  2066. break;
  2067. }
  2068. start = DateTime.Now;
  2069. }
  2070. }
  2071. private IDisposable RegisterOperationResult(OperationResultBase operationResult)
  2072. {
  2073. _operationResults.Add(operationResult);
  2074. return new OperationResultGuard(this, operationResult);
  2075. }
  2076. internal void UnregisterOperationResult(OperationResultBase operationResult)
  2077. {
  2078. // GetFile relies on this not to throw
  2079. _operationResults.Remove(operationResult);
  2080. }
  2081. internal bool WantsProgress
  2082. {
  2083. get
  2084. {
  2085. return (_fileTransferProgress != null);
  2086. }
  2087. }
  2088. private IDisposable CreateProgressHandler()
  2089. {
  2090. using (Logger.CreateCallstack())
  2091. {
  2092. _progressHandling++;
  2093. return new ProgressHandler(this);
  2094. }
  2095. }
  2096. internal void DisableProgressHandling()
  2097. {
  2098. using (Logger.CreateCallstack())
  2099. {
  2100. if (_progressHandling <= 0)
  2101. {
  2102. throw Logger.WriteException(new InvalidOperationException("Progress handling not enabled"));
  2103. }
  2104. // make sure we process all pending progress events
  2105. DispatchEvents(0);
  2106. _progressHandling--;
  2107. }
  2108. }
  2109. internal void ProcessChoice(QueryReceivedEventArgs args)
  2110. {
  2111. if (_queryReceived != null) // optimization
  2112. {
  2113. _choiceEvent.Reset();
  2114. ScheduleEvent(() => Choice(args));
  2115. _choiceEvent.WaitOne();
  2116. }
  2117. }
  2118. private void Choice(QueryReceivedEventArgs args)
  2119. {
  2120. _queryReceived?.Invoke(this, args);
  2121. _choiceEvent.Set();
  2122. }
  2123. internal void ProcessProgress(FileTransferProgressEventArgs args)
  2124. {
  2125. ScheduleEvent(() => Progress(args));
  2126. }
  2127. private void Progress(FileTransferProgressEventArgs args)
  2128. {
  2129. if ((_progressHandling >= 0) && WantsProgress)
  2130. {
  2131. _fileTransferProgress(this, args);
  2132. if (args.Cancel)
  2133. {
  2134. _process.Cancel();
  2135. }
  2136. }
  2137. }
  2138. private void SetupTempPath()
  2139. {
  2140. using (Logger.CreateCallstack())
  2141. {
  2142. if (!string.IsNullOrEmpty(_xmlLogPath))
  2143. {
  2144. bool exists = File.Exists(_xmlLogPath);
  2145. Logger.WriteLine("Configured temporary file: {0} - Exists [{1}]", _xmlLogPath, exists);
  2146. if (exists)
  2147. {
  2148. throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Configured temporary file {0} already exists", _xmlLogPath)));
  2149. }
  2150. }
  2151. else
  2152. {
  2153. string path = Path.GetTempPath();
  2154. Logger.WriteLine("Temporary folder: {0}", path);
  2155. string process = Process.GetCurrentProcess().Id.ToString("X4", CultureInfo.InvariantCulture);
  2156. string instance = GetHashCode().ToString("X8", CultureInfo.InvariantCulture);
  2157. string filename;
  2158. bool exists;
  2159. do
  2160. {
  2161. string uniqueStr = (_logUnique > 0 ? "." + _logUnique.ToString(CultureInfo.InvariantCulture) : string.Empty);
  2162. ++_logUnique;
  2163. filename = Path.Combine(path, "wscp" + process + "." + instance + uniqueStr + ".tmp");
  2164. exists = File.Exists(filename);
  2165. Logger.WriteLine("Temporary file [{0}] - Exists [{1}]", filename, exists);
  2166. }
  2167. while (exists);
  2168. _xmlLogPath = filename;
  2169. }
  2170. }
  2171. }
  2172. #if !NETSTANDARD
  2173. private static string GetTypeLibKey(Type t)
  2174. {
  2175. return "CLSID\\{" + t.GUID.ToString().ToUpperInvariant() + "}\\TypeLib";
  2176. }
  2177. #endif
  2178. FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
  2179. {
  2180. using (Logger.CreateCallstack())
  2181. {
  2182. Logger.WriteLine("Name [{0}]", name);
  2183. FieldInfo result = GetType().GetField(name, bindingAttr);
  2184. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2185. return result;
  2186. }
  2187. }
  2188. FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
  2189. {
  2190. using (Logger.CreateCallstack())
  2191. {
  2192. FieldInfo[] result = GetType().GetFields(bindingAttr);
  2193. Logger.WriteLine("Fields [{0}]", result.Length);
  2194. return result;
  2195. }
  2196. }
  2197. MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
  2198. {
  2199. using (Logger.CreateCallstack())
  2200. {
  2201. Logger.WriteLine("Name [{0}]", name);
  2202. MemberInfo[] result = GetType().GetMember(name, bindingAttr);
  2203. Logger.WriteLine("Result [{0}]", result.Length);
  2204. return result;
  2205. }
  2206. }
  2207. MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
  2208. {
  2209. using (Logger.CreateCallstack())
  2210. {
  2211. MemberInfo[] result = GetType().GetMembers(bindingAttr);
  2212. Logger.WriteLine("Result [{0}]", result.Length);
  2213. return result;
  2214. }
  2215. }
  2216. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
  2217. {
  2218. using (Logger.CreateCallstack())
  2219. {
  2220. Logger.WriteLine("Name [{0}]", name);
  2221. MethodInfo result = GetType().GetMethod(name, bindingAttr);
  2222. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2223. return result;
  2224. }
  2225. }
  2226. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
  2227. {
  2228. using (Logger.CreateCallstack())
  2229. {
  2230. Logger.WriteLine("Name [{0}]", name);
  2231. MethodInfo result = GetType().GetMethod(name, bindingAttr, binder, types, modifiers);
  2232. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2233. return result;
  2234. }
  2235. }
  2236. MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
  2237. {
  2238. using (Logger.CreateCallstack())
  2239. {
  2240. MethodInfo[] result = GetType().GetMethods(bindingAttr);
  2241. Logger.WriteLine("Result [{0}]", result.Length);
  2242. return result;
  2243. }
  2244. }
  2245. PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
  2246. {
  2247. using (Logger.CreateCallstack())
  2248. {
  2249. PropertyInfo[] result = GetType().GetProperties(bindingAttr);
  2250. Logger.WriteLine("Result [{0}]", result.Length);
  2251. return result;
  2252. }
  2253. }
  2254. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
  2255. {
  2256. using (Logger.CreateCallstack())
  2257. {
  2258. Logger.WriteLine("Name [{0}]", name);
  2259. PropertyInfo result = GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
  2260. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2261. return result;
  2262. }
  2263. }
  2264. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
  2265. {
  2266. using (Logger.CreateCallstack())
  2267. {
  2268. Logger.WriteLine("Name [{0}]", name);
  2269. PropertyInfo result = GetType().GetProperty(name, bindingAttr);
  2270. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2271. return result;
  2272. }
  2273. }
  2274. private void LogInvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  2275. {
  2276. Logger.WriteLine("Name [{0}]", name);
  2277. Logger.WriteLine("BindingFlags [{0}]", invokeAttr);
  2278. Logger.WriteLine("Binder [{0}]", binder);
  2279. Logger.WriteLine("Target [{0}]", target);
  2280. if (args != null)
  2281. {
  2282. Logger.WriteLine("Args [{0}] [{1}]", args.Length, modifiers != null ? modifiers.Length.ToString(CultureInfo.InvariantCulture) : "null");
  2283. for (int i = 0; i < args.Length; ++i)
  2284. {
  2285. Logger.WriteLine("Arg [{0}] [{1}] [{1}] [{2}]", i, args[i], (args[i] != null ? args[i].GetType().ToString() : "null"), (modifiers != null ? modifiers[i].ToString() : "null"));
  2286. }
  2287. }
  2288. Logger.WriteLine("Culture [{0}]", culture);
  2289. if (namedParameters != null)
  2290. {
  2291. foreach (string namedParameter in namedParameters)
  2292. {
  2293. Logger.WriteLine("NamedParameter [{0}]", namedParameter);
  2294. }
  2295. }
  2296. }
  2297. object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  2298. {
  2299. using (Logger.CreateCallstack())
  2300. {
  2301. object result;
  2302. try
  2303. {
  2304. bool wasLogging = Logger.Logging;
  2305. if (wasLogging)
  2306. {
  2307. // factored out to reduce this method complexity
  2308. LogInvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  2309. }
  2310. if (target == null)
  2311. {
  2312. throw Logger.WriteException(new ArgumentNullException(nameof(target)));
  2313. }
  2314. Type type = target.GetType();
  2315. // RuntimeType.InvokeMember below calls into Binder.BindToMethod (Binder is OleAutBinder)
  2316. // that fails to match method, if integer value is provided to enum argument
  2317. // (SynchronizeDirectories with its SynchronizationMode and SynchronizationCriteria).
  2318. // This does not happen if we do not implement IReflect, though no idea why.
  2319. // So as a workaround we check, if the method has no overloads (what is always true for Session),
  2320. // and call the only instance directly.
  2321. // Calling MethodInfo.Invoke with int values for enum arguments works.
  2322. // Only as a fallback, we call InvokeMember (what is currently actually used only when
  2323. // the method with given name does not exist at all)
  2324. MethodInfo method = null;
  2325. PropertyInfo property = null;
  2326. // would be way too difficult to implement the below involving named arguments
  2327. if (namedParameters == null)
  2328. {
  2329. try
  2330. {
  2331. BindingFlags bindingFlags = invokeAttr | BindingFlags.Instance | BindingFlags.Public;
  2332. method = type.GetMethod(name, bindingFlags);
  2333. if (args == null)
  2334. {
  2335. throw Logger.WriteException(new ArgumentNullException(nameof(args)));
  2336. }
  2337. if (method != null)
  2338. {
  2339. // MethodInfo.Invoke does not fill-in optional arguments (contrary to RuntimeType.InvokeMember)
  2340. ParameterInfo[] parameters = method.GetParameters();
  2341. if (args.Length < parameters.Length)
  2342. {
  2343. Logger.WriteLine("Provided less parameters [{0}] than defined [{1}]", args.Length, parameters.Length);
  2344. object[] args2 = new object[parameters.Length];
  2345. for (int i = 0; i < parameters.Length; i++)
  2346. {
  2347. if (i < args.Length)
  2348. {
  2349. args2[i] = args[i];
  2350. }
  2351. else
  2352. {
  2353. if (!parameters[i].IsOptional)
  2354. {
  2355. Logger.WriteLine("Parameter [{0}] of [{1}] is not optional", i, method);
  2356. args2 = null;
  2357. break;
  2358. }
  2359. else
  2360. {
  2361. Logger.WriteLine("Adding default value [{0}] for optional parameter [{1}]", parameters[i].DefaultValue, i);
  2362. args2[i] = parameters[i].DefaultValue;
  2363. }
  2364. }
  2365. }
  2366. if (args2 != null)
  2367. {
  2368. args = args2;
  2369. }
  2370. }
  2371. }
  2372. else if (args.Length == 1) // sanity check
  2373. {
  2374. property = type.GetProperty(name, bindingFlags);
  2375. }
  2376. }
  2377. catch (AmbiguousMatchException e)
  2378. {
  2379. Logger.WriteLine("Unexpected ambiguous match [{0}]", e.Message);
  2380. }
  2381. }
  2382. if (method != null)
  2383. {
  2384. Logger.WriteLine("Invoking unambiguous method [{0}]", method);
  2385. result = method.Invoke(target, invokeAttr, binder, args, culture);
  2386. }
  2387. else if (property != null)
  2388. {
  2389. Logger.WriteLine("Setting unambiguous property [{0}]", property);
  2390. property.SetValue(target, args[0], invokeAttr, binder, null, culture);
  2391. result = null;
  2392. }
  2393. else
  2394. {
  2395. Logger.WriteLine("Invoking ambiguous/non-existing method 2 [{0}]", name);
  2396. result = type.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  2397. }
  2398. if (!wasLogging && Logger.Logging)
  2399. {
  2400. Logger.WriteLine("Invoking member {0} enabled debug logging", name);
  2401. // Might call LogInvokeMember here, but it's not really useful.
  2402. }
  2403. Logger.WriteLine("Result [{0}] [{1}]", result, (result != null ? result.GetType().ToString() : "null"));
  2404. }
  2405. catch (Exception e)
  2406. {
  2407. Logger.WriteLine("Error [{0}]", e);
  2408. throw;
  2409. }
  2410. return result;
  2411. }
  2412. }
  2413. Type IReflect.UnderlyingSystemType
  2414. {
  2415. get { return GetType(); }
  2416. }
  2417. internal const string Namespace = "http://winscp.net/schema/session/1.0";
  2418. internal Logger Logger { get; private set; }
  2419. internal bool GuardProcessWithJobInternal { get { return _guardProcessWithJob; } set { CheckNotOpened(); _guardProcessWithJob = value; } }
  2420. internal bool TestHandlesClosedInternal { get; set; }
  2421. internal Dictionary<string, string> RawConfiguration { get; private set; }
  2422. internal bool DefaultConfigurationInternal { get { return _defaultConfiguration; } }
  2423. internal string IniFilePathInternal { get { return _iniFilePath; } }
  2424. private ExeSessionProcess _process;
  2425. private DateTime _lastOutput;
  2426. private ElementLogReader _reader;
  2427. private SessionLogReader _logReader;
  2428. private readonly IList<OperationResultBase> _operationResults;
  2429. private readonly IList<Action> _events;
  2430. private AutoResetEvent _eventsEvent;
  2431. private ManualResetEvent _choiceEvent;
  2432. private bool _disposed;
  2433. private string _executablePath;
  2434. private string _additionalExecutableArguments;
  2435. private bool _defaultConfiguration;
  2436. private bool _disableVersionCheck;
  2437. private string _iniFilePath;
  2438. private TimeSpan _reconnectTime;
  2439. private string _sessionLogPath;
  2440. private bool _aborted;
  2441. private int _logUnique;
  2442. private string _xmlLogPath;
  2443. private FileTransferProgressEventHandler _fileTransferProgress;
  2444. private int _progressHandling;
  2445. private bool _guardProcessWithJob;
  2446. private string _homePath;
  2447. #if !NETSTANDARD
  2448. private string _executableProcessUserName;
  2449. private SecureString _executableProcessPassword;
  2450. #endif
  2451. private StringCollection _error;
  2452. private bool _ignoreFailed;
  2453. private TimeSpan _sessionTimeout;
  2454. private QueryReceivedEventHandler _queryReceived;
  2455. }
  2456. }