Session.cs 91 KB

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