Session.cs 93 KB

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