Session.cs 90 KB

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