Session.cs 81 KB

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