Session.cs 113 KB

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