Session.cs 87 KB

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