Session.cs 90 KB

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