Session.cs 86 KB

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