Session.cs 99 KB

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