Session.cs 86 KB

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