Session.cs 119 KB

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