Session.cs 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227
  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. DoGetFileInfo(path);
  817. return true;
  818. }
  819. catch (SessionRemoteException)
  820. {
  821. return false;
  822. }
  823. }
  824. }
  825. public byte[] CalculateFileChecksum(string algorithm, string path)
  826. {
  827. using (Logger.CreateCallstackAndLock())
  828. {
  829. WriteCommand(string.Format(CultureInfo.InvariantCulture, "checksum -- \"{0}\" \"{1}\"", Tools.ArgumentEscape(algorithm), Tools.ArgumentEscape(path)));
  830. string hex = null;
  831. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  832. using (ElementLogReader checksumReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("checksum", LogReadFlags.ThrowFailures))
  833. {
  834. while (checksumReader.Read(0))
  835. {
  836. string value;
  837. if (checksumReader.GetEmptyElementValue("checksum", out value))
  838. {
  839. hex = value;
  840. }
  841. }
  842. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  843. }
  844. int len = hex.Length;
  845. if ((len % 2) != 0)
  846. {
  847. string error = string.Format(CultureInfo.CurrentCulture, "Invalid string representation of checksum - {0}", hex);
  848. throw Logger.WriteException(new SessionLocalException(this, error));
  849. }
  850. int count = len / 2;
  851. byte[] bytes = new byte[count];
  852. for (int i = 0; i < count; i++)
  853. {
  854. bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
  855. }
  856. return bytes;
  857. }
  858. }
  859. public void CreateDirectory(string path)
  860. {
  861. using (Logger.CreateCallstackAndLock())
  862. {
  863. CheckOpened();
  864. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mkdir \"{0}\"", Tools.ArgumentEscape(path)));
  865. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  866. using (ElementLogReader mkdirReader = groupReader.WaitForNonEmptyElementAndCreateLogReader(TransferEventArgs.MkDirTag, LogReadFlags.ThrowFailures))
  867. {
  868. ReadElement(mkdirReader, 0);
  869. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  870. }
  871. }
  872. }
  873. public void MoveFile(string sourcePath, string targetPath)
  874. {
  875. using (Logger.CreateCallstackAndLock())
  876. {
  877. CheckOpened();
  878. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mv \"{0}\" \"{1}\"", Tools.ArgumentEscape(sourcePath), Tools.ArgumentEscape(targetPath)));
  879. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  880. {
  881. if (!groupReader.TryWaitForNonEmptyElement("mv", LogReadFlags.ThrowFailures))
  882. {
  883. throw Logger.WriteException(new SessionRemoteException(this, string.Format(CultureInfo.CurrentCulture, "{0} not found.", sourcePath)));
  884. }
  885. else
  886. {
  887. using (ElementLogReader mvReader = groupReader.CreateLogReader())
  888. {
  889. ReadElement(mvReader, 0);
  890. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  891. }
  892. }
  893. }
  894. }
  895. }
  896. // This is not static method only to make it visible to COM
  897. public string EscapeFileMask(string fileMask)
  898. {
  899. if (fileMask == null)
  900. {
  901. throw Logger.WriteException(new ArgumentNullException("fileMask"));
  902. }
  903. int lastSlash = fileMask.LastIndexOf('/');
  904. string path = lastSlash > 0 ? fileMask.Substring(0, lastSlash + 1) : string.Empty;
  905. string mask = lastSlash > 0 ? fileMask.Substring(lastSlash + 1) : fileMask;
  906. // Keep in sync with EscapeFileMask in GenerateUrl.cpp
  907. mask = mask.Replace("[", "[[]").Replace("*", "[*]").Replace("?", "[?]");
  908. return path + mask;
  909. }
  910. public string TranslateRemotePathToLocal(string remotePath, string remoteRoot, string localRoot)
  911. {
  912. if (remotePath == null)
  913. {
  914. throw Logger.WriteException(new ArgumentNullException("remotePath"));
  915. }
  916. if (remoteRoot == null)
  917. {
  918. throw Logger.WriteException(new ArgumentNullException("remoteRoot"));
  919. }
  920. if (localRoot == null)
  921. {
  922. throw Logger.WriteException(new ArgumentNullException("localRoot"));
  923. }
  924. if ((localRoot.Length > 0) && !localRoot.EndsWith("\\", StringComparison.Ordinal))
  925. {
  926. localRoot += "\\";
  927. }
  928. // not adding to empty root paths, because the path may not even start with slash
  929. if ((remoteRoot.Length > 0) && !remoteRoot.EndsWith("/", StringComparison.Ordinal))
  930. {
  931. remoteRoot += "/";
  932. }
  933. string localPath;
  934. // special case
  935. if (remotePath == remoteRoot)
  936. {
  937. localPath = localRoot;
  938. }
  939. else
  940. {
  941. if (!remotePath.StartsWith(remoteRoot, StringComparison.Ordinal))
  942. {
  943. throw Logger.WriteException(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "{0} does not start with {1}", remotePath, remoteRoot)));
  944. }
  945. string subPath = remotePath.Substring(remoteRoot.Length);
  946. // can happen only when remoteRoot is empty
  947. if (subPath.StartsWith("/", StringComparison.Ordinal))
  948. {
  949. subPath = subPath.Substring(1);
  950. }
  951. subPath = subPath.Replace('/', '\\');
  952. localPath = localRoot + subPath;
  953. }
  954. return localPath;
  955. }
  956. public string TranslateLocalPathToRemote(string localPath, string localRoot, string remoteRoot)
  957. {
  958. if (localPath == null)
  959. {
  960. throw Logger.WriteException(new ArgumentNullException("localPath"));
  961. }
  962. if (localRoot == null)
  963. {
  964. throw Logger.WriteException(new ArgumentNullException("localRoot"));
  965. }
  966. if (remoteRoot == null)
  967. {
  968. throw Logger.WriteException(new ArgumentNullException("remoteRoot"));
  969. }
  970. if ((localRoot.Length > 0) && !localRoot.EndsWith("\\", StringComparison.Ordinal))
  971. {
  972. localRoot += "\\";
  973. }
  974. // not adding to empty root paths, because the path may not even start with slash
  975. if ((remoteRoot.Length > 0) && !remoteRoot.EndsWith("/", StringComparison.Ordinal))
  976. {
  977. remoteRoot += "/";
  978. }
  979. string remotePath;
  980. // special case
  981. if (localPath == localRoot)
  982. {
  983. remotePath = remoteRoot;
  984. }
  985. else
  986. {
  987. if (!localPath.StartsWith(localRoot, StringComparison.Ordinal))
  988. {
  989. throw Logger.WriteException(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "{0} does not start with {1}", localPath, localRoot)));
  990. }
  991. string subPath = localPath.Substring(localRoot.Length);
  992. // can happen only when localRoot is empty
  993. if (subPath.StartsWith("\\", StringComparison.Ordinal))
  994. {
  995. subPath = subPath.Substring(1);
  996. }
  997. subPath = subPath.Replace('\\', '/');
  998. remotePath = remoteRoot + subPath;
  999. }
  1000. return remotePath;
  1001. }
  1002. public string CombinePaths(string path1, string path2)
  1003. {
  1004. if (path1 == null)
  1005. {
  1006. throw Logger.WriteException(new ArgumentNullException("path1"));
  1007. }
  1008. if (path2 == null)
  1009. {
  1010. throw Logger.WriteException(new ArgumentNullException("path2"));
  1011. }
  1012. string result;
  1013. if (path2.StartsWith("/", StringComparison.Ordinal))
  1014. {
  1015. result = path2;
  1016. }
  1017. else
  1018. {
  1019. result =
  1020. path1 +
  1021. ((path1.Length == 0) || (path2.Length == 0) || path1.EndsWith("/", StringComparison.Ordinal) ? string.Empty : "/") +
  1022. path2;
  1023. }
  1024. return result;
  1025. }
  1026. public void AddRawConfiguration(string setting, string value)
  1027. {
  1028. CheckNotOpened();
  1029. RawConfiguration.Add(setting, value);
  1030. }
  1031. [ComRegisterFunction]
  1032. private static void ComRegister(Type t)
  1033. {
  1034. string subKey = GetTypeLibKey(t);
  1035. Assembly assembly = Assembly.GetAssembly(t);
  1036. object[] attributes = assembly.GetCustomAttributes(typeof(GuidAttribute), false);
  1037. if (attributes.Length == 0)
  1038. {
  1039. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Cannot find {0} attribute for assembly {1}", typeof(GuidAttribute), assembly));
  1040. }
  1041. GuidAttribute guidAttribute = (GuidAttribute)attributes[0];
  1042. Registry.ClassesRoot.CreateSubKey(subKey).SetValue(null, guidAttribute.Value);
  1043. }
  1044. [ComUnregisterFunction]
  1045. private static void ComUnregister(Type t)
  1046. {
  1047. string subKey = GetTypeLibKey(t);
  1048. Registry.ClassesRoot.DeleteSubKey(subKey, false);
  1049. }
  1050. private void ReadFile(RemoteFileInfo fileInfo, CustomLogReader fileReader)
  1051. {
  1052. using (Logger.CreateCallstack())
  1053. {
  1054. string value;
  1055. if (fileReader.GetEmptyElementValue("type", out value))
  1056. {
  1057. fileInfo.FileType = value[0];
  1058. }
  1059. else if (fileReader.GetEmptyElementValue("size", out value))
  1060. {
  1061. fileInfo.Length = long.Parse(value, CultureInfo.InvariantCulture);
  1062. }
  1063. else if (fileReader.GetEmptyElementValue("modification", out value))
  1064. {
  1065. fileInfo.LastWriteTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Local);
  1066. }
  1067. else if (fileReader.GetEmptyElementValue("permissions", out value))
  1068. {
  1069. fileInfo.FilePermissions = FilePermissions.CreateReadOnlyFromText(value);
  1070. }
  1071. else if (fileReader.GetEmptyElementValue("owner", out value))
  1072. {
  1073. fileInfo.Owner = value;
  1074. }
  1075. else if (fileReader.GetEmptyElementValue("group", out value))
  1076. {
  1077. fileInfo.Group = value;
  1078. }
  1079. }
  1080. }
  1081. internal static string BooleanSwitch(bool flag, string name)
  1082. {
  1083. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", name) : null;
  1084. }
  1085. internal static string BooleanSwitch(bool flag, string onName, string offName)
  1086. {
  1087. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", onName) : string.Format(CultureInfo.InvariantCulture, "-{0}", offName);
  1088. }
  1089. private void AddSynchronizationTransfer(SynchronizationResult result, TransferEventArgs transfer)
  1090. {
  1091. if (transfer != null)
  1092. {
  1093. if (transfer.Side == ProgressSide.Local)
  1094. {
  1095. result.AddUpload(transfer);
  1096. }
  1097. else
  1098. {
  1099. result.AddDownload(transfer);
  1100. }
  1101. RaiseFileTransferredEvent(transfer);
  1102. }
  1103. }
  1104. private static string IncludeTrailingSlash(string path)
  1105. {
  1106. if (!string.IsNullOrEmpty(path) && !path.EndsWith("/", StringComparison.Ordinal))
  1107. {
  1108. path += '/';
  1109. }
  1110. return path;
  1111. }
  1112. private void Cleanup()
  1113. {
  1114. using (Logger.CreateCallstack())
  1115. {
  1116. if (_process != null)
  1117. {
  1118. Logger.WriteLine("Terminating process");
  1119. try
  1120. {
  1121. try
  1122. {
  1123. WriteCommand("exit");
  1124. _process.Close();
  1125. }
  1126. finally
  1127. {
  1128. _process.Dispose();
  1129. _process = null;
  1130. }
  1131. }
  1132. catch (Exception e)
  1133. {
  1134. Logger.WriteLine("Process cleanup Exception: {0}", e);
  1135. }
  1136. }
  1137. Logger.WriteLine("Disposing log readers");
  1138. if (_reader != null)
  1139. {
  1140. _reader.Dispose();
  1141. _reader = null;
  1142. }
  1143. if (_logReader != null)
  1144. {
  1145. _logReader.Dispose();
  1146. _logReader = null;
  1147. }
  1148. // Cleanup log file
  1149. if ((XmlLogPath != null) && File.Exists(XmlLogPath))
  1150. {
  1151. Logger.WriteLine("Deleting XML log file [{0}]", XmlLogPath);
  1152. try
  1153. {
  1154. File.Delete(XmlLogPath);
  1155. }
  1156. catch (DirectoryNotFoundException e)
  1157. {
  1158. Logger.WriteLine("XML log cleanup DirectoryNotFoundException: {0}", e);
  1159. }
  1160. catch (IOException e)
  1161. {
  1162. Logger.WriteLine("XML log cleanup IOException: {0}", e);
  1163. }
  1164. catch (UnauthorizedAccessException e)
  1165. {
  1166. Logger.WriteLine("XML log cleanup UnauthorizedAccessException: {0}", e);
  1167. }
  1168. _xmlLogPath = null;
  1169. }
  1170. }
  1171. }
  1172. private void WriteCommand(string command)
  1173. {
  1174. WriteCommand(command, command);
  1175. }
  1176. private void WriteCommand(string command, string log)
  1177. {
  1178. Logger.WriteLine("Command: [{0}]", log);
  1179. _process.ExecuteCommand(command, log);
  1180. GotOutput();
  1181. }
  1182. private static void ReadElement(CustomLogReader reader, LogReadFlags flags)
  1183. {
  1184. while (reader.Read(flags))
  1185. {
  1186. }
  1187. }
  1188. private void SessionOptionsToUrlAndSwitches(SessionOptions sessionOptions, bool scanFingerprint, out string command, out string log)
  1189. {
  1190. using (Logger.CreateCallstack())
  1191. {
  1192. if (sessionOptions.WebdavSecure)
  1193. {
  1194. if (sessionOptions.Protocol != Protocol.Webdav)
  1195. {
  1196. throw Logger.WriteException(new ArgumentException("SessionOptions.WebdavSecure is set, but SessionOptions.Protocol is not Protocol.Webdav."));
  1197. }
  1198. }
  1199. string head;
  1200. switch (sessionOptions.Protocol)
  1201. {
  1202. case Protocol.Sftp:
  1203. head = "sftp://";
  1204. break;
  1205. case Protocol.Scp:
  1206. head = "scp://";
  1207. break;
  1208. case Protocol.Ftp:
  1209. head = "ftp://";
  1210. break;
  1211. case Protocol.Webdav:
  1212. if (!sessionOptions.WebdavSecure)
  1213. {
  1214. head = "dav://";
  1215. }
  1216. else
  1217. {
  1218. head = "davs://";
  1219. }
  1220. break;
  1221. default:
  1222. throw Logger.WriteException(new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.Protocol)));
  1223. }
  1224. bool hasUsername;
  1225. if (!scanFingerprint)
  1226. {
  1227. hasUsername = !string.IsNullOrEmpty(sessionOptions.UserName);
  1228. if (hasUsername)
  1229. {
  1230. head += UriEscape(sessionOptions.UserName);
  1231. }
  1232. }
  1233. else
  1234. {
  1235. hasUsername = false;
  1236. }
  1237. string url = head;
  1238. string logUrl = head;
  1239. if ((sessionOptions.SecurePassword != null) && !scanFingerprint)
  1240. {
  1241. if (!hasUsername)
  1242. {
  1243. throw Logger.WriteException(new ArgumentException("SessionOptions.Password is set, but SessionOptions.UserName is not."));
  1244. }
  1245. url += ":" + UriEscape(sessionOptions.Password);
  1246. logUrl += ":***";
  1247. }
  1248. string tail = string.Empty;
  1249. if (hasUsername)
  1250. {
  1251. tail += "@";
  1252. }
  1253. if (string.IsNullOrEmpty(sessionOptions.HostName))
  1254. {
  1255. throw Logger.WriteException(new ArgumentException("SessionOptions.HostName is not set."));
  1256. }
  1257. // We should wrap IPv6 literals to square brackets, instead of URL-encoding them,
  1258. // but it works anyway...
  1259. tail += UriEscape(sessionOptions.HostName);
  1260. if (sessionOptions.PortNumber != 0)
  1261. {
  1262. tail += ":" + sessionOptions.PortNumber.ToString(CultureInfo.InvariantCulture);
  1263. }
  1264. if (!string.IsNullOrEmpty(sessionOptions.WebdavRoot) && !scanFingerprint)
  1265. {
  1266. if (sessionOptions.Protocol != Protocol.Webdav)
  1267. {
  1268. throw Logger.WriteException(new ArgumentException("SessionOptions.WebdavRoot is set, but SessionOptions.Protocol is not Protocol.Webdav."));
  1269. }
  1270. tail += sessionOptions.WebdavRoot;
  1271. }
  1272. url += tail;
  1273. logUrl += tail;
  1274. string arguments;
  1275. string logArguments;
  1276. SessionOptionsToSwitches(sessionOptions, scanFingerprint, out arguments, out logArguments);
  1277. const string switchName = "-rawsettings";
  1278. Tools.AddRawParameters(ref arguments, sessionOptions.RawSettings, "-rawsettings");
  1279. Tools.AddRawParameters(ref logArguments, sessionOptions.RawSettings, switchName);
  1280. if (!string.IsNullOrEmpty(arguments))
  1281. {
  1282. arguments = " " + arguments;
  1283. logArguments = " " + logArguments;
  1284. }
  1285. // Switches should (and particularly the -rawsettings MUST) come after the URL
  1286. command = "\"" + Tools.ArgumentEscape(url) + "\"" + arguments;
  1287. log = "\"" + Tools.ArgumentEscape(logUrl) + "\"" + logArguments;
  1288. }
  1289. }
  1290. private void SessionOptionsToSwitches(SessionOptions sessionOptions, bool scanFingerprint, out string arguments, out string logArguments)
  1291. {
  1292. using (Logger.CreateCallstack())
  1293. {
  1294. List<string> switches = new List<string>();
  1295. if (!string.IsNullOrEmpty(sessionOptions.SshHostKeyFingerprint) ||
  1296. (sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey && !scanFingerprint))
  1297. {
  1298. if (!sessionOptions.IsSsh)
  1299. {
  1300. throw Logger.WriteException(new ArgumentException("SessionOptions.SshHostKeyFingerprint or SessionOptions.GiveUpSecurityAndAcceptAnySshHostKey is set, but SessionOptions.Protocol is neither Protocol.Sftp nor Protocol.Scp."));
  1301. }
  1302. string sshHostKeyFingerprint = sessionOptions.SshHostKeyFingerprint;
  1303. if (sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey)
  1304. {
  1305. Logger.WriteLine("WARNING! Giving up security and accepting any key as configured");
  1306. sshHostKeyFingerprint = AddStarToList(sshHostKeyFingerprint);
  1307. }
  1308. switches.Add(FormatSwitch("hostkey", sshHostKeyFingerprint));
  1309. }
  1310. else
  1311. {
  1312. if (sessionOptions.IsSsh && DefaultConfigurationInternal && !scanFingerprint)
  1313. {
  1314. throw Logger.WriteException(new ArgumentException("SessionOptions.Protocol is Protocol.Sftp or Protocol.Scp, but SessionOptions.SshHostKeyFingerprint is not set."));
  1315. }
  1316. }
  1317. if (!string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath) && !scanFingerprint)
  1318. {
  1319. if (!sessionOptions.IsSsh)
  1320. {
  1321. throw Logger.WriteException(new ArgumentException("SessionOptions.SshPrivateKeyPath is set, but SessionOptions.Protocol is neither Protocol.Sftp nor Protocol.Scp."));
  1322. }
  1323. switches.Add(FormatSwitch("privatekey", sessionOptions.SshPrivateKeyPath));
  1324. }
  1325. if (!string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath) && !scanFingerprint)
  1326. {
  1327. if (!sessionOptions.IsTls)
  1328. {
  1329. throw Logger.WriteException(new ArgumentException("SessionOptions.TlsClientCertificatePath is set, but neither SessionOptions.FtpSecure nor SessionOptions.WebdavSecure is enabled."));
  1330. }
  1331. switches.Add(FormatSwitch("clientcert", sessionOptions.TlsClientCertificatePath));
  1332. }
  1333. if (sessionOptions.FtpSecure != FtpSecure.None)
  1334. {
  1335. if (sessionOptions.Protocol != Protocol.Ftp)
  1336. {
  1337. throw Logger.WriteException(new ArgumentException("SessionOptions.FtpSecure is not FtpSecure.None, but SessionOptions.Protocol is not Protocol.Ftp."));
  1338. }
  1339. switch (sessionOptions.FtpSecure)
  1340. {
  1341. case FtpSecure.Implicit:
  1342. switches.Add(FormatSwitch("implicit"));
  1343. break;
  1344. case FtpSecure.Explicit:
  1345. switches.Add(FormatSwitch("explicit"));
  1346. break;
  1347. default:
  1348. throw Logger.WriteException(new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.FtpSecure)));
  1349. }
  1350. }
  1351. if ((!string.IsNullOrEmpty(sessionOptions.TlsHostCertificateFingerprint) ||
  1352. sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate) &&
  1353. !scanFingerprint)
  1354. {
  1355. if (!sessionOptions.IsTls)
  1356. {
  1357. throw Logger.WriteException(new ArgumentException("SessionOptions.TlsHostCertificateFingerprint or SessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate is set, but neither SessionOptions.FtpSecure nor SessionOptions.WebdavSecure is enabled."));
  1358. }
  1359. string tlsHostCertificateFingerprint = sessionOptions.TlsHostCertificateFingerprint;
  1360. if (sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
  1361. {
  1362. Logger.WriteLine("WARNING! Giving up security and accepting any certificate as configured");
  1363. tlsHostCertificateFingerprint = AddStarToList(tlsHostCertificateFingerprint);
  1364. }
  1365. switches.Add(FormatSwitch("certificate", tlsHostCertificateFingerprint));
  1366. }
  1367. if ((sessionOptions.Protocol == Protocol.Ftp) && !scanFingerprint)
  1368. {
  1369. switches.Add(FormatSwitch("passive", (sessionOptions.FtpMode == FtpMode.Passive)));
  1370. }
  1371. switches.Add(FormatSwitch("timeout", (int)sessionOptions.Timeout.TotalSeconds));
  1372. List<string> logSwitches = new List<string>(switches);
  1373. if (!string.IsNullOrEmpty(sessionOptions.PrivateKeyPassphrase) && !scanFingerprint)
  1374. {
  1375. if (string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath) && string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath))
  1376. {
  1377. throw Logger.WriteException(new ArgumentException("SessionOptions.PrivateKeyPassphrase is set, but neither SessionOptions.SshPrivateKeyPath nor SessionOptions.TlsClientCertificatePath is set."));
  1378. }
  1379. switches.Add(FormatSwitch("passphrase", sessionOptions.PrivateKeyPassphrase));
  1380. logSwitches.Add(FormatSwitch("passphrase", "***"));
  1381. }
  1382. if ((sessionOptions.SecureNewPassword != null) && !scanFingerprint)
  1383. {
  1384. if (sessionOptions.SecurePassword == null)
  1385. {
  1386. throw Logger.WriteException(new ArgumentException("SessionOptions.SecureNewPassword is set, but SessionOptions.SecurePassword is not."));
  1387. }
  1388. switches.Add(FormatSwitch("newpassword", sessionOptions.NewPassword));
  1389. logSwitches.Add(FormatSwitch("newpassword", "***"));
  1390. }
  1391. arguments = string.Join(" ", switches.ToArray());
  1392. logArguments = string.Join(" ", logSwitches.ToArray());
  1393. }
  1394. }
  1395. private static string AddStarToList(string list)
  1396. {
  1397. return (string.IsNullOrEmpty(list) ? string.Empty : list + ";") + "*";
  1398. }
  1399. private RemoteFileInfo DoGetFileInfo(string path)
  1400. {
  1401. using (Logger.CreateCallstack())
  1402. {
  1403. WriteCommand(string.Format(CultureInfo.InvariantCulture, "stat -- \"{0}\"", Tools.ArgumentEscape(path)));
  1404. RemoteFileInfo fileInfo = new RemoteFileInfo();
  1405. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1406. using (ElementLogReader statReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("stat", LogReadFlags.ThrowFailures))
  1407. {
  1408. while (statReader.Read(0))
  1409. {
  1410. string value;
  1411. if (statReader.GetEmptyElementValue("filename", out value))
  1412. {
  1413. string name = value;
  1414. int p = name.LastIndexOf('/');
  1415. if (p >= 0)
  1416. {
  1417. name = name.Substring(p + 1);
  1418. }
  1419. fileInfo.Name = name;
  1420. fileInfo.FullName = value;
  1421. }
  1422. else if (statReader.IsNonEmptyElement("file"))
  1423. {
  1424. using (ElementLogReader fileReader = statReader.CreateLogReader())
  1425. {
  1426. while (fileReader.Read(0))
  1427. {
  1428. ReadFile(fileInfo, fileReader);
  1429. }
  1430. }
  1431. }
  1432. }
  1433. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1434. }
  1435. return fileInfo;
  1436. }
  1437. }
  1438. internal static string FormatSwitch(string key)
  1439. {
  1440. return string.Format(CultureInfo.InvariantCulture, "-{0}", key);
  1441. }
  1442. internal static string FormatSwitch(string key, string value)
  1443. {
  1444. return string.Format(CultureInfo.InvariantCulture, "-{0}=\"{1}\"", key, Tools.ArgumentEscape(value));
  1445. }
  1446. internal static string FormatSwitch(string key, int value)
  1447. {
  1448. return string.Format(CultureInfo.InvariantCulture, "-{0}={1}", key, value.ToString(CultureInfo.InvariantCulture));
  1449. }
  1450. internal static string FormatSwitch(string key, bool value)
  1451. {
  1452. return FormatSwitch(key, (value ? 1 : 0));
  1453. }
  1454. private static string UriEscape(string s)
  1455. {
  1456. return Uri.EscapeDataString(s);
  1457. }
  1458. internal void GotOutput()
  1459. {
  1460. _lastOutput = DateTime.Now;
  1461. }
  1462. private void ProcessOutputDataReceived(object sender, OutputDataReceivedEventArgs e)
  1463. {
  1464. if (e == null)
  1465. {
  1466. Logger.WriteLine("Got incomplete progress output");
  1467. }
  1468. else
  1469. {
  1470. Logger.WriteLine("Scheduling output: [{0}]", e.Data);
  1471. string s = e.Data.TrimEnd(new[] { '\r' });
  1472. lock (Output)
  1473. {
  1474. Output.InternalAdd(s);
  1475. if (Output.Count > 1000)
  1476. {
  1477. Output.InternalRemoveFirst();
  1478. }
  1479. if (e.Error)
  1480. {
  1481. _error.InternalAdd(s);
  1482. if (_error.Count > 1000)
  1483. {
  1484. _error.InternalRemoveFirst();
  1485. }
  1486. }
  1487. }
  1488. ScheduleEvent(() => RaiseOutputDataReceived(e.Data, e.Error));
  1489. }
  1490. GotOutput();
  1491. }
  1492. private void ScheduleEvent(Action action)
  1493. {
  1494. lock (_events)
  1495. {
  1496. _events.Add(action);
  1497. _eventsEvent.Set();
  1498. }
  1499. }
  1500. internal void CheckForTimeout(string additional = null)
  1501. {
  1502. if (DateTime.Now - _lastOutput > Timeout)
  1503. {
  1504. string message = "Timeout waiting for WinSCP to respond";
  1505. if (additional != null)
  1506. {
  1507. message += " - " + additional;
  1508. }
  1509. throw Logger.WriteException(new TimeoutException(message));
  1510. }
  1511. if (_aborted)
  1512. {
  1513. throw Logger.WriteException(new SessionLocalException(this, "Aborted."));
  1514. }
  1515. }
  1516. private void RaiseFileTransferredEvent(TransferEventArgs args)
  1517. {
  1518. Logger.WriteLine("FileTransferredEvent: [{0}]", args.FileName);
  1519. if (FileTransferred != null)
  1520. {
  1521. FileTransferred(this, args);
  1522. }
  1523. }
  1524. internal void RaiseFailed(SessionRemoteException e)
  1525. {
  1526. Logger.WriteLine("Failed: [{0}]", e);
  1527. if (Failed != null)
  1528. {
  1529. Failed(this, new FailedEventArgs { Error = e });
  1530. }
  1531. foreach (OperationResultBase operationResult in _operationResults)
  1532. {
  1533. operationResult.AddFailure(e);
  1534. }
  1535. }
  1536. private void CheckNotDisposed()
  1537. {
  1538. if (_disposed)
  1539. {
  1540. throw Logger.WriteException(new InvalidOperationException("Object is disposed"));
  1541. }
  1542. if (_aborted)
  1543. {
  1544. throw Logger.WriteException(new InvalidOperationException("Session was aborted"));
  1545. }
  1546. }
  1547. private void CheckOpened()
  1548. {
  1549. if (!Opened)
  1550. {
  1551. throw Logger.WriteException(new InvalidOperationException("Session is not opened"));
  1552. }
  1553. }
  1554. private void CheckNotOpened()
  1555. {
  1556. if (Opened)
  1557. {
  1558. throw Logger.WriteException(new InvalidOperationException("Session is already opened"));
  1559. }
  1560. }
  1561. private void RaiseOutputDataReceived(string data, bool error)
  1562. {
  1563. Logger.WriteLine("Output: [{0}]", data);
  1564. if (OutputDataReceived != null)
  1565. {
  1566. OutputDataReceived(this, new OutputDataReceivedEventArgs(data, error));
  1567. }
  1568. }
  1569. internal void DispatchEvents(int interval)
  1570. {
  1571. DateTime start = DateTime.Now;
  1572. while (_eventsEvent.WaitOne(interval, false))
  1573. {
  1574. lock (_events)
  1575. {
  1576. foreach (Action action in _events)
  1577. {
  1578. action();
  1579. }
  1580. _events.Clear();
  1581. }
  1582. interval -= (int) (DateTime.Now - start).TotalMilliseconds;
  1583. if (interval < 0)
  1584. {
  1585. break;
  1586. }
  1587. start = DateTime.Now;
  1588. }
  1589. }
  1590. private IDisposable RegisterOperationResult(OperationResultBase operationResult)
  1591. {
  1592. _operationResults.Add(operationResult);
  1593. return new OperationResultGuard(this, operationResult);
  1594. }
  1595. internal void UnregisterOperationResult(OperationResultBase operationResult)
  1596. {
  1597. _operationResults.Remove(operationResult);
  1598. }
  1599. internal bool WantsProgress
  1600. {
  1601. get
  1602. {
  1603. return (_fileTransferProgress != null);
  1604. }
  1605. }
  1606. private IDisposable CreateProgressHandler()
  1607. {
  1608. using (Logger.CreateCallstack())
  1609. {
  1610. _progressHandling++;
  1611. return new ProgressHandler(this);
  1612. }
  1613. }
  1614. internal void DisableProgressHandling()
  1615. {
  1616. using (Logger.CreateCallstack())
  1617. {
  1618. if (_progressHandling <= 0)
  1619. {
  1620. throw Logger.WriteException(new InvalidOperationException("Progress handling not enabled"));
  1621. }
  1622. // make sure we process all pending progress events
  1623. DispatchEvents(0);
  1624. _progressHandling--;
  1625. }
  1626. }
  1627. internal void ProcessProgress(FileTransferProgressEventArgs args)
  1628. {
  1629. ScheduleEvent(() => Progress(args));
  1630. }
  1631. private void Progress(FileTransferProgressEventArgs args)
  1632. {
  1633. if ((_progressHandling >= 0) && WantsProgress)
  1634. {
  1635. _fileTransferProgress(this, args);
  1636. }
  1637. }
  1638. private void SetupTempPath()
  1639. {
  1640. using (Logger.CreateCallstack())
  1641. {
  1642. if (!string.IsNullOrEmpty(_xmlLogPath))
  1643. {
  1644. bool exists = File.Exists(_xmlLogPath);
  1645. Logger.WriteLine("Configured temporary file: {0} - Exists [{1}]", _xmlLogPath, exists);
  1646. if (exists)
  1647. {
  1648. throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Configured temporary file {0} already exists", _xmlLogPath)));
  1649. }
  1650. }
  1651. else
  1652. {
  1653. string path = Path.GetTempPath();
  1654. Logger.WriteLine("Temporary folder: {0}", path);
  1655. string process = Process.GetCurrentProcess().Id.ToString("X4", CultureInfo.InvariantCulture);
  1656. string instance = GetHashCode().ToString("X8", CultureInfo.InvariantCulture);
  1657. string filename;
  1658. bool exists;
  1659. do
  1660. {
  1661. string uniqueStr = (_logUnique > 0 ? "." + _logUnique.ToString(CultureInfo.InvariantCulture) : string.Empty);
  1662. ++_logUnique;
  1663. filename = Path.Combine(path, "wscp" + process + "." + instance + uniqueStr + ".tmp");
  1664. exists = File.Exists(filename);
  1665. Logger.WriteLine("Temporary file [{0}] - Exists [{1}]", filename, exists);
  1666. }
  1667. while (exists);
  1668. _xmlLogPath = filename;
  1669. }
  1670. }
  1671. }
  1672. private static string GetTypeLibKey(Type t)
  1673. {
  1674. return "CLSID\\{" + t.GUID.ToString().ToUpperInvariant() + "}\\TypeLib";
  1675. }
  1676. FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
  1677. {
  1678. using (Logger.CreateCallstack())
  1679. {
  1680. Logger.WriteLine("Name [{0}]", name);
  1681. FieldInfo result = GetType().GetField(name, bindingAttr);
  1682. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1683. return result;
  1684. }
  1685. }
  1686. FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
  1687. {
  1688. using (Logger.CreateCallstack())
  1689. {
  1690. FieldInfo[] result = GetType().GetFields(bindingAttr);
  1691. Logger.WriteLine("Fields [{0}]", result.Length);
  1692. return result;
  1693. }
  1694. }
  1695. MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
  1696. {
  1697. using (Logger.CreateCallstack())
  1698. {
  1699. Logger.WriteLine("Name [{0}]", name);
  1700. MemberInfo[] result = GetType().GetMember(name, bindingAttr);
  1701. Logger.WriteLine("Result [{0}]", result.Length);
  1702. return result;
  1703. }
  1704. }
  1705. MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
  1706. {
  1707. using (Logger.CreateCallstack())
  1708. {
  1709. MemberInfo[] result = GetType().GetMembers(bindingAttr);
  1710. Logger.WriteLine("Result [{0}]", result.Length);
  1711. return result;
  1712. }
  1713. }
  1714. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
  1715. {
  1716. using (Logger.CreateCallstack())
  1717. {
  1718. Logger.WriteLine("Name [{0}]", name);
  1719. MethodInfo result = GetType().GetMethod(name, bindingAttr);
  1720. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1721. return result;
  1722. }
  1723. }
  1724. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
  1725. {
  1726. using (Logger.CreateCallstack())
  1727. {
  1728. Logger.WriteLine("Name [{0}]", name);
  1729. MethodInfo result = GetType().GetMethod(name, bindingAttr, binder, types, modifiers);
  1730. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1731. return result;
  1732. }
  1733. }
  1734. MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
  1735. {
  1736. using (Logger.CreateCallstack())
  1737. {
  1738. MethodInfo[] result = GetType().GetMethods(bindingAttr);
  1739. Logger.WriteLine("Result [{0}]", result.Length);
  1740. return result;
  1741. }
  1742. }
  1743. PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
  1744. {
  1745. using (Logger.CreateCallstack())
  1746. {
  1747. PropertyInfo[] result = GetType().GetProperties(bindingAttr);
  1748. Logger.WriteLine("Result [{0}]", result.Length);
  1749. return result;
  1750. }
  1751. }
  1752. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
  1753. {
  1754. using (Logger.CreateCallstack())
  1755. {
  1756. Logger.WriteLine("Name [{0}]", name);
  1757. PropertyInfo result = GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
  1758. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1759. return result;
  1760. }
  1761. }
  1762. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
  1763. {
  1764. using (Logger.CreateCallstack())
  1765. {
  1766. Logger.WriteLine("Name [{0}]", name);
  1767. PropertyInfo result = GetType().GetProperty(name, bindingAttr);
  1768. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1769. return result;
  1770. }
  1771. }
  1772. object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  1773. {
  1774. using (Logger.CreateCallstack())
  1775. {
  1776. object result;
  1777. try
  1778. {
  1779. if (Logger.Logging)
  1780. {
  1781. Logger.WriteLine("Name [{0}]", name);
  1782. Logger.WriteLine("BindingFlags [{0}]", invokeAttr);
  1783. Logger.WriteLine("Binder [{0}]", binder);
  1784. Logger.WriteLine("Target [{0}]", target);
  1785. if (args != null)
  1786. {
  1787. Logger.WriteLine("Args [{0}] [{1}]", args.Length, modifiers != null ? modifiers.Length.ToString(CultureInfo.InvariantCulture) : "null");
  1788. for (int i = 0; i < args.Length; ++i)
  1789. {
  1790. Logger.WriteLine("Arg [{0}] [{1}] [{1}] [{2}]", i, args[i], (args[i] != null ? args[i].GetType().ToString() : "null"), (modifiers != null ? modifiers[i].ToString() : "null"));
  1791. }
  1792. }
  1793. Logger.WriteLine("Culture [{0}]", culture);
  1794. if (namedParameters != null)
  1795. {
  1796. foreach (string namedParameter in namedParameters)
  1797. {
  1798. Logger.WriteLine("NamedParameter [{0}]", namedParameter);
  1799. }
  1800. }
  1801. }
  1802. if (target == null)
  1803. {
  1804. throw Logger.WriteException(new ArgumentNullException("target"));
  1805. }
  1806. Type type = target.GetType();
  1807. // RuntimeType.InvokeMember below calls into Binder.BindToMethod (Binder is OleAutBinder)
  1808. // that fails to match method, if integer value is provided to enum argument
  1809. // (SynchronizeDirectories with its SynchronizationMode and SynchronizationCriteria).
  1810. // This does not happen if we do not implement IReflect, though no idea why.
  1811. // So as a workaround we check, if the method has no overloads (what is always true for Session),
  1812. // and call the only instance directly.
  1813. // Calling MethodInfo.Invoke with int values for enum arguments works.
  1814. // Only as a fallback, we call InvokeMember (what is currently actually used only when
  1815. // the method with given name does not exist at all)
  1816. MethodInfo method = null;
  1817. PropertyInfo property = null;
  1818. // would be way too difficult to implement the below involving named arguments
  1819. if (namedParameters == null)
  1820. {
  1821. try
  1822. {
  1823. BindingFlags bindingFlags = invokeAttr | BindingFlags.Instance | BindingFlags.Public;
  1824. method = type.GetMethod(name, bindingFlags);
  1825. if (args == null)
  1826. {
  1827. throw Logger.WriteException(new ArgumentNullException("args"));
  1828. }
  1829. if (method != null)
  1830. {
  1831. // MethodInfo.Invoke does not fill-in optional arguments (contrary to RuntimeType.InvokeMember)
  1832. ParameterInfo[] parameters = method.GetParameters();
  1833. if (args.Length < parameters.Length)
  1834. {
  1835. Logger.WriteLine("Provided less parameters [{0}] than defined [{1}]", args.Length, parameters.Length);
  1836. object[] args2 = new object[parameters.Length];
  1837. for (int i = 0; i < parameters.Length; i++)
  1838. {
  1839. if (i < args.Length)
  1840. {
  1841. args2[i] = args[i];
  1842. }
  1843. else
  1844. {
  1845. if (!parameters[i].IsOptional)
  1846. {
  1847. Logger.WriteLine("Parameter [{0}] of [{1}] is not optional", i, method);
  1848. args2 = null;
  1849. break;
  1850. }
  1851. else
  1852. {
  1853. Logger.WriteLine("Adding default value [{0}] for optional parameter [{1}]", parameters[i].DefaultValue, i);
  1854. args2[i] = parameters[i].DefaultValue;
  1855. }
  1856. }
  1857. }
  1858. if (args2 != null)
  1859. {
  1860. args = args2;
  1861. }
  1862. }
  1863. }
  1864. else if (args.Length == 1) // sanity check
  1865. {
  1866. property = type.GetProperty(name, bindingFlags);
  1867. }
  1868. }
  1869. catch (AmbiguousMatchException e)
  1870. {
  1871. Logger.WriteLine("Unexpected ambiguous match [{0}]", e.Message);
  1872. }
  1873. }
  1874. if (method != null)
  1875. {
  1876. Logger.WriteLine("Invoking unambiguous method [{0}]", method);
  1877. result = method.Invoke(target, invokeAttr, binder, args, culture);
  1878. }
  1879. else if (property != null)
  1880. {
  1881. Logger.WriteLine("Setting unambiguous property [{0}]", property);
  1882. property.SetValue(target, args[0], invokeAttr, binder, null, culture);
  1883. result = null;
  1884. }
  1885. else
  1886. {
  1887. Logger.WriteLine("Invoking ambiguous/non-existing method 2 [{0}]", name);
  1888. result = type.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  1889. }
  1890. Logger.WriteLine("Result [{0}] [{1}]", result, (result != null ? result.GetType().ToString() : "null"));
  1891. }
  1892. catch (Exception e)
  1893. {
  1894. Logger.WriteLine("Error [{0}]", e);
  1895. throw;
  1896. }
  1897. return result;
  1898. }
  1899. }
  1900. Type IReflect.UnderlyingSystemType
  1901. {
  1902. get { return GetType(); }
  1903. }
  1904. internal const string Namespace = "http://winscp.net/schema/session/1.0";
  1905. internal Logger Logger { get; private set; }
  1906. internal bool GuardProcessWithJobInternal { get { return _guardProcessWithJob; } set { CheckNotOpened(); _guardProcessWithJob = value; } }
  1907. internal bool TestHandlesClosedInternal { get; set; }
  1908. internal Dictionary<string, string> RawConfiguration { get; private set; }
  1909. internal bool DefaultConfigurationInternal { get { return _defaultConfiguration; } }
  1910. internal string IniFilePathInternal { get { return _iniFilePath; } }
  1911. internal bool DisableVersionCheckInternal { get { return _disableVersionCheck; } }
  1912. private ExeSessionProcess _process;
  1913. private DateTime _lastOutput;
  1914. private ElementLogReader _reader;
  1915. private SessionLogReader _logReader;
  1916. private readonly IList<OperationResultBase> _operationResults;
  1917. private delegate void Action();
  1918. private readonly IList<Action> _events;
  1919. private AutoResetEvent _eventsEvent;
  1920. private bool _disposed;
  1921. private string _executablePath;
  1922. private string _additionalExecutableArguments;
  1923. private bool _defaultConfiguration;
  1924. private bool _disableVersionCheck;
  1925. private string _iniFilePath;
  1926. private TimeSpan _reconnectTime;
  1927. private string _sessionLogPath;
  1928. private bool _aborted;
  1929. private int _logUnique;
  1930. private string _xmlLogPath;
  1931. private FileTransferProgressEventHandler _fileTransferProgress;
  1932. private int _progressHandling;
  1933. private bool _guardProcessWithJob;
  1934. private string _homePath;
  1935. private string _executableProcessUserName;
  1936. private SecureString _executableProcessPassword;
  1937. private StringCollection _error;
  1938. }
  1939. }