Session.cs 91 KB

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