Session.cs 91 KB

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