Session.cs 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782
  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. return DoPutFiles(localPath, remotePath, remove, options);
  592. }
  593. }
  594. public TransferOperationResult DoPutFiles(string localPath, string remotePath, bool remove, TransferOptions options)
  595. {
  596. using (Logger.CreateCallstack())
  597. {
  598. if (options == null)
  599. {
  600. options = new TransferOptions();
  601. }
  602. CheckOpened();
  603. WriteCommand(
  604. string.Format(CultureInfo.InvariantCulture,
  605. "put {0} {1} -- \"{2}\" \"{3}\"",
  606. BooleanSwitch(remove, "delete"), options.ToSwitches(),
  607. Tools.ArgumentEscape(localPath), Tools.ArgumentEscape(remotePath)));
  608. TransferOperationResult result = new TransferOperationResult();
  609. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  610. using (RegisterOperationResult(result))
  611. using (CreateProgressHandler())
  612. {
  613. TransferEventArgs args = null;
  614. bool mkdir = false;
  615. while (groupReader.Read(0))
  616. {
  617. if (groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag))
  618. {
  619. AddTransfer(result, args);
  620. args = TransferEventArgs.Read(ProgressSide.Local, groupReader);
  621. mkdir = false;
  622. }
  623. else if (groupReader.IsNonEmptyElement(TransferEventArgs.MkDirTag))
  624. {
  625. AddTransfer(result, args);
  626. args = null;
  627. mkdir = true;
  628. // For now, silently ignoring results (even errors)
  629. // of mkdir operation, including future chmod/touch
  630. }
  631. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  632. {
  633. if (!mkdir)
  634. {
  635. if (args == null)
  636. {
  637. throw Logger.WriteException(new InvalidOperationException("Tag chmod before tag upload"));
  638. }
  639. args.Chmod = ChmodEventArgs.Read(groupReader);
  640. }
  641. }
  642. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  643. {
  644. if (!mkdir)
  645. {
  646. if (args == null)
  647. {
  648. throw Logger.WriteException(new InvalidOperationException("Tag touch before tag upload"));
  649. }
  650. args.Touch = TouchEventArgs.Read(groupReader);
  651. }
  652. }
  653. }
  654. AddTransfer(result, args);
  655. }
  656. return result;
  657. }
  658. }
  659. public TransferOperationResult PutFilesToDirectory(
  660. string localDirectory, string remoteDirectory, string filemask = null, bool remove = false, TransferOptions options = null)
  661. {
  662. // Not locking, locked in PutFiles
  663. using (Logger.CreateCallstack())
  664. {
  665. if (localDirectory == null)
  666. {
  667. throw Logger.WriteException(new ArgumentNullException(nameof(localDirectory)));
  668. }
  669. if (remoteDirectory == null)
  670. {
  671. throw Logger.WriteException(new ArgumentNullException(nameof(remoteDirectory)));
  672. }
  673. if (string.IsNullOrEmpty(filemask))
  674. {
  675. filemask = "*";
  676. }
  677. string localPath = Path.Combine(localDirectory, filemask);
  678. const string remoteSeparator = "/";
  679. string remotePath =
  680. remoteDirectory +
  681. (remoteDirectory.EndsWith(remoteSeparator, StringComparison.Ordinal) ? string.Empty : remoteSeparator);
  682. return PutFiles(localPath, remotePath, remove, options);
  683. }
  684. }
  685. public TransferEventArgs PutFileToDirectory(string localFilePath, string remoteDirectory, bool remove = false, TransferOptions options = null)
  686. {
  687. // Not locking, locked in PutFiles (within PutFilesToDirectory)
  688. using (Logger.CreateCallstack())
  689. {
  690. if (!File.Exists(localFilePath))
  691. {
  692. throw Logger.WriteException(new FileNotFoundException($"File {localFilePath} does not exist", localFilePath));
  693. }
  694. TransferOperationResult operationResult = PutEntryToDirectory(localFilePath, remoteDirectory, remove, options);
  695. return GetOnlyFileOperation(operationResult.Transfers);
  696. }
  697. }
  698. public void PutFile(Stream stream, string remoteFilePath, TransferOptions options = null)
  699. {
  700. using (Logger.CreateCallstackAndLock())
  701. {
  702. if (stream == null)
  703. {
  704. throw Logger.WriteException(new ArgumentNullException(nameof(stream)));
  705. }
  706. if (remoteFilePath == null)
  707. {
  708. throw Logger.WriteException(new ArgumentNullException(nameof(remoteFilePath)));
  709. }
  710. if (_process.StdIn != null)
  711. {
  712. throw Logger.WriteException(new InvalidOperationException("Already uploading from a stream"));
  713. }
  714. _process.StdIn = stream;
  715. try
  716. {
  717. remoteFilePath = RemotePath.EscapeFileMask(remoteFilePath);
  718. TransferOperationResult operationResult = DoPutFiles("-", remoteFilePath, false, options);
  719. operationResult.Check();
  720. // Assert that any transfer took place at all
  721. GetOnlyFileOperation(operationResult.Transfers);
  722. }
  723. finally
  724. {
  725. _process.StdIn = null;
  726. }
  727. }
  728. }
  729. internal TransferOperationResult PutEntryToDirectory(string localFilePath, string remoteDirectory, bool remove = false, TransferOptions options = null)
  730. {
  731. using (Logger.CreateCallstack())
  732. {
  733. if (string.IsNullOrEmpty(localFilePath))
  734. {
  735. throw Logger.WriteException(new ArgumentException("File to path cannot be empty", nameof(localFilePath)));
  736. }
  737. string localDirectory = Path.GetDirectoryName(localFilePath);
  738. string filemask = RemotePath.EscapeFileMask(Path.GetFileName(localFilePath));
  739. TransferOperationResult operationResult = PutFilesToDirectory(localDirectory, remoteDirectory, filemask, remove, options);
  740. operationResult.Check();
  741. return operationResult;
  742. }
  743. }
  744. private void AddTransfer(TransferOperationResult result, TransferEventArgs args)
  745. {
  746. if (args != null)
  747. {
  748. result.AddTransfer(args);
  749. RaiseFileTransferredEvent(args);
  750. }
  751. }
  752. public TransferOperationResult GetFiles(string remotePath, string localPath, bool remove = false, TransferOptions options = null)
  753. {
  754. using (Logger.CreateCallstackAndLock())
  755. {
  756. return DoGetFiles(remotePath, localPath, remove, options, string.Empty);
  757. }
  758. }
  759. private TransferOperationResult DoGetFiles(
  760. string remotePath, string localPath, bool remove, TransferOptions options, string additionalParams)
  761. {
  762. using (Logger.CreateCallstack())
  763. {
  764. StartGetCommand(remotePath, localPath, remove, options, additionalParams);
  765. TransferOperationResult result = new TransferOperationResult();
  766. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  767. using (RegisterOperationResult(result))
  768. using (CreateProgressHandler())
  769. {
  770. TransferEventArgs args = null;
  771. while (groupReader.Read(0))
  772. {
  773. if (groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
  774. {
  775. AddTransfer(result, args);
  776. args = TransferEventArgs.Read(ProgressSide.Remote, groupReader);
  777. }
  778. else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  779. {
  780. // When "downloading and deleting" a folder,
  781. // we get "rm" tag without preceeding "download" tag.
  782. // So we use only the first "rm" tag after preceeding "download" tag,
  783. // silently ignoring the others
  784. if ((args != null) && (args.Removal == null))
  785. {
  786. args.Removal = RemovalEventArgs.Read(groupReader);
  787. }
  788. }
  789. }
  790. AddTransfer(result, args);
  791. }
  792. return result;
  793. }
  794. }
  795. private void StartGetCommand(string remotePath, string localPath, bool remove, TransferOptions options, string additionalParams)
  796. {
  797. if (options == null)
  798. {
  799. options = new TransferOptions();
  800. }
  801. CheckOpened();
  802. WriteCommand(
  803. string.Format(CultureInfo.InvariantCulture, "get {0} {1} {2} -- \"{3}\" \"{4}\"",
  804. BooleanSwitch(remove, "delete"), options.ToSwitches(), additionalParams,
  805. Tools.ArgumentEscape(remotePath), Tools.ArgumentEscape(localPath)));
  806. }
  807. public TransferOperationResult GetFilesToDirectory(
  808. string remoteDirectory, string localDirectory, string filemask = null, bool remove = false, TransferOptions options = null)
  809. {
  810. using (Logger.CreateCallstackAndLock())
  811. {
  812. return DoGetFilesToDirectory(remoteDirectory, localDirectory, filemask, remove, options, null);
  813. }
  814. }
  815. private TransferOperationResult DoGetFilesToDirectory(
  816. string remoteDirectory, string localDirectory, string filemask, bool remove, TransferOptions options, string additionalParams)
  817. {
  818. using (Logger.CreateCallstack())
  819. {
  820. if (remoteDirectory == null)
  821. {
  822. throw Logger.WriteException(new ArgumentNullException(nameof(remoteDirectory)));
  823. }
  824. if (localDirectory == null)
  825. {
  826. throw Logger.WriteException(new ArgumentNullException(nameof(localDirectory)));
  827. }
  828. if (string.IsNullOrEmpty(filemask))
  829. {
  830. filemask = "*";
  831. }
  832. string remotePath = RemotePath.Combine(remoteDirectory, filemask);
  833. if (!Directory.Exists(localDirectory))
  834. {
  835. throw Logger.WriteException(new DirectoryNotFoundException(localDirectory));
  836. }
  837. string localSeparator = Path.DirectorySeparatorChar.ToString();
  838. string localPath =
  839. localDirectory +
  840. (localDirectory.EndsWith(localSeparator, StringComparison.Ordinal) ? string.Empty : localSeparator);
  841. return DoGetFiles(remotePath, localPath, remove, options, additionalParams);
  842. }
  843. }
  844. public TransferEventArgs GetFileToDirectory(string remoteFilePath, string localDirectory, bool remove = false, TransferOptions options = null)
  845. {
  846. using (Logger.CreateCallstackAndLock())
  847. {
  848. const string additionalParams = "-onlyfile";
  849. TransferOperationResult operationResult = GetEntryToDirectory(remoteFilePath, localDirectory, remove, options, additionalParams);
  850. return GetOnlyFileOperation(operationResult.Transfers);
  851. }
  852. }
  853. internal TransferOperationResult GetEntryToDirectory(
  854. string remoteFilePath, string localDirectory, bool remove = false, TransferOptions options = null, string additionalParams = null)
  855. {
  856. using (Logger.CreateCallstack())
  857. {
  858. ParseRemotePath(remoteFilePath, out string remoteDirectory, out string filemask);
  859. TransferOperationResult operationResult =
  860. DoGetFilesToDirectory(remoteDirectory, localDirectory, filemask, remove, options, additionalParams ?? string.Empty);
  861. operationResult.Check();
  862. return operationResult;
  863. }
  864. }
  865. private void ParseRemotePath(string remoteFilePath, out string remoteDirectory, out string filemask)
  866. {
  867. if (string.IsNullOrEmpty(remoteFilePath))
  868. {
  869. throw Logger.WriteException(new ArgumentException("File to path cannot be empty", nameof(remoteFilePath)));
  870. }
  871. remoteDirectory = RemotePath.GetDirectoryName(remoteFilePath);
  872. filemask = RemotePath.EscapeFileMask(RemotePath.GetFileName(remoteFilePath));
  873. }
  874. private T GetOnlyFileOperation<T>(ICollection<T> operations)
  875. {
  876. // For "get", this should happen only when the filename is mask-like, otherwise "get" throws straight away.
  877. // For "put", this should not happen.
  878. if (operations.Count == 0)
  879. {
  880. throw Logger.WriteException(new FileNotFoundException("File not found"));
  881. }
  882. if (operations.Count > 1)
  883. {
  884. throw Logger.WriteException(new InvalidOperationException("More then one file has been unexpectedly found"));
  885. }
  886. return operations.First();
  887. }
  888. public Stream GetFile(string remoteFilePath, TransferOptions options = null)
  889. {
  890. using (CallstackAndLock callstackAndLock = Logger.CreateCallstackAndLock())
  891. {
  892. const string additionalParams = "-onlyfile";
  893. ParseRemotePath(remoteFilePath, out string remoteDirectory, out string filemask);
  894. string remotePath = RemotePath.Combine(remoteDirectory, filemask);
  895. StartGetCommand(remotePath, "-", false, options, additionalParams);
  896. // only to collect failures
  897. TransferOperationResult result = new TransferOperationResult();
  898. ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader();
  899. IDisposable operationResultGuard = RegisterOperationResult(result);
  900. IDisposable progressHandler = CreateProgressHandler();
  901. void onGetEnd()
  902. {
  903. try
  904. {
  905. // This can throw
  906. progressHandler.Dispose();
  907. }
  908. finally
  909. {
  910. try
  911. {
  912. groupReader.Dispose();
  913. }
  914. finally
  915. {
  916. _process.StdOut = null;
  917. // Only after disposing the group reader, so when called from onGetEndWithExit, the Check() has all failures.
  918. operationResultGuard.Dispose();
  919. }
  920. }
  921. }
  922. void onGetEndWithExit()
  923. {
  924. try
  925. {
  926. onGetEnd();
  927. }
  928. finally
  929. {
  930. Logger.Lock.Exit();
  931. result.Check();
  932. }
  933. }
  934. // should never happen
  935. if (_process.StdOut != null)
  936. {
  937. throw Logger.WriteException(new InvalidOperationException("Data stream already exist"));
  938. }
  939. PipeStream stream = new PipeStream(onGetEndWithExit);
  940. _process.StdOut = stream;
  941. try
  942. {
  943. bool downloadFound;
  944. try
  945. {
  946. // Not using WaitForNonEmptyElement only to allow throwing better exception message below.
  947. // Not using ThrowFailures as we need to return the stream, is there's <download>, even if there's a <failure> as well.
  948. downloadFound = groupReader.TryWaitForNonEmptyElement(TransferEventArgs.DownloadTag, 0);
  949. }
  950. catch (StdOutException)
  951. {
  952. downloadFound = true;
  953. }
  954. if (downloadFound)
  955. {
  956. callstackAndLock.DisarmLock();
  957. return stream;
  958. }
  959. else
  960. {
  961. // First throw any specific error from <failure>
  962. result.Check();
  963. // And only then fallback to the generic one.
  964. // See also the comment in GetOnlyFileOperation.
  965. throw Logger.WriteException(new FileNotFoundException("File not found"));
  966. }
  967. }
  968. catch
  969. {
  970. onGetEnd();
  971. throw;
  972. }
  973. }
  974. }
  975. public RemovalOperationResult RemoveFiles(string path)
  976. {
  977. using (Logger.CreateCallstackAndLock())
  978. {
  979. return DoRemoveFiles(path, string.Empty);
  980. }
  981. }
  982. private RemovalOperationResult DoRemoveFiles(string path, string additionalParams)
  983. {
  984. using (Logger.CreateCallstack())
  985. {
  986. CheckOpened();
  987. WriteCommand(string.Format(CultureInfo.InvariantCulture, "rm {0} -- \"{1}\"", additionalParams, Tools.ArgumentEscape(path)));
  988. RemovalOperationResult result = new RemovalOperationResult();
  989. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  990. using (RegisterOperationResult(result))
  991. {
  992. while (groupReader.Read(0))
  993. {
  994. if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  995. {
  996. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  997. }
  998. }
  999. }
  1000. return result;
  1001. }
  1002. }
  1003. public RemovalEventArgs RemoveFile(string path)
  1004. {
  1005. using (Logger.CreateCallstackAndLock())
  1006. {
  1007. RemovalOperationResult operationResult = RemoveEntry(path, "-onlyfile");
  1008. return GetOnlyFileOperation(operationResult.Removals);
  1009. }
  1010. }
  1011. internal RemovalOperationResult RemoveEntry(string path, string additionalParams = null)
  1012. {
  1013. using (Logger.CreateCallstack())
  1014. {
  1015. if (string.IsNullOrEmpty(path))
  1016. {
  1017. throw Logger.WriteException(new ArgumentException("File to path cannot be empty", nameof(path)));
  1018. }
  1019. string remoteDirectory = RemotePath.GetDirectoryName(path);
  1020. string filemask = RemotePath.EscapeFileMask(RemotePath.GetFileName(path));
  1021. if (string.IsNullOrEmpty(filemask))
  1022. {
  1023. throw Logger.WriteException(new ArgumentException("File name cannot be empty", nameof(path)));
  1024. }
  1025. path = RemotePath.Combine(remoteDirectory, filemask);
  1026. RemovalOperationResult operationResult = DoRemoveFiles(path, additionalParams ?? string.Empty);
  1027. operationResult.Check();
  1028. return operationResult;
  1029. }
  1030. }
  1031. public SynchronizationResult SynchronizeDirectories(
  1032. SynchronizationMode mode, string localPath, string remotePath,
  1033. bool removeFiles, bool mirror = false, SynchronizationCriteria criteria = SynchronizationCriteria.Time,
  1034. TransferOptions options = null)
  1035. {
  1036. using (Logger.CreateCallstackAndLock())
  1037. {
  1038. DoSynchronizeDirectories(mode, localPath, remotePath, removeFiles, mirror, criteria, options, string.Empty);
  1039. return ReadSynchronizeDirectories();
  1040. }
  1041. }
  1042. private void DoSynchronizeDirectories(
  1043. SynchronizationMode mode, string localPath, string remotePath, bool removeFiles, bool mirror,
  1044. SynchronizationCriteria criteria, TransferOptions options, string additionalParameters)
  1045. {
  1046. if (options == null)
  1047. {
  1048. options = new TransferOptions();
  1049. }
  1050. CheckOpened();
  1051. if (removeFiles && (mode == SynchronizationMode.Both))
  1052. {
  1053. throw Logger.WriteException(new ArgumentException("Cannot delete files in synchronization mode Both"));
  1054. }
  1055. if (mirror && (mode == SynchronizationMode.Both))
  1056. {
  1057. throw Logger.WriteException(new ArgumentException("Cannot mirror files in synchronization mode Both"));
  1058. }
  1059. if ((criteria != SynchronizationCriteria.Time) && (mode == SynchronizationMode.Both))
  1060. {
  1061. throw Logger.WriteException(new ArgumentException("Only Time criteria is allowed in synchronization mode Both"));
  1062. }
  1063. string modeName;
  1064. switch (mode)
  1065. {
  1066. case SynchronizationMode.Local:
  1067. modeName = "local";
  1068. break;
  1069. case SynchronizationMode.Remote:
  1070. modeName = "remote";
  1071. break;
  1072. case SynchronizationMode.Both:
  1073. modeName = "both";
  1074. break;
  1075. default:
  1076. throw Logger.WriteException(new ArgumentOutOfRangeException(nameof(mode)));
  1077. }
  1078. string criteriaName;
  1079. switch (criteria)
  1080. {
  1081. case SynchronizationCriteria.None:
  1082. criteriaName = "none";
  1083. break;
  1084. case SynchronizationCriteria.Time:
  1085. criteriaName = "time";
  1086. break;
  1087. case SynchronizationCriteria.Size:
  1088. criteriaName = "size";
  1089. break;
  1090. case SynchronizationCriteria.Either:
  1091. criteriaName = "either";
  1092. break;
  1093. default:
  1094. throw Logger.WriteException(new ArgumentOutOfRangeException(nameof(criteria)));
  1095. }
  1096. WriteCommand(
  1097. string.Format(CultureInfo.InvariantCulture,
  1098. "synchronize {0} {1} {2} {3} -criteria=\"{4}\" {5} -- \"{6}\" \"{7}\"",
  1099. modeName,
  1100. BooleanSwitch(removeFiles, "delete"),
  1101. BooleanSwitch(mirror, "mirror"),
  1102. options.ToSwitches(),
  1103. criteriaName,
  1104. additionalParameters,
  1105. Tools.ArgumentEscape(localPath), Tools.ArgumentEscape(remotePath)));
  1106. }
  1107. private SynchronizationResult ReadSynchronizeDirectories()
  1108. {
  1109. using (Logger.CreateCallstack())
  1110. {
  1111. SynchronizationResult result = new SynchronizationResult();
  1112. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1113. using (RegisterOperationResult(result))
  1114. using (CreateProgressHandler())
  1115. {
  1116. TransferEventArgs transfer = null;
  1117. bool mkdir = false;
  1118. while (groupReader.Read(0))
  1119. {
  1120. ProgressSide? newSide = null;
  1121. if (groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag))
  1122. {
  1123. newSide = ProgressSide.Local;
  1124. }
  1125. else if (groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
  1126. {
  1127. newSide = ProgressSide.Remote;
  1128. }
  1129. if (newSide.HasValue)
  1130. {
  1131. AddSynchronizationTransfer(result, transfer);
  1132. transfer = TransferEventArgs.Read(newSide.Value, groupReader);
  1133. mkdir = false;
  1134. }
  1135. else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  1136. {
  1137. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  1138. }
  1139. else if (groupReader.IsNonEmptyElement(TransferEventArgs.MkDirTag))
  1140. {
  1141. AddSynchronizationTransfer(result, transfer);
  1142. transfer = null;
  1143. mkdir = true;
  1144. // For now, silently ignoring results (even errors)
  1145. // of mkdir operation, including future chmod/touch
  1146. }
  1147. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  1148. {
  1149. if (!mkdir)
  1150. {
  1151. if (transfer == null)
  1152. {
  1153. throw Logger.WriteException(new InvalidOperationException("Tag chmod before tag download"));
  1154. }
  1155. transfer.Chmod = ChmodEventArgs.Read(groupReader);
  1156. }
  1157. }
  1158. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  1159. {
  1160. if (!mkdir)
  1161. {
  1162. if (transfer == null)
  1163. {
  1164. throw Logger.WriteException(new InvalidOperationException("Tag touch before tag download"));
  1165. }
  1166. transfer.Touch = TouchEventArgs.Read(groupReader);
  1167. }
  1168. }
  1169. }
  1170. AddSynchronizationTransfer(result, transfer);
  1171. }
  1172. return result;
  1173. }
  1174. }
  1175. public ComparisonDifferenceCollection CompareDirectories(
  1176. SynchronizationMode mode, string localPath, string remotePath,
  1177. bool removeFiles, bool mirror = false, SynchronizationCriteria criteria = SynchronizationCriteria.Time,
  1178. TransferOptions options = null)
  1179. {
  1180. using (Logger.CreateCallstackAndLock())
  1181. {
  1182. DoSynchronizeDirectories(mode, localPath, remotePath, removeFiles, mirror, criteria, options, "-preview");
  1183. return ReadCompareDirectories(localPath, remotePath);
  1184. }
  1185. }
  1186. private ComparisonDifferenceCollection ReadCompareDirectories(string localPath, string remotePath)
  1187. {
  1188. using (Logger.CreateCallstack())
  1189. {
  1190. ComparisonDifferenceCollection result = new ComparisonDifferenceCollection();
  1191. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1192. {
  1193. while (groupReader.TryWaitForNonEmptyElement("difference", LogReadFlags.ThrowFailures))
  1194. {
  1195. using (ElementLogReader differenceReader = groupReader.CreateLogReader())
  1196. {
  1197. ComparisonDifference difference = new ComparisonDifference(localPath, remotePath);
  1198. ComparisonFileInfo current = null;
  1199. while (differenceReader.Read(0))
  1200. {
  1201. if (differenceReader.GetEmptyElementValue("action", out string actionName))
  1202. {
  1203. if ((difference.Local != null) || (difference.Remote != null))
  1204. {
  1205. throw Logger.WriteException(new InvalidOperationException("Tag action after filename"));
  1206. }
  1207. if (actionName.Equals("uploadnew", StringComparison.OrdinalIgnoreCase))
  1208. {
  1209. difference.Action = SynchronizationAction.UploadNew;
  1210. difference.Local = new ComparisonFileInfo();
  1211. }
  1212. else if (actionName.Equals("downloadnew", StringComparison.OrdinalIgnoreCase))
  1213. {
  1214. difference.Action = SynchronizationAction.DownloadNew;
  1215. difference.Remote = new ComparisonFileInfo();
  1216. }
  1217. else if (actionName.Equals("uploadupdate", StringComparison.OrdinalIgnoreCase))
  1218. {
  1219. difference.Action = SynchronizationAction.UploadUpdate;
  1220. difference.Local = new ComparisonFileInfo();
  1221. difference.Remote = new ComparisonFileInfo();
  1222. }
  1223. else if (actionName.Equals("downloadupdate", StringComparison.OrdinalIgnoreCase))
  1224. {
  1225. difference.Action = SynchronizationAction.DownloadUpdate;
  1226. difference.Remote = new ComparisonFileInfo();
  1227. difference.Local = new ComparisonFileInfo();
  1228. }
  1229. else if (actionName.Equals("deleteremote", StringComparison.OrdinalIgnoreCase))
  1230. {
  1231. difference.Action = SynchronizationAction.DeleteRemote;
  1232. difference.Remote = new ComparisonFileInfo();
  1233. }
  1234. else if (actionName.Equals("deletelocal", StringComparison.OrdinalIgnoreCase))
  1235. {
  1236. difference.Action = SynchronizationAction.DeleteLocal;
  1237. difference.Local = new ComparisonFileInfo();
  1238. }
  1239. else
  1240. {
  1241. throw Logger.WriteException(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Unknown synchronization action \"{0}\"", actionName)));
  1242. }
  1243. }
  1244. else if (differenceReader.GetEmptyElementValue("type", out string fileType))
  1245. {
  1246. difference.IsDirectory = (fileType.Length == 1) && RemoteFileInfo.IsDirectoryFileType(fileType[0]);
  1247. }
  1248. else if (differenceReader.GetEmptyElementValue("filename", out string value))
  1249. {
  1250. if (current == null)
  1251. {
  1252. current = difference.Local ?? difference.Remote;
  1253. }
  1254. else if (current == difference.Local)
  1255. {
  1256. current = difference.Remote;
  1257. }
  1258. if (current == null)
  1259. {
  1260. throw Logger.WriteException(new InvalidOperationException("Unexpected filename tag"));
  1261. }
  1262. current.FileName = value;
  1263. }
  1264. else if (differenceReader.GetEmptyElementValue("modification", out value))
  1265. {
  1266. if (current == null)
  1267. {
  1268. throw Logger.WriteException(new InvalidOperationException("Unexpected modification tag"));
  1269. }
  1270. current.LastWriteTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Local);
  1271. }
  1272. else if (differenceReader.GetEmptyElementValue("size", out value))
  1273. {
  1274. if (current == null)
  1275. {
  1276. throw Logger.WriteException(new InvalidOperationException("Unexpected size tag"));
  1277. }
  1278. current.Length = long.Parse(value, CultureInfo.InvariantCulture);
  1279. }
  1280. }
  1281. if (difference.Action == default(SynchronizationAction))
  1282. {
  1283. throw Logger.WriteException(new InvalidOperationException("No action tag found"));
  1284. }
  1285. if (((difference.Local != null) && string.IsNullOrEmpty(difference.Local.FileName)) ||
  1286. ((difference.Remote != null) && string.IsNullOrEmpty(difference.Remote.FileName)))
  1287. {
  1288. throw Logger.WriteException(new InvalidOperationException("Missing file information"));
  1289. }
  1290. result.InternalAdd(difference);
  1291. }
  1292. }
  1293. }
  1294. return result;
  1295. }
  1296. }
  1297. public CommandExecutionResult ExecuteCommand(string command)
  1298. {
  1299. using (Logger.CreateCallstackAndLock())
  1300. {
  1301. CheckOpened();
  1302. WriteCommand(string.Format(CultureInfo.InvariantCulture, "call {0}", command));
  1303. CommandExecutionResult result = new CommandExecutionResult();
  1304. // registering before creating group reader, so that
  1305. // it is still registered, when group reader is read to the end in its .Dispose();
  1306. using (RegisterOperationResult(result))
  1307. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1308. using (ElementLogReader callReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("call", LogReadFlags.ThrowFailures))
  1309. {
  1310. while (callReader.Read(0))
  1311. {
  1312. if (callReader.GetEmptyElementValue("output", out string value))
  1313. {
  1314. result.Output = value;
  1315. }
  1316. if (callReader.GetEmptyElementValue("erroroutput", out value))
  1317. {
  1318. result.ErrorOutput = value;
  1319. }
  1320. if (callReader.GetEmptyElementValue("exitcode", out value))
  1321. {
  1322. result.ExitCode = int.Parse(value, CultureInfo.InvariantCulture);
  1323. }
  1324. }
  1325. }
  1326. return result;
  1327. }
  1328. }
  1329. public RemoteFileInfo GetFileInfo(string path)
  1330. {
  1331. using (Logger.CreateCallstackAndLock())
  1332. {
  1333. CheckOpened();
  1334. return DoGetFileInfo(path);
  1335. }
  1336. }
  1337. public bool FileExists(string path)
  1338. {
  1339. using (Logger.CreateCallstackAndLock())
  1340. {
  1341. CheckOpened();
  1342. try
  1343. {
  1344. _ignoreFailed = true;
  1345. try
  1346. {
  1347. DoGetFileInfo(path);
  1348. }
  1349. finally
  1350. {
  1351. _ignoreFailed = false;
  1352. }
  1353. return true;
  1354. }
  1355. catch (SessionRemoteException)
  1356. {
  1357. return false;
  1358. }
  1359. }
  1360. }
  1361. public byte[] CalculateFileChecksum(string algorithm, string path)
  1362. {
  1363. using (Logger.CreateCallstackAndLock())
  1364. {
  1365. WriteCommand(string.Format(CultureInfo.InvariantCulture, "checksum -- \"{0}\" \"{1}\"", Tools.ArgumentEscape(algorithm), Tools.ArgumentEscape(path)));
  1366. string hex = null;
  1367. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1368. using (ElementLogReader checksumReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("checksum", LogReadFlags.ThrowFailures))
  1369. {
  1370. while (checksumReader.Read(0))
  1371. {
  1372. if (checksumReader.GetEmptyElementValue("checksum", out string value))
  1373. {
  1374. hex = value;
  1375. }
  1376. }
  1377. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1378. }
  1379. int len = hex.Length;
  1380. if ((len % 2) != 0)
  1381. {
  1382. string error = string.Format(CultureInfo.CurrentCulture, "Invalid string representation of checksum - {0}", hex);
  1383. throw Logger.WriteException(new SessionLocalException(this, error));
  1384. }
  1385. int count = len / 2;
  1386. byte[] bytes = new byte[count];
  1387. for (int i = 0; i < count; i++)
  1388. {
  1389. bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
  1390. }
  1391. return bytes;
  1392. }
  1393. }
  1394. public void CreateDirectory(string path)
  1395. {
  1396. using (Logger.CreateCallstackAndLock())
  1397. {
  1398. CheckOpened();
  1399. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mkdir \"{0}\"", Tools.ArgumentEscape(path)));
  1400. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1401. using (ElementLogReader mkdirReader = groupReader.WaitForNonEmptyElementAndCreateLogReader(TransferEventArgs.MkDirTag, LogReadFlags.ThrowFailures))
  1402. {
  1403. ReadElement(mkdirReader, 0);
  1404. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1405. }
  1406. }
  1407. }
  1408. public void MoveFile(string sourcePath, string targetPath)
  1409. {
  1410. using (Logger.CreateCallstackAndLock())
  1411. {
  1412. CheckOpened();
  1413. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mv \"{0}\" \"{1}\"", Tools.ArgumentEscape(sourcePath), Tools.ArgumentEscape(targetPath)));
  1414. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1415. {
  1416. if (!groupReader.TryWaitForNonEmptyElement("mv", LogReadFlags.ThrowFailures))
  1417. {
  1418. throw Logger.WriteException(new SessionRemoteException(this, string.Format(CultureInfo.CurrentCulture, "{0} not found.", sourcePath)));
  1419. }
  1420. else
  1421. {
  1422. using (ElementLogReader mvReader = groupReader.CreateLogReader())
  1423. {
  1424. ReadElement(mvReader, 0);
  1425. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1426. }
  1427. }
  1428. }
  1429. }
  1430. }
  1431. public void DuplicateFile(string sourcePath, string targetPath)
  1432. {
  1433. using (Logger.CreateCallstackAndLock())
  1434. {
  1435. CheckOpened();
  1436. string sourceArgument = Tools.ArgumentEscape(RemotePath.EscapeFileMask(sourcePath));
  1437. string targetArgument = Tools.ArgumentEscape(targetPath);
  1438. string command = string.Format(CultureInfo.InvariantCulture, "cp \"{0}\" \"{1}\"", sourceArgument, targetArgument);
  1439. WriteCommand(command);
  1440. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1441. {
  1442. if (!groupReader.TryWaitForNonEmptyElement("cp", LogReadFlags.ThrowFailures))
  1443. {
  1444. throw Logger.WriteException(new SessionRemoteException(this, string.Format(CultureInfo.CurrentCulture, "{0} not found.", sourcePath)));
  1445. }
  1446. else
  1447. {
  1448. using (ElementLogReader cpReader = groupReader.CreateLogReader())
  1449. {
  1450. ReadElement(cpReader, 0);
  1451. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1452. }
  1453. }
  1454. }
  1455. }
  1456. }
  1457. [Obsolete("Use RemotePath.EscapeFileMask")]
  1458. public string EscapeFileMask(string fileMask)
  1459. {
  1460. return RemotePath.EscapeFileMask(fileMask);
  1461. }
  1462. [Obsolete("Use RemotePath.TranslateRemotePathToLocal")]
  1463. public string TranslateRemotePathToLocal(string remotePath, string remoteRoot, string localRoot)
  1464. {
  1465. return RemotePath.TranslateRemotePathToLocal(remotePath, remoteRoot, localRoot);
  1466. }
  1467. [Obsolete("Use RemotePath.TranslateLocalPathToRemote")]
  1468. public string TranslateLocalPathToRemote(string localPath, string localRoot, string remoteRoot)
  1469. {
  1470. return RemotePath.TranslateLocalPathToRemote(localPath, localRoot, remoteRoot);
  1471. }
  1472. [Obsolete("Use RemotePath.CombinePaths")]
  1473. public string CombinePaths(string path1, string path2)
  1474. {
  1475. return RemotePath.Combine(path1, path2);
  1476. }
  1477. public void AddRawConfiguration(string setting, string value)
  1478. {
  1479. CheckNotOpened();
  1480. RawConfiguration.Add(setting, value);
  1481. }
  1482. #if !NETSTANDARD
  1483. [ComRegisterFunction]
  1484. private static void ComRegister(Type t)
  1485. {
  1486. string subKey = GetTypeLibKey(t);
  1487. Assembly assembly = Assembly.GetAssembly(t);
  1488. object[] attributes = assembly.GetCustomAttributes(typeof(GuidAttribute), false);
  1489. if (attributes.Length == 0)
  1490. {
  1491. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Cannot find {0} attribute for assembly {1}", typeof(GuidAttribute), assembly));
  1492. }
  1493. GuidAttribute guidAttribute = (GuidAttribute)attributes[0];
  1494. Registry.ClassesRoot.CreateSubKey(subKey).SetValue(null, guidAttribute.Value);
  1495. }
  1496. [ComUnregisterFunction]
  1497. private static void ComUnregister(Type t)
  1498. {
  1499. string subKey = GetTypeLibKey(t);
  1500. Registry.ClassesRoot.DeleteSubKey(subKey, false);
  1501. }
  1502. #endif
  1503. private void ReadFile(RemoteFileInfo fileInfo, CustomLogReader fileReader)
  1504. {
  1505. using (Logger.CreateCallstack())
  1506. {
  1507. if (fileReader.GetEmptyElementValue("type", out string value))
  1508. {
  1509. fileInfo.FileType = value[0];
  1510. }
  1511. else if (fileReader.GetEmptyElementValue("size", out value))
  1512. {
  1513. fileInfo.Length = long.Parse(value, CultureInfo.InvariantCulture);
  1514. }
  1515. else if (fileReader.GetEmptyElementValue("modification", out value))
  1516. {
  1517. fileInfo.LastWriteTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Local);
  1518. }
  1519. else if (fileReader.GetEmptyElementValue("permissions", out value))
  1520. {
  1521. fileInfo.FilePermissions = FilePermissions.CreateReadOnlyFromText(value);
  1522. }
  1523. else if (fileReader.GetEmptyElementValue("owner", out value))
  1524. {
  1525. fileInfo.Owner = value;
  1526. }
  1527. else if (fileReader.GetEmptyElementValue("group", out value))
  1528. {
  1529. fileInfo.Group = value;
  1530. }
  1531. }
  1532. }
  1533. internal static string BooleanSwitch(bool flag, string name)
  1534. {
  1535. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", name) : null;
  1536. }
  1537. internal static string BooleanSwitch(bool flag, string onName, string offName)
  1538. {
  1539. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", onName) : string.Format(CultureInfo.InvariantCulture, "-{0}", offName);
  1540. }
  1541. private void AddSynchronizationTransfer(SynchronizationResult result, TransferEventArgs transfer)
  1542. {
  1543. if (transfer != null)
  1544. {
  1545. if (transfer.Side == ProgressSide.Local)
  1546. {
  1547. result.AddUpload(transfer);
  1548. }
  1549. else
  1550. {
  1551. result.AddDownload(transfer);
  1552. }
  1553. RaiseFileTransferredEvent(transfer);
  1554. }
  1555. }
  1556. private static string IncludeTrailingSlash(string path)
  1557. {
  1558. if (!string.IsNullOrEmpty(path) && !path.EndsWith("/", StringComparison.Ordinal))
  1559. {
  1560. path += '/';
  1561. }
  1562. return path;
  1563. }
  1564. private void Cleanup()
  1565. {
  1566. using (Logger.CreateCallstack())
  1567. {
  1568. if (_process != null)
  1569. {
  1570. Logger.WriteLine("Terminating process");
  1571. try
  1572. {
  1573. try
  1574. {
  1575. WriteCommand("exit");
  1576. _process.Close();
  1577. }
  1578. finally
  1579. {
  1580. _process.Dispose();
  1581. _process = null;
  1582. }
  1583. }
  1584. catch (Exception e)
  1585. {
  1586. Logger.WriteLine("Process cleanup Exception: {0}", e);
  1587. }
  1588. }
  1589. Logger.WriteLine("Disposing log readers");
  1590. if (_reader != null)
  1591. {
  1592. _reader.Dispose();
  1593. _reader = null;
  1594. }
  1595. if (_logReader != null)
  1596. {
  1597. _logReader.Dispose();
  1598. _logReader = null;
  1599. }
  1600. // Cleanup log file
  1601. if ((XmlLogPath != null) && File.Exists(XmlLogPath) && !XmlLogPreserve)
  1602. {
  1603. Logger.WriteLine("Deleting XML log file [{0}]", XmlLogPath);
  1604. try
  1605. {
  1606. File.Delete(XmlLogPath);
  1607. }
  1608. catch (DirectoryNotFoundException e)
  1609. {
  1610. Logger.WriteLine("XML log cleanup DirectoryNotFoundException: {0}", e);
  1611. }
  1612. catch (IOException e)
  1613. {
  1614. Logger.WriteLine("XML log cleanup IOException: {0}", e);
  1615. }
  1616. catch (UnauthorizedAccessException e)
  1617. {
  1618. Logger.WriteLine("XML log cleanup UnauthorizedAccessException: {0}", e);
  1619. }
  1620. _xmlLogPath = null;
  1621. }
  1622. }
  1623. }
  1624. private void WriteCommand(string command)
  1625. {
  1626. WriteCommand(command, command);
  1627. }
  1628. private void WriteCommand(string command, string log)
  1629. {
  1630. Logger.WriteLine("Command: [{0}]", log);
  1631. _process.ExecuteCommand(command, log);
  1632. GotOutput();
  1633. }
  1634. private static void ReadElement(CustomLogReader reader, LogReadFlags flags)
  1635. {
  1636. while (reader.Read(flags))
  1637. {
  1638. }
  1639. }
  1640. private void SessionOptionsToUrlAndSwitches(SessionOptions sessionOptions, bool scanFingerprint, out string command, out string log)
  1641. {
  1642. using (Logger.CreateCallstack())
  1643. {
  1644. if (sessionOptions.WebdavSecure)
  1645. {
  1646. if (sessionOptions.Protocol != Protocol.Webdav)
  1647. {
  1648. throw Logger.WriteException(new ArgumentException("SessionOptions.WebdavSecure is set, but SessionOptions.Protocol is not Protocol.Webdav."));
  1649. }
  1650. }
  1651. string head;
  1652. switch (sessionOptions.Protocol)
  1653. {
  1654. case Protocol.Sftp:
  1655. head = "sftp://";
  1656. break;
  1657. case Protocol.Scp:
  1658. head = "scp://";
  1659. break;
  1660. case Protocol.Ftp:
  1661. head = "ftp://";
  1662. break;
  1663. case Protocol.Webdav:
  1664. if (!sessionOptions.WebdavSecure)
  1665. {
  1666. head = "dav://";
  1667. }
  1668. else
  1669. {
  1670. head = "davs://";
  1671. }
  1672. break;
  1673. case Protocol.S3:
  1674. head = "s3://";
  1675. break;
  1676. default:
  1677. throw Logger.WriteException(new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.Protocol)));
  1678. }
  1679. bool hasUsername;
  1680. if (!scanFingerprint)
  1681. {
  1682. hasUsername = !string.IsNullOrEmpty(sessionOptions.UserName);
  1683. if (hasUsername)
  1684. {
  1685. head += UriEscape(sessionOptions.UserName);
  1686. }
  1687. }
  1688. else
  1689. {
  1690. hasUsername = false;
  1691. }
  1692. string url = head;
  1693. string logUrl = head;
  1694. if ((sessionOptions.SecurePassword != null) && !scanFingerprint)
  1695. {
  1696. if (!hasUsername)
  1697. {
  1698. throw Logger.WriteException(new ArgumentException("SessionOptions.Password is set, but SessionOptions.UserName is not."));
  1699. }
  1700. url += ":" + UriEscape(sessionOptions.Password);
  1701. logUrl += ":***";
  1702. }
  1703. string tail = string.Empty;
  1704. if (hasUsername)
  1705. {
  1706. tail += "@";
  1707. }
  1708. if (string.IsNullOrEmpty(sessionOptions.HostName))
  1709. {
  1710. throw Logger.WriteException(new ArgumentException("SessionOptions.HostName is not set."));
  1711. }
  1712. // We should wrap IPv6 literals to square brackets, instead of URL-encoding them,
  1713. // but it works anyway...
  1714. tail += UriEscape(sessionOptions.HostName);
  1715. if (sessionOptions.PortNumber != 0)
  1716. {
  1717. tail += ":" + sessionOptions.PortNumber.ToString(CultureInfo.InvariantCulture);
  1718. }
  1719. if (!string.IsNullOrEmpty(sessionOptions.RootPath) && !scanFingerprint)
  1720. {
  1721. if ((sessionOptions.Protocol != Protocol.Webdav) && (sessionOptions.Protocol != Protocol.S3))
  1722. {
  1723. throw Logger.WriteException(new ArgumentException("SessionOptions.RootPath is set, but SessionOptions.Protocol is not Protocol.Webdav nor Protocol.S3."));
  1724. }
  1725. tail += sessionOptions.RootPath;
  1726. }
  1727. url += tail;
  1728. logUrl += tail;
  1729. SessionOptionsToSwitches(sessionOptions, scanFingerprint, out string arguments, out string logArguments);
  1730. const string switchName = "-rawsettings";
  1731. Tools.AddRawParameters(ref arguments, sessionOptions.RawSettings, switchName, false);
  1732. Tools.AddRawParameters(ref logArguments, sessionOptions.RawSettings, switchName, false);
  1733. if (!string.IsNullOrEmpty(arguments))
  1734. {
  1735. arguments = " " + arguments;
  1736. logArguments = " " + logArguments;
  1737. }
  1738. // Switches should (and particularly the -rawsettings MUST) come after the URL
  1739. command = "\"" + Tools.ArgumentEscape(url) + "\"" + arguments;
  1740. log = "\"" + Tools.ArgumentEscape(logUrl) + "\"" + logArguments;
  1741. }
  1742. }
  1743. private void SessionOptionsToSwitches(SessionOptions sessionOptions, bool scanFingerprint, out string arguments, out string logArguments)
  1744. {
  1745. using (Logger.CreateCallstack())
  1746. {
  1747. List<string> switches = new List<string>();
  1748. if (!string.IsNullOrEmpty(sessionOptions.SshHostKeyFingerprint) ||
  1749. ((sessionOptions.SshHostKeyPolicy != SshHostKeyPolicy.Check) && !scanFingerprint))
  1750. {
  1751. if (!sessionOptions.IsSsh)
  1752. {
  1753. 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."));
  1754. }
  1755. string sshHostKeyFingerprint = sessionOptions.SshHostKeyFingerprint;
  1756. switch (sessionOptions.SshHostKeyPolicy)
  1757. {
  1758. case SshHostKeyPolicy.Check:
  1759. // noop
  1760. break;
  1761. case SshHostKeyPolicy.GiveUpSecurityAndAcceptAny:
  1762. sshHostKeyFingerprint = AddStarToList(sshHostKeyFingerprint);
  1763. Logger.WriteLine("WARNING! Giving up security and accepting any key as configured");
  1764. break;
  1765. case SshHostKeyPolicy.AcceptNew:
  1766. if (!string.IsNullOrEmpty(sshHostKeyFingerprint))
  1767. {
  1768. throw Logger.WriteException(new ArgumentException("SessionOptions.SshHostKeyFingerprint is set and SshHostKeyPolicy is not Check"));
  1769. }
  1770. sshHostKeyFingerprint = "acceptnew";
  1771. break;
  1772. }
  1773. switches.Add(FormatSwitch("hostkey", sshHostKeyFingerprint));
  1774. }
  1775. else
  1776. {
  1777. if (sessionOptions.IsSsh && DefaultConfigurationInternal && !scanFingerprint)
  1778. {
  1779. throw Logger.WriteException(new ArgumentException("SessionOptions.Protocol is Protocol.Sftp or Protocol.Scp, but SessionOptions.SshHostKeyFingerprint is not set."));
  1780. }
  1781. }
  1782. if (!string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath) && !scanFingerprint)
  1783. {
  1784. if (!sessionOptions.IsSsh)
  1785. {
  1786. throw Logger.WriteException(new ArgumentException("SessionOptions.SshPrivateKeyPath is set, but SessionOptions.Protocol is neither Protocol.Sftp nor Protocol.Scp."));
  1787. }
  1788. switches.Add(FormatSwitch("privatekey", sessionOptions.SshPrivateKeyPath));
  1789. }
  1790. if (!string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath) && !scanFingerprint)
  1791. {
  1792. if (!sessionOptions.IsTls)
  1793. {
  1794. throw Logger.WriteException(new ArgumentException("SessionOptions.TlsClientCertificatePath is set, but neither SessionOptions.FtpSecure nor SessionOptions.WebdavSecure is enabled nor is the protocol S3."));
  1795. }
  1796. switches.Add(FormatSwitch("clientcert", sessionOptions.TlsClientCertificatePath));
  1797. }
  1798. if (sessionOptions.FtpSecure != FtpSecure.None)
  1799. {
  1800. if (sessionOptions.Protocol != Protocol.Ftp)
  1801. {
  1802. throw Logger.WriteException(new ArgumentException("SessionOptions.FtpSecure is not FtpSecure.None, but SessionOptions.Protocol is not Protocol.Ftp."));
  1803. }
  1804. switch (sessionOptions.FtpSecure)
  1805. {
  1806. case FtpSecure.Implicit:
  1807. switches.Add(FormatSwitch("implicit"));
  1808. break;
  1809. case FtpSecure.Explicit:
  1810. switches.Add(FormatSwitch("explicit"));
  1811. break;
  1812. default:
  1813. throw Logger.WriteException(new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.FtpSecure)));
  1814. }
  1815. }
  1816. if ((!string.IsNullOrEmpty(sessionOptions.TlsHostCertificateFingerprint) ||
  1817. sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate) &&
  1818. !scanFingerprint)
  1819. {
  1820. if (!sessionOptions.IsTls)
  1821. {
  1822. 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."));
  1823. }
  1824. string tlsHostCertificateFingerprint = sessionOptions.TlsHostCertificateFingerprint;
  1825. if (sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
  1826. {
  1827. Logger.WriteLine("WARNING! Giving up security and accepting any certificate as configured");
  1828. tlsHostCertificateFingerprint = AddStarToList(tlsHostCertificateFingerprint);
  1829. }
  1830. switches.Add(FormatSwitch("certificate", tlsHostCertificateFingerprint));
  1831. }
  1832. if ((sessionOptions.Protocol == Protocol.Ftp) && !scanFingerprint)
  1833. {
  1834. switches.Add(FormatSwitch("passive", (sessionOptions.FtpMode == FtpMode.Passive)));
  1835. }
  1836. switches.Add(FormatSwitch("timeout", (int)sessionOptions.Timeout.TotalSeconds));
  1837. List<string> logSwitches = new List<string>(switches);
  1838. if ((sessionOptions.SecurePrivateKeyPassphrase != null) && !scanFingerprint)
  1839. {
  1840. if (string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath) && string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath))
  1841. {
  1842. throw Logger.WriteException(new ArgumentException("SessionOptions.PrivateKeyPassphrase is set, but neither SessionOptions.SshPrivateKeyPath nor SessionOptions.TlsClientCertificatePath is set."));
  1843. }
  1844. switches.Add(FormatSwitch("passphrase", sessionOptions.PrivateKeyPassphrase));
  1845. logSwitches.Add(FormatSwitch("passphrase", "***"));
  1846. }
  1847. if ((sessionOptions.SecureNewPassword != null) && !scanFingerprint)
  1848. {
  1849. if (sessionOptions.SecurePassword == null)
  1850. {
  1851. throw Logger.WriteException(new ArgumentException("SessionOptions.SecureNewPassword is set, but SessionOptions.SecurePassword is not."));
  1852. }
  1853. switches.Add(FormatSwitch("newpassword", sessionOptions.NewPassword));
  1854. logSwitches.Add(FormatSwitch("newpassword", "***"));
  1855. }
  1856. arguments = string.Join(" ", switches.ToArray());
  1857. logArguments = string.Join(" ", logSwitches.ToArray());
  1858. }
  1859. }
  1860. private static string AddStarToList(string list)
  1861. {
  1862. return (string.IsNullOrEmpty(list) ? string.Empty : list + ";") + "*";
  1863. }
  1864. private RemoteFileInfo DoGetFileInfo(string path)
  1865. {
  1866. using (Logger.CreateCallstack())
  1867. {
  1868. WriteCommand(string.Format(CultureInfo.InvariantCulture, "stat -- \"{0}\"", Tools.ArgumentEscape(path)));
  1869. RemoteFileInfo fileInfo = new RemoteFileInfo();
  1870. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1871. using (ElementLogReader statReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("stat", LogReadFlags.ThrowFailures))
  1872. {
  1873. while (statReader.Read(0))
  1874. {
  1875. if (statReader.GetEmptyElementValue("filename", out string value))
  1876. {
  1877. string name = value;
  1878. int p = name.LastIndexOf('/');
  1879. if (p >= 0)
  1880. {
  1881. name = name.Substring(p + 1);
  1882. }
  1883. fileInfo.Name = name;
  1884. fileInfo.FullName = value;
  1885. }
  1886. else if (statReader.IsNonEmptyElement("file"))
  1887. {
  1888. using (ElementLogReader fileReader = statReader.CreateLogReader())
  1889. {
  1890. while (fileReader.Read(0))
  1891. {
  1892. ReadFile(fileInfo, fileReader);
  1893. }
  1894. }
  1895. }
  1896. }
  1897. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1898. }
  1899. return fileInfo;
  1900. }
  1901. }
  1902. internal static string FormatSwitch(string key)
  1903. {
  1904. return string.Format(CultureInfo.InvariantCulture, "-{0}", key);
  1905. }
  1906. internal static string FormatSwitch(string key, string value)
  1907. {
  1908. return string.Format(CultureInfo.InvariantCulture, "-{0}=\"{1}\"", key, Tools.ArgumentEscape(value));
  1909. }
  1910. internal static string FormatSwitch(string key, int value)
  1911. {
  1912. return string.Format(CultureInfo.InvariantCulture, "-{0}={1}", key, value.ToString(CultureInfo.InvariantCulture));
  1913. }
  1914. internal static string FormatSwitch(string key, bool value)
  1915. {
  1916. return FormatSwitch(key, (value ? 1 : 0));
  1917. }
  1918. private static string UriEscape(string s)
  1919. {
  1920. return Uri.EscapeDataString(s);
  1921. }
  1922. internal void GotOutput()
  1923. {
  1924. _lastOutput = DateTime.Now;
  1925. }
  1926. private void ProcessOutputDataReceived(object sender, OutputDataReceivedEventArgs e)
  1927. {
  1928. if (e == null)
  1929. {
  1930. Logger.WriteLine("Got incomplete progress output");
  1931. }
  1932. else
  1933. {
  1934. Logger.WriteLine("Scheduling output: [{0}]", e.Data);
  1935. string s = e.Data.TrimEnd(new[] { '\r' });
  1936. lock (Output)
  1937. {
  1938. Output.InternalAdd(s);
  1939. if (Output.Count > 1000)
  1940. {
  1941. Output.InternalRemoveFirst();
  1942. }
  1943. if (e.Error)
  1944. {
  1945. _error.InternalAdd(s);
  1946. if (_error.Count > 1000)
  1947. {
  1948. _error.InternalRemoveFirst();
  1949. }
  1950. }
  1951. }
  1952. ScheduleEvent(() => RaiseOutputDataReceived(e.Data, e.Error));
  1953. }
  1954. GotOutput();
  1955. }
  1956. private void ScheduleEvent(Action action)
  1957. {
  1958. lock (_events)
  1959. {
  1960. _events.Add(action);
  1961. _eventsEvent.Set();
  1962. }
  1963. }
  1964. internal void CheckForTimeout(string additional = null)
  1965. {
  1966. TimeSpan timeout = Timeout;
  1967. if (timeout < _sessionTimeout)
  1968. {
  1969. timeout = _sessionTimeout + TimeSpan.FromSeconds(1);
  1970. }
  1971. if (DateTime.Now - _lastOutput > timeout)
  1972. {
  1973. Logger.WriteLine("Timeout waiting for WinSCP to respond - asking for callstack");
  1974. _process.RequestCallstack();
  1975. string message = "Timeout waiting for WinSCP to respond";
  1976. if (additional != null)
  1977. {
  1978. message += " - " + additional;
  1979. }
  1980. if (_logReader != null)
  1981. {
  1982. _logReader.SetTimeouted();
  1983. }
  1984. throw Logger.WriteException(new TimeoutException(message));
  1985. }
  1986. if (_aborted)
  1987. {
  1988. throw Logger.WriteException(new SessionLocalException(this, "Aborted."));
  1989. }
  1990. if ((_process.StdOut != null) && _process.StdOut.ReadAvailable(1))
  1991. {
  1992. throw new StdOutException();
  1993. }
  1994. }
  1995. private void RaiseFileTransferredEvent(TransferEventArgs args)
  1996. {
  1997. Logger.WriteLine("FileTransferredEvent: [{0}]", args.FileName);
  1998. FileTransferred?.Invoke(this, args);
  1999. }
  2000. internal void RaiseFailed(SessionRemoteException e)
  2001. {
  2002. Logger.WriteLine("Failed: [{0}]", e);
  2003. if ((Failed != null) && !_ignoreFailed)
  2004. {
  2005. Failed(this, new FailedEventArgs { Error = e });
  2006. }
  2007. foreach (OperationResultBase operationResult in _operationResults)
  2008. {
  2009. operationResult.AddFailure(e);
  2010. }
  2011. }
  2012. private void CheckNotDisposed()
  2013. {
  2014. if (_disposed)
  2015. {
  2016. throw Logger.WriteException(new InvalidOperationException("Object is disposed"));
  2017. }
  2018. if (_aborted)
  2019. {
  2020. throw Logger.WriteException(new InvalidOperationException("Session was aborted"));
  2021. }
  2022. }
  2023. private void CheckOpened()
  2024. {
  2025. if (!Opened)
  2026. {
  2027. throw Logger.WriteException(new InvalidOperationException("Session is not opened"));
  2028. }
  2029. }
  2030. private void CheckNotOpened()
  2031. {
  2032. if (Opened)
  2033. {
  2034. throw Logger.WriteException(new InvalidOperationException("Session is already opened"));
  2035. }
  2036. }
  2037. private void RaiseOutputDataReceived(string data, bool error)
  2038. {
  2039. Logger.WriteLine("Output: [{0}]", data);
  2040. OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(data, error));
  2041. }
  2042. internal void DispatchEvents(int interval)
  2043. {
  2044. DateTime start = DateTime.Now;
  2045. while (_eventsEvent.WaitOne(interval, false))
  2046. {
  2047. lock (_events)
  2048. {
  2049. foreach (Action action in _events)
  2050. {
  2051. action();
  2052. }
  2053. _events.Clear();
  2054. }
  2055. interval -= (int) (DateTime.Now - start).TotalMilliseconds;
  2056. if (interval < 0)
  2057. {
  2058. break;
  2059. }
  2060. start = DateTime.Now;
  2061. }
  2062. }
  2063. private IDisposable RegisterOperationResult(OperationResultBase operationResult)
  2064. {
  2065. _operationResults.Add(operationResult);
  2066. return new OperationResultGuard(this, operationResult);
  2067. }
  2068. internal void UnregisterOperationResult(OperationResultBase operationResult)
  2069. {
  2070. // GetFile relies on this not to throw
  2071. _operationResults.Remove(operationResult);
  2072. }
  2073. internal bool WantsProgress
  2074. {
  2075. get
  2076. {
  2077. return (_fileTransferProgress != null);
  2078. }
  2079. }
  2080. private IDisposable CreateProgressHandler()
  2081. {
  2082. using (Logger.CreateCallstack())
  2083. {
  2084. _progressHandling++;
  2085. return new ProgressHandler(this);
  2086. }
  2087. }
  2088. internal void DisableProgressHandling()
  2089. {
  2090. using (Logger.CreateCallstack())
  2091. {
  2092. if (_progressHandling <= 0)
  2093. {
  2094. throw Logger.WriteException(new InvalidOperationException("Progress handling not enabled"));
  2095. }
  2096. // make sure we process all pending progress events
  2097. DispatchEvents(0);
  2098. _progressHandling--;
  2099. }
  2100. }
  2101. internal void ProcessChoice(QueryReceivedEventArgs args)
  2102. {
  2103. if (_queryReceived != null) // optimization
  2104. {
  2105. _choiceEvent.Reset();
  2106. ScheduleEvent(() => Choice(args));
  2107. _choiceEvent.WaitOne();
  2108. }
  2109. }
  2110. private void Choice(QueryReceivedEventArgs args)
  2111. {
  2112. _queryReceived?.Invoke(this, args);
  2113. _choiceEvent.Set();
  2114. }
  2115. internal void ProcessProgress(FileTransferProgressEventArgs args)
  2116. {
  2117. ScheduleEvent(() => Progress(args));
  2118. }
  2119. private void Progress(FileTransferProgressEventArgs args)
  2120. {
  2121. if ((_progressHandling >= 0) && WantsProgress)
  2122. {
  2123. _fileTransferProgress(this, args);
  2124. if (args.Cancel)
  2125. {
  2126. _process.Cancel();
  2127. }
  2128. }
  2129. }
  2130. private void SetupTempPath()
  2131. {
  2132. using (Logger.CreateCallstack())
  2133. {
  2134. if (!string.IsNullOrEmpty(_xmlLogPath))
  2135. {
  2136. bool exists = File.Exists(_xmlLogPath);
  2137. Logger.WriteLine("Configured temporary file: {0} - Exists [{1}]", _xmlLogPath, exists);
  2138. if (exists)
  2139. {
  2140. throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Configured temporary file {0} already exists", _xmlLogPath)));
  2141. }
  2142. }
  2143. else
  2144. {
  2145. string path = Path.GetTempPath();
  2146. Logger.WriteLine("Temporary folder: {0}", path);
  2147. string process = Process.GetCurrentProcess().Id.ToString("X4", CultureInfo.InvariantCulture);
  2148. string instance = GetHashCode().ToString("X8", CultureInfo.InvariantCulture);
  2149. string filename;
  2150. bool exists;
  2151. do
  2152. {
  2153. string uniqueStr = (_logUnique > 0 ? "." + _logUnique.ToString(CultureInfo.InvariantCulture) : string.Empty);
  2154. ++_logUnique;
  2155. filename = Path.Combine(path, "wscp" + process + "." + instance + uniqueStr + ".tmp");
  2156. exists = File.Exists(filename);
  2157. Logger.WriteLine("Temporary file [{0}] - Exists [{1}]", filename, exists);
  2158. }
  2159. while (exists);
  2160. _xmlLogPath = filename;
  2161. }
  2162. }
  2163. }
  2164. private static string GetTypeLibKey(Type t)
  2165. {
  2166. return "CLSID\\{" + t.GUID.ToString().ToUpperInvariant() + "}\\TypeLib";
  2167. }
  2168. FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
  2169. {
  2170. using (Logger.CreateCallstack())
  2171. {
  2172. Logger.WriteLine("Name [{0}]", name);
  2173. FieldInfo result = GetType().GetField(name, bindingAttr);
  2174. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2175. return result;
  2176. }
  2177. }
  2178. FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
  2179. {
  2180. using (Logger.CreateCallstack())
  2181. {
  2182. FieldInfo[] result = GetType().GetFields(bindingAttr);
  2183. Logger.WriteLine("Fields [{0}]", result.Length);
  2184. return result;
  2185. }
  2186. }
  2187. MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
  2188. {
  2189. using (Logger.CreateCallstack())
  2190. {
  2191. Logger.WriteLine("Name [{0}]", name);
  2192. MemberInfo[] result = GetType().GetMember(name, bindingAttr);
  2193. Logger.WriteLine("Result [{0}]", result.Length);
  2194. return result;
  2195. }
  2196. }
  2197. MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
  2198. {
  2199. using (Logger.CreateCallstack())
  2200. {
  2201. MemberInfo[] result = GetType().GetMembers(bindingAttr);
  2202. Logger.WriteLine("Result [{0}]", result.Length);
  2203. return result;
  2204. }
  2205. }
  2206. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
  2207. {
  2208. using (Logger.CreateCallstack())
  2209. {
  2210. Logger.WriteLine("Name [{0}]", name);
  2211. MethodInfo result = GetType().GetMethod(name, bindingAttr);
  2212. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2213. return result;
  2214. }
  2215. }
  2216. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
  2217. {
  2218. using (Logger.CreateCallstack())
  2219. {
  2220. Logger.WriteLine("Name [{0}]", name);
  2221. MethodInfo result = GetType().GetMethod(name, bindingAttr, binder, types, modifiers);
  2222. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2223. return result;
  2224. }
  2225. }
  2226. MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
  2227. {
  2228. using (Logger.CreateCallstack())
  2229. {
  2230. MethodInfo[] result = GetType().GetMethods(bindingAttr);
  2231. Logger.WriteLine("Result [{0}]", result.Length);
  2232. return result;
  2233. }
  2234. }
  2235. PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
  2236. {
  2237. using (Logger.CreateCallstack())
  2238. {
  2239. PropertyInfo[] result = GetType().GetProperties(bindingAttr);
  2240. Logger.WriteLine("Result [{0}]", result.Length);
  2241. return result;
  2242. }
  2243. }
  2244. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
  2245. {
  2246. using (Logger.CreateCallstack())
  2247. {
  2248. Logger.WriteLine("Name [{0}]", name);
  2249. PropertyInfo result = GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
  2250. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2251. return result;
  2252. }
  2253. }
  2254. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
  2255. {
  2256. using (Logger.CreateCallstack())
  2257. {
  2258. Logger.WriteLine("Name [{0}]", name);
  2259. PropertyInfo result = GetType().GetProperty(name, bindingAttr);
  2260. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2261. return result;
  2262. }
  2263. }
  2264. private void LogInvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  2265. {
  2266. Logger.WriteLine("Name [{0}]", name);
  2267. Logger.WriteLine("BindingFlags [{0}]", invokeAttr);
  2268. Logger.WriteLine("Binder [{0}]", binder);
  2269. Logger.WriteLine("Target [{0}]", target);
  2270. if (args != null)
  2271. {
  2272. Logger.WriteLine("Args [{0}] [{1}]", args.Length, modifiers != null ? modifiers.Length.ToString(CultureInfo.InvariantCulture) : "null");
  2273. for (int i = 0; i < args.Length; ++i)
  2274. {
  2275. Logger.WriteLine("Arg [{0}] [{1}] [{1}] [{2}]", i, args[i], (args[i] != null ? args[i].GetType().ToString() : "null"), (modifiers != null ? modifiers[i].ToString() : "null"));
  2276. }
  2277. }
  2278. Logger.WriteLine("Culture [{0}]", culture);
  2279. if (namedParameters != null)
  2280. {
  2281. foreach (string namedParameter in namedParameters)
  2282. {
  2283. Logger.WriteLine("NamedParameter [{0}]", namedParameter);
  2284. }
  2285. }
  2286. }
  2287. object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  2288. {
  2289. using (Logger.CreateCallstack())
  2290. {
  2291. object result;
  2292. try
  2293. {
  2294. bool wasLogging = Logger.Logging;
  2295. if (wasLogging)
  2296. {
  2297. // factored out to reduce this method complexity
  2298. LogInvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  2299. }
  2300. if (target == null)
  2301. {
  2302. throw Logger.WriteException(new ArgumentNullException(nameof(target)));
  2303. }
  2304. Type type = target.GetType();
  2305. // RuntimeType.InvokeMember below calls into Binder.BindToMethod (Binder is OleAutBinder)
  2306. // that fails to match method, if integer value is provided to enum argument
  2307. // (SynchronizeDirectories with its SynchronizationMode and SynchronizationCriteria).
  2308. // This does not happen if we do not implement IReflect, though no idea why.
  2309. // So as a workaround we check, if the method has no overloads (what is always true for Session),
  2310. // and call the only instance directly.
  2311. // Calling MethodInfo.Invoke with int values for enum arguments works.
  2312. // Only as a fallback, we call InvokeMember (what is currently actually used only when
  2313. // the method with given name does not exist at all)
  2314. MethodInfo method = null;
  2315. PropertyInfo property = null;
  2316. // would be way too difficult to implement the below involving named arguments
  2317. if (namedParameters == null)
  2318. {
  2319. try
  2320. {
  2321. BindingFlags bindingFlags = invokeAttr | BindingFlags.Instance | BindingFlags.Public;
  2322. method = type.GetMethod(name, bindingFlags);
  2323. if (args == null)
  2324. {
  2325. throw Logger.WriteException(new ArgumentNullException(nameof(args)));
  2326. }
  2327. if (method != null)
  2328. {
  2329. // MethodInfo.Invoke does not fill-in optional arguments (contrary to RuntimeType.InvokeMember)
  2330. ParameterInfo[] parameters = method.GetParameters();
  2331. if (args.Length < parameters.Length)
  2332. {
  2333. Logger.WriteLine("Provided less parameters [{0}] than defined [{1}]", args.Length, parameters.Length);
  2334. object[] args2 = new object[parameters.Length];
  2335. for (int i = 0; i < parameters.Length; i++)
  2336. {
  2337. if (i < args.Length)
  2338. {
  2339. args2[i] = args[i];
  2340. }
  2341. else
  2342. {
  2343. if (!parameters[i].IsOptional)
  2344. {
  2345. Logger.WriteLine("Parameter [{0}] of [{1}] is not optional", i, method);
  2346. args2 = null;
  2347. break;
  2348. }
  2349. else
  2350. {
  2351. Logger.WriteLine("Adding default value [{0}] for optional parameter [{1}]", parameters[i].DefaultValue, i);
  2352. args2[i] = parameters[i].DefaultValue;
  2353. }
  2354. }
  2355. }
  2356. if (args2 != null)
  2357. {
  2358. args = args2;
  2359. }
  2360. }
  2361. }
  2362. else if (args.Length == 1) // sanity check
  2363. {
  2364. property = type.GetProperty(name, bindingFlags);
  2365. }
  2366. }
  2367. catch (AmbiguousMatchException e)
  2368. {
  2369. Logger.WriteLine("Unexpected ambiguous match [{0}]", e.Message);
  2370. }
  2371. }
  2372. if (method != null)
  2373. {
  2374. Logger.WriteLine("Invoking unambiguous method [{0}]", method);
  2375. result = method.Invoke(target, invokeAttr, binder, args, culture);
  2376. }
  2377. else if (property != null)
  2378. {
  2379. Logger.WriteLine("Setting unambiguous property [{0}]", property);
  2380. property.SetValue(target, args[0], invokeAttr, binder, null, culture);
  2381. result = null;
  2382. }
  2383. else
  2384. {
  2385. Logger.WriteLine("Invoking ambiguous/non-existing method 2 [{0}]", name);
  2386. result = type.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  2387. }
  2388. if (!wasLogging && Logger.Logging)
  2389. {
  2390. Logger.WriteLine("Invoking member {0} enabled debug logging", name);
  2391. // Might call LogInvokeMember here, but it's not really useful.
  2392. }
  2393. Logger.WriteLine("Result [{0}] [{1}]", result, (result != null ? result.GetType().ToString() : "null"));
  2394. }
  2395. catch (Exception e)
  2396. {
  2397. Logger.WriteLine("Error [{0}]", e);
  2398. throw;
  2399. }
  2400. return result;
  2401. }
  2402. }
  2403. Type IReflect.UnderlyingSystemType
  2404. {
  2405. get { return GetType(); }
  2406. }
  2407. internal const string Namespace = "http://winscp.net/schema/session/1.0";
  2408. internal Logger Logger { get; private set; }
  2409. internal bool GuardProcessWithJobInternal { get { return _guardProcessWithJob; } set { CheckNotOpened(); _guardProcessWithJob = value; } }
  2410. internal bool TestHandlesClosedInternal { get; set; }
  2411. internal Dictionary<string, string> RawConfiguration { get; private set; }
  2412. internal bool DefaultConfigurationInternal { get { return _defaultConfiguration; } }
  2413. internal string IniFilePathInternal { get { return _iniFilePath; } }
  2414. private ExeSessionProcess _process;
  2415. private DateTime _lastOutput;
  2416. private ElementLogReader _reader;
  2417. private SessionLogReader _logReader;
  2418. private readonly IList<OperationResultBase> _operationResults;
  2419. private readonly IList<Action> _events;
  2420. private AutoResetEvent _eventsEvent;
  2421. private ManualResetEvent _choiceEvent;
  2422. private bool _disposed;
  2423. private string _executablePath;
  2424. private string _additionalExecutableArguments;
  2425. private bool _defaultConfiguration;
  2426. private bool _disableVersionCheck;
  2427. private string _iniFilePath;
  2428. private TimeSpan _reconnectTime;
  2429. private string _sessionLogPath;
  2430. private bool _aborted;
  2431. private int _logUnique;
  2432. private string _xmlLogPath;
  2433. private FileTransferProgressEventHandler _fileTransferProgress;
  2434. private int _progressHandling;
  2435. private bool _guardProcessWithJob;
  2436. private string _homePath;
  2437. #if !NETSTANDARD
  2438. private string _executableProcessUserName;
  2439. private SecureString _executableProcessPassword;
  2440. #endif
  2441. private StringCollection _error;
  2442. private bool _ignoreFailed;
  2443. private TimeSpan _sessionTimeout;
  2444. private QueryReceivedEventHandler _queryReceived;
  2445. }
  2446. }