Session.cs 89 KB

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