Session.cs 91 KB

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