Session.cs 118 KB

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