Session.cs 87 KB

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