Session.cs 106 KB

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