Session.cs 116 KB

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