Session.cs 91 KB

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